blob: 3315ab6e53ada5352d238016143a0655aff1d7d4 [file] [log] [blame]
Douglas Gregoreb11cd02009-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 Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
John McCall2d887082010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Lookup.h"
John McCall19510852010-08-20 18:27:03 +000017#include "clang/Sema/DeclSpec.h"
John McCall5f1e0942010-08-24 08:50:51 +000018#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
John McCall2a7fb272010-08-25 05:32:35 +000020#include "clang/Sema/TemplateDeduction.h"
Axel Naumannf8291a12011-02-24 16:47:47 +000021#include "clang/Sema/ExternalSemaSource.h"
Douglas Gregor7176fff2009-01-15 00:26:24 +000022#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000023#include "clang/AST/CXXInheritance.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000024#include "clang/AST/Decl.h"
25#include "clang/AST/DeclCXX.h"
26#include "clang/AST/DeclObjC.h"
Douglas Gregor42af25f2009-05-11 19:58:34 +000027#include "clang/AST/DeclTemplate.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000028#include "clang/AST/Expr.h"
Douglas Gregordaa439a2009-07-08 10:57:20 +000029#include "clang/AST/ExprCXX.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000030#include "clang/Basic/Builtins.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000031#include "clang/Basic/LangOptions.h"
John McCall50df6ae2010-08-25 07:03:20 +000032#include "llvm/ADT/DenseSet.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000033#include "llvm/ADT/STLExtras.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000034#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregore24b5752010-10-14 20:34:08 +000035#include "llvm/ADT/StringMap.h"
John McCall6e247262009-10-10 05:48:19 +000036#include "llvm/Support/ErrorHandling.h"
Douglas Gregore24b5752010-10-14 20:34:08 +000037#include <limits>
Douglas Gregor546be3c2009-12-30 17:04:44 +000038#include <list>
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +000039#include <set>
Douglas Gregor2a3009a2009-02-03 19:21:40 +000040#include <vector>
41#include <iterator>
42#include <utility>
43#include <algorithm>
Douglas Gregoreb11cd02009-01-14 22:20:51 +000044
45using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000046using namespace sema;
Douglas Gregoreb11cd02009-01-14 22:20:51 +000047
John McCalld7be78a2009-11-10 07:01:13 +000048namespace {
49 class UnqualUsingEntry {
50 const DeclContext *Nominated;
51 const DeclContext *CommonAncestor;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000052
John McCalld7be78a2009-11-10 07:01:13 +000053 public:
54 UnqualUsingEntry(const DeclContext *Nominated,
55 const DeclContext *CommonAncestor)
56 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
57 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000058
John McCalld7be78a2009-11-10 07:01:13 +000059 const DeclContext *getCommonAncestor() const {
60 return CommonAncestor;
61 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000062
John McCalld7be78a2009-11-10 07:01:13 +000063 const DeclContext *getNominatedNamespace() const {
64 return Nominated;
65 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000066
John McCalld7be78a2009-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 Gregor2a3009a2009-02-03 19:21:40 +000072
John McCalld7be78a2009-11-10 07:01:13 +000073 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
74 return E.getCommonAncestor() < DC;
75 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000076
John McCalld7be78a2009-11-10 07:01:13 +000077 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
78 return DC < E.getCommonAncestor();
79 }
80 };
81 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +000082
John McCalld7be78a2009-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 Gregor2a3009a2009-02-03 19:21:40 +000087
John McCalld7be78a2009-11-10 07:01:13 +000088 ListTy list;
89 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000090
John McCalld7be78a2009-11-10 07:01:13 +000091 public:
92 UnqualUsingDirectiveSet() {}
Douglas Gregor2a3009a2009-02-03 19:21:40 +000093
John McCalld7be78a2009-11-10 07:01:13 +000094 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000095 // C++ [namespace.udir]p1:
John McCalld7be78a2009-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 Gregor2a3009a2009-02-03 19:21:40 +0000102
John McCalld7be78a2009-11-10 07:01:13 +0000103 for (; S; S = S->getParent()) {
John McCalld7be78a2009-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 Takumidfbb02a2011-01-27 07:10:08 +0000110
John McCalld7be78a2009-11-10 07:01:13 +0000111 for (; I != End; ++I)
John McCalld226f652010-08-21 09:40:31 +0000112 visit(*I, InnermostFileDC);
John McCalld7be78a2009-11-10 07:01:13 +0000113 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000114 }
115 }
John McCalld7be78a2009-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 McCall12ea5782009-11-10 09:20:04 +0000180 Common = Common->getPrimaryContext();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000181
John McCalld7be78a2009-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 McCalld7be78a2009-11-10 07:01:13 +0000189 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000190
John McCalld7be78a2009-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 McCall12ea5782009-11-10 09:20:04 +0000196 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCalld7be78a2009-11-10 07:01:13 +0000197 UnqualUsingEntry::Comparator());
198 }
199 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000200}
201
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000202// Retrieve the set of identifier namespaces that correspond to a
203// specific kind of name lookup.
John McCall1d7c5282009-12-18 10:40:03 +0000204static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
205 bool CPlusPlus,
206 bool Redeclaration) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000207 unsigned IDNS = 0;
208 switch (NameKind) {
209 case Sema::LookupOrdinaryName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000210 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000211 IDNS = Decl::IDNS_Ordinary;
John McCall1d7c5282009-12-18 10:40:03 +0000212 if (CPlusPlus) {
John McCall0d6b1642010-04-23 18:46:30 +0000213 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattner337e5502011-02-18 01:27:55 +0000214 if (Redeclaration)
215 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCall1d7c5282009-12-18 10:40:03 +0000216 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000217 break;
218
John McCall76d32642010-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 Gregor2a3009a2009-02-03 19:21:40 +0000226 case Sema::LookupTagName:
John McCall0d6b1642010-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 Gregor2a3009a2009-02-03 19:21:40 +0000240 break;
Chris Lattner337e5502011-02-18 01:27:55 +0000241 case Sema::LookupLabel:
242 IDNS = Decl::IDNS_Label;
243 break;
244
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000245 case Sema::LookupMemberName:
246 IDNS = Decl::IDNS_Member;
247 if (CPlusPlus)
Mike Stump1eb44332009-09-09 15:08:12 +0000248 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000249 break;
250
251 case Sema::LookupNestedNameSpecifierName:
John McCall0d6b1642010-04-23 18:46:30 +0000252 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
253 break;
254
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000255 case Sema::LookupNamespaceName:
John McCall0d6b1642010-04-23 18:46:30 +0000256 IDNS = Decl::IDNS_Namespace;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000257 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000258
John McCall9f54ad42009-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 Gregor8fc463a2009-04-24 00:11:27 +0000264 case Sema::LookupObjCProtocolName:
265 IDNS = Decl::IDNS_ObjCProtocol;
266 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000267
Douglas Gregor8071e422010-08-15 06:18:01 +0000268 case Sema::LookupAnyName:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000269 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor8071e422010-08-15 06:18:01 +0000270 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
271 | Decl::IDNS_Type;
272 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000273 }
274 return IDNS;
275}
276
John McCall1d7c5282009-12-18 10:40:03 +0000277void LookupResult::configure() {
Chris Lattner337e5502011-02-18 01:27:55 +0000278 IDNS = getIDNS(LookupKind, SemaRef.getLangOptions().CPlusPlus,
John McCall1d7c5282009-12-18 10:40:03 +0000279 isForRedeclaration());
Douglas Gregorb5b2ccb2010-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 Bagnara25777432010-08-11 22:01:17 +0000285 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorb5b2ccb2010-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 McCall1d7c5282009-12-18 10:40:03 +0000297}
298
John McCall2a7fb272010-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 Gregorf17b58c2010-10-22 22:08:47 +0000307 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
308 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall2a7fb272010-08-25 05:32:35 +0000309 assert((Paths != NULL) == (ResultKind == Ambiguous &&
310 (Ambiguity == AmbiguousBaseSubobjectTypes ||
311 Ambiguity == AmbiguousBaseSubobjects)));
312}
John McCall2a7fb272010-08-25 05:32:35 +0000313
John McCallf36e02d2009-10-09 21:13:30 +0000314// Necessary because CXXBasePaths is not complete in Sema.h
John McCall7d384dd2009-11-18 07:57:50 +0000315void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCallf36e02d2009-10-09 21:13:30 +0000316 delete Paths;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000317}
318
John McCall7453ed42009-11-22 00:44:51 +0000319/// Resolves the result kind of this lookup.
John McCall7d384dd2009-11-18 07:57:50 +0000320void LookupResult::resolveKind() {
John McCallf36e02d2009-10-09 21:13:30 +0000321 unsigned N = Decls.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000322
John McCallf36e02d2009-10-09 21:13:30 +0000323 // Fast case: no possible ambiguity.
John McCall68263142009-11-18 22:49:29 +0000324 if (N == 0) {
John McCalldc5c7862010-01-15 21:27:01 +0000325 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall68263142009-11-18 22:49:29 +0000326 return;
327 }
328
John McCall7453ed42009-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 McCall7ba107a2009-11-18 02:36:19 +0000331 if (N == 1) {
Douglas Gregor2b147f02010-04-25 21:15:30 +0000332 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
333 if (isa<FunctionTemplateDecl>(D))
John McCall7453ed42009-11-22 00:44:51 +0000334 ResultKind = FoundOverloaded;
Douglas Gregor2b147f02010-04-25 21:15:30 +0000335 else if (isa<UnresolvedUsingValueDecl>(D))
John McCall7ba107a2009-11-18 02:36:19 +0000336 ResultKind = FoundUnresolvedValue;
337 return;
338 }
John McCallf36e02d2009-10-09 21:13:30 +0000339
John McCall6e247262009-10-10 05:48:19 +0000340 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000341 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000342
John McCallf36e02d2009-10-09 21:13:30 +0000343 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000344 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000345
John McCallf36e02d2009-10-09 21:13:30 +0000346 bool Ambiguous = false;
347 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000348 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000349
350 unsigned UniqueTagIndex = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000351
John McCallf36e02d2009-10-09 21:13:30 +0000352 unsigned I = 0;
353 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000354 NamedDecl *D = Decls[I]->getUnderlyingDecl();
355 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000356
Douglas Gregor7f1c5472010-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 Takumidfbb02a2011-01-27 07:10:08 +0000372
John McCall314be4e2009-11-17 07:50:12 +0000373 if (!Unique.insert(D)) {
John McCallf36e02d2009-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 Gregor7f1c5472010-08-11 14:45:53 +0000377 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000378 }
379
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000380 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000381
Douglas Gregor7f1c5472010-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 Gregor7176fff2009-01-15 00:26:24 +0000398 }
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000399 I++;
Mike Stump1eb44332009-09-09 15:08:12 +0000400 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000401
John McCallf36e02d2009-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 McCallfda8e122009-12-03 00:58:24 +0000411 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregor77a1a882010-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 Carlsson8b50d012009-06-26 03:37:05 +0000419
John McCallf36e02d2009-10-09 21:13:30 +0000420 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000421
John McCallfda8e122009-12-03 00:58:24 +0000422 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000423 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000424
John McCallf36e02d2009-10-09 21:13:30 +0000425 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000426 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000427 else if (HasUnresolved)
428 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000429 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000430 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000431 else
John McCalla24dc2e2009-11-17 02:14:36 +0000432 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000433}
434
John McCall7d384dd2009-11-18 07:57:50 +0000435void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall6b2accb2010-02-10 09:31:12 +0000436 CXXBasePaths::const_paths_iterator I, E;
John McCallf36e02d2009-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 Gregor31a19b62009-04-01 21:51:26 +0000441}
442
John McCall7d384dd2009-11-18 07:57:50 +0000443void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000444 Paths = new CXXBasePaths;
445 Paths->swap(P);
446 addDeclsFromBasePaths(*Paths);
447 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000448 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000449}
450
John McCall7d384dd2009-11-18 07:57:50 +0000451void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000452 Paths = new CXXBasePaths;
453 Paths->swap(P);
454 addDeclsFromBasePaths(*Paths);
455 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000456 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000457}
458
John McCall7d384dd2009-11-18 07:57:50 +0000459void LookupResult::print(llvm::raw_ostream &Out) {
John McCallf36e02d2009-10-09 21:13:30 +0000460 Out << Decls.size() << " result(s)";
461 if (isAmbiguous()) Out << ", ambiguous";
462 if (Paths) Out << ", base paths present";
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000463
John McCallf36e02d2009-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 Gregor85910982010-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 Takumidfbb02a2011-01-27 07:10:08 +0000489
490 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
491 BuiltinID, S.TUScope,
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000492 R.isForRedeclaration(),
493 R.getNameLoc())) {
Douglas Gregor85910982010-02-12 05:48:04 +0000494 R.addDecl(D);
Douglas Gregor6b9109e2011-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 Gregor85910982010-02-12 05:48:04 +0000505 }
506 }
507 }
508
509 return false;
510}
511
Douglas Gregor4923aa22010-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 McCallb3b50a82010-08-11 23:52:36 +0000516 // Don't do it if the class is invalid.
517 if (Class->isInvalidDecl())
518 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000519
Douglas Gregor4923aa22010-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 Takumidfbb02a2011-01-27 07:10:08 +0000523
Douglas Gregor4923aa22010-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 Takumidfbb02a2011-01-27 07:10:08 +0000528
Douglas Gregor4923aa22010-07-02 20:37:36 +0000529 return false;
530}
531
532void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregor22584312010-07-02 23:41:54 +0000533 if (!CanDeclareSpecialMemberFunction(Context, Class))
534 return;
Douglas Gregor18274032010-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 Takumidfbb02a2011-01-27 07:10:08 +0000539
Douglas Gregor22584312010-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 Takumidfbb02a2011-01-27 07:10:08 +0000543
Douglas Gregora376d102010-07-02 21:50:04 +0000544 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000545 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +0000546 DeclareImplicitCopyAssignment(Class);
547
Douglas Gregor4923aa22010-07-02 20:37:36 +0000548 // If the destructor has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000549 if (!Class->hasDeclaredDestructor())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000550 DeclareImplicitDestructor(Class);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000551}
552
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000553/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregora376d102010-07-02 21:50:04 +0000554/// special member function.
555static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
556 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000557 case DeclarationName::CXXConstructorName:
Douglas Gregora376d102010-07-02 21:50:04 +0000558 case DeclarationName::CXXDestructorName:
559 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000560
Douglas Gregora376d102010-07-02 21:50:04 +0000561 case DeclarationName::CXXOperatorName:
562 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000563
Douglas Gregora376d102010-07-02 21:50:04 +0000564 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000565 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000566 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000567
Douglas Gregora376d102010-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 Takumidfbb02a2011-01-27 07:10:08 +0000573static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregora376d102010-07-02 21:50:04 +0000574 DeclarationName Name,
575 const DeclContext *DC) {
576 if (!DC)
577 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000578
Douglas Gregora376d102010-07-02 21:50:04 +0000579 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000580 case DeclarationName::CXXConstructorName:
581 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor18274032010-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 Gregor22584312010-07-02 23:41:54 +0000590 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000591
Douglas Gregora376d102010-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 Gregora376d102010-07-02 21:50:04 +0000597 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000598
Douglas Gregora376d102010-07-02 21:50:04 +0000599 case DeclarationName::CXXOperatorName:
600 if (Name.getCXXOverloadedOperator() != OO_Equal)
601 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000602
Douglas Gregora376d102010-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 Takumidfbb02a2011-01-27 07:10:08 +0000608
Douglas Gregora376d102010-07-02 21:50:04 +0000609 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000610 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000611 }
612}
Douglas Gregor4923aa22010-07-02 20:37:36 +0000613
John McCallf36e02d2009-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 Gregor85910982010-02-12 05:48:04 +0000616static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000617 bool Found = false;
618
Douglas Gregor4923aa22010-07-02 20:37:36 +0000619 // Lazily declare C++ special member functions.
Douglas Gregora376d102010-07-02 21:50:04 +0000620 if (S.getLangOptions().CPlusPlus)
621 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000622
Douglas Gregor4923aa22010-07-02 20:37:36 +0000623 // Perform lookup into this declaration context.
John McCalld7be78a2009-11-10 07:01:13 +0000624 DeclContext::lookup_const_iterator I, E;
Douglas Gregor48026d22010-01-11 18:40:55 +0000625 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall46460a62010-01-20 21:53:11 +0000626 NamedDecl *D = *I;
627 if (R.isAcceptableDecl(D)) {
628 R.addDecl(D);
Douglas Gregor48026d22010-01-11 18:40:55 +0000629 Found = true;
630 }
631 }
John McCallf36e02d2009-10-09 21:13:30 +0000632
Douglas Gregor85910982010-02-12 05:48:04 +0000633 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
634 return true;
635
Douglas Gregor48026d22010-01-11 18:40:55 +0000636 if (R.getLookupName().getNameKind()
Chandler Carruthaaa1a892010-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 Takumidfbb02a2011-01-27 07:10:08 +0000643 // A specialization of a conversion function template is not found by
Chandler Carruthaaa1a892010-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 Takumidfbb02a2011-01-27 07:10:08 +0000651 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
Chandler Carruthaaa1a892010-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 Takumidfbb02a2011-01-27 07:10:08 +0000656
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000657 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumidfbb02a2011-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 Carruthaaa1a892010-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 Takumidfbb02a2011-01-27 07:10:08 +0000666
Douglas Gregor48026d22010-01-11 18:40:55 +0000667 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-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 Carruthaaa1a892010-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 Takumidfbb02a2011-01-27 07:10:08 +0000674 // result), perform template argument deduction and place the
Chandler Carruthaaa1a892010-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 McCall2a7fb272010-08-25 05:32:35 +0000677 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000678 FunctionDecl *Specialization = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000679
680 const FunctionProtoType *ConvProto
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000681 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
682 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3f477a12010-01-12 01:17:50 +0000683
Chandler Carruthaaa1a892010-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 McCalle23cf432010-12-14 08:05:40 +0000687 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
688 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
Sebastian Redl06bfa842011-03-05 22:42:26 +0000689 EPI.ExceptionSpecType = EST_None;
John McCalle23cf432010-12-14 08:05:40 +0000690 EPI.NumExceptions = 0;
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000691 QualType ExpectedType
692 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
John McCalle23cf432010-12-14 08:05:40 +0000693 0, 0, EPI);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000694
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000695 // Perform template argument deduction against the type that we would
696 // expect the function to have.
697 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
698 Specialization, Info)
699 == Sema::TDK_Success) {
700 R.addDecl(Specialization);
701 Found = true;
Douglas Gregor48026d22010-01-11 18:40:55 +0000702 }
703 }
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000704
John McCallf36e02d2009-10-09 21:13:30 +0000705 return Found;
706}
707
John McCalld7be78a2009-11-10 07:01:13 +0000708// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000709static bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000710CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregor85910982010-02-12 05:48:04 +0000711 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000712
713 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
714
John McCalld7be78a2009-11-10 07:01:13 +0000715 // Perform direct name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +0000716 bool Found = LookupDirect(S, R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000717
John McCalld7be78a2009-11-10 07:01:13 +0000718 // Perform direct name lookup into the namespaces nominated by the
719 // using directives whose common ancestor is this namespace.
720 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
721 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000722
John McCalld7be78a2009-11-10 07:01:13 +0000723 for (; UI != UEnd; ++UI)
Douglas Gregor85910982010-02-12 05:48:04 +0000724 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000725 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000726
727 R.resolveKind();
728
729 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000730}
731
732static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000733 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000734 return Ctx->isFileContext();
735 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000736}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000737
Douglas Gregor711be1e2010-03-15 14:33:29 +0000738// Find the next outer declaration context from this scope. This
739// routine actually returns the semantic outer context, which may
740// differ from the lexical context (encoded directly in the Scope
741// stack) when we are parsing a member of a class template. In this
742// case, the second element of the pair will be true, to indicate that
743// name lookup should continue searching in this semantic context when
744// it leaves the current template parameter scope.
745static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
746 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
747 DeclContext *Lexical = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000748 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor711be1e2010-03-15 14:33:29 +0000749 OuterS = OuterS->getParent()) {
750 if (OuterS->getEntity()) {
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000751 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor711be1e2010-03-15 14:33:29 +0000752 break;
753 }
754 }
755
756 // C++ [temp.local]p8:
757 // In the definition of a member of a class template that appears
758 // outside of the namespace containing the class template
759 // definition, the name of a template-parameter hides the name of
760 // a member of this namespace.
761 //
762 // Example:
763 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000764 // namespace N {
765 // class C { };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000766 //
767 // template<class T> class B {
768 // void f(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000769 // };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000770 // }
771 //
772 // template<class C> void N::B<C>::f(C) {
773 // C b; // C is the template parameter, not N::C
774 // }
775 //
776 // In this example, the lexical context we return is the
777 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000778 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor711be1e2010-03-15 14:33:29 +0000779 !S->getParent()->isTemplateParamScope())
780 return std::make_pair(Lexical, false);
781
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000782 // Find the outermost template parameter scope.
Douglas Gregor711be1e2010-03-15 14:33:29 +0000783 // For the example, this is the scope for the template parameters of
784 // template<class C>.
785 Scope *OutermostTemplateScope = S->getParent();
786 while (OutermostTemplateScope->getParent() &&
787 OutermostTemplateScope->getParent()->isTemplateParamScope())
788 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000789
Douglas Gregor711be1e2010-03-15 14:33:29 +0000790 // Find the namespace context in which the original scope occurs. In
791 // the example, this is namespace N.
792 DeclContext *Semantic = DC;
793 while (!Semantic->isFileContext())
794 Semantic = Semantic->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000795
Douglas Gregor711be1e2010-03-15 14:33:29 +0000796 // Find the declaration context just outside of the template
797 // parameter scope. This is the context in which the template is
798 // being lexically declaration (a namespace context). In the
799 // example, this is the global scope.
800 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
801 Lexical->Encloses(Semantic))
802 return std::make_pair(Semantic, true);
803
804 return std::make_pair(Lexical, false);
Douglas Gregore942bbe2009-09-10 16:57:35 +0000805}
806
John McCalla24dc2e2009-11-17 02:14:36 +0000807bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCall1d7c5282009-12-18 10:40:03 +0000808 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000809
810 DeclarationName Name = R.getLookupName();
811
Douglas Gregora376d102010-07-02 21:50:04 +0000812 // If this is the name of an implicitly-declared special member function,
813 // go through the scope stack to implicitly declare
814 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
815 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
816 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
817 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
818 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000819
Douglas Gregora376d102010-07-02 21:50:04 +0000820 // Implicitly declare member functions with the name we're looking for, if in
821 // fact we are in a scope where it matters.
822
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000823 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000824 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000825 I = IdResolver.begin(Name),
826 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000827
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000828 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000829 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000830 // ...During unqualified name lookup (3.4.1), the names appear as if
831 // they were declared in the nearest enclosing namespace which contains
832 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000833 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000834 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000835 //
836 // For example:
837 // namespace A { int i; }
838 // void foo() {
839 // int i;
840 // {
841 // using namespace A;
842 // ++i; // finds local 'i', A::i appears at global scope
843 // }
844 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000845 //
Douglas Gregor711be1e2010-03-15 14:33:29 +0000846 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000847 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregord2235f62010-05-20 20:58:56 +0000848 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
849
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000850 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000851 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000852 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000853 if (R.isAcceptableDecl(*I)) {
John McCallf36e02d2009-10-09 21:13:30 +0000854 Found = true;
855 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000856 }
857 }
John McCallf36e02d2009-10-09 21:13:30 +0000858 if (Found) {
859 R.resolveKind();
Douglas Gregord2235f62010-05-20 20:58:56 +0000860 if (S->isClassScope())
861 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
862 R.setNamingClass(Record);
John McCallf36e02d2009-10-09 21:13:30 +0000863 return true;
864 }
865
Douglas Gregor711be1e2010-03-15 14:33:29 +0000866 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
867 S->getParent() && !S->getParent()->isTemplateParamScope()) {
868 // We've just searched the last template parameter scope and
869 // found nothing, so look into the the contexts between the
870 // lexical and semantic declaration contexts returned by
871 // findOuterContext(). This implements the name lookup behavior
872 // of C++ [temp.local]p8.
873 Ctx = OutsideOfTemplateParamDC;
874 OutsideOfTemplateParamDC = 0;
875 }
876
877 if (Ctx) {
878 DeclContext *OuterCtx;
879 bool SearchAfterTemplateScope;
880 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
881 if (SearchAfterTemplateScope)
882 OutsideOfTemplateParamDC = OuterCtx;
883
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000884 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-02-19 16:08:35 +0000885 // We do not directly look into transparent contexts, since
886 // those entities will be found in the nearest enclosing
887 // non-transparent context.
888 if (Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000889 continue;
Douglas Gregor36262b82010-02-19 16:08:35 +0000890
891 // We do not look directly into function or method contexts,
892 // since all of the local variables and parameters of the
893 // function/method are present within the Scope.
894 if (Ctx->isFunctionOrMethod()) {
895 // If we have an Objective-C instance method, look for ivars
896 // in the corresponding interface.
897 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
898 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
899 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
900 ObjCInterfaceDecl *ClassDeclared;
901 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000902 Name.getAsIdentifierInfo(),
Douglas Gregor36262b82010-02-19 16:08:35 +0000903 ClassDeclared)) {
904 if (R.isAcceptableDecl(Ivar)) {
905 R.addDecl(Ivar);
906 R.resolveKind();
907 return true;
908 }
909 }
910 }
911 }
912
913 continue;
914 }
915
Douglas Gregore942bbe2009-09-10 16:57:35 +0000916 // Perform qualified name lookup into this context.
917 // FIXME: In some cases, we know that every name that could be found by
918 // this qualified name lookup will also be on the identifier chain. For
919 // example, inside a class without any base classes, we never need to
920 // perform qualified lookup because all of the members are on top of the
921 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000922 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +0000923 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +0000924 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000925 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000926 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000927
John McCalld7be78a2009-11-10 07:01:13 +0000928 // Stop if we ran out of scopes.
929 // FIXME: This really, really shouldn't be happening.
930 if (!S) return false;
931
Argyrios Kyrtzidis78f59112010-10-29 16:12:50 +0000932 // If we are looking for members, no need to look into global/namespace scope.
933 if (R.getLookupKind() == LookupMemberName)
934 return false;
935
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000936 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000937 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +0000938 //
Mike Stump390b4cc2009-05-16 07:39:55 +0000939 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
940 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000941
John McCalld7be78a2009-11-10 07:01:13 +0000942 UnqualUsingDirectiveSet UDirs;
943 UDirs.visitScopeChain(Initial, S);
944 UDirs.done();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000945
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000946 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000947 // Unqualified name lookup in C++ requires looking into scopes
948 // that aren't strictly lexical, and therefore we walk through the
949 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000950
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000951 for (; S; S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000952 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000953 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000954 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000955 if (R.isAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000956 // We found something. Look for anything else in our scope
957 // with this same name and in an acceptable identifier
958 // namespace, so that we can construct an overload set if we
959 // need to.
John McCallf36e02d2009-10-09 21:13:30 +0000960 Found = true;
961 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000962 }
963 }
964
Douglas Gregor00b4b032010-05-14 04:53:42 +0000965 if (Found && S->isTemplateParamScope()) {
John McCallf36e02d2009-10-09 21:13:30 +0000966 R.resolveKind();
967 return true;
968 }
969
Douglas Gregor00b4b032010-05-14 04:53:42 +0000970 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
971 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
972 S->getParent() && !S->getParent()->isTemplateParamScope()) {
973 // We've just searched the last template parameter scope and
974 // found nothing, so look into the the contexts between the
975 // lexical and semantic declaration contexts returned by
976 // findOuterContext(). This implements the name lookup behavior
977 // of C++ [temp.local]p8.
978 Ctx = OutsideOfTemplateParamDC;
979 OutsideOfTemplateParamDC = 0;
980 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000981
Douglas Gregor00b4b032010-05-14 04:53:42 +0000982 if (Ctx) {
983 DeclContext *OuterCtx;
984 bool SearchAfterTemplateScope;
985 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
986 if (SearchAfterTemplateScope)
987 OutsideOfTemplateParamDC = OuterCtx;
988
989 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
990 // We do not directly look into transparent contexts, since
991 // those entities will be found in the nearest enclosing
992 // non-transparent context.
993 if (Ctx->isTransparentContext())
994 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000995
Douglas Gregor00b4b032010-05-14 04:53:42 +0000996 // If we have a context, and it's not a context stashed in the
997 // template parameter scope for an out-of-line definition, also
998 // look into that context.
999 if (!(Found && S && S->isTemplateParamScope())) {
1000 assert(Ctx->isFileContext() &&
1001 "We should have been looking only at file context here already.");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001002
Douglas Gregor00b4b032010-05-14 04:53:42 +00001003 // Look into context considering using-directives.
1004 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1005 Found = true;
1006 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001007
Douglas Gregor00b4b032010-05-14 04:53:42 +00001008 if (Found) {
1009 R.resolveKind();
1010 return true;
1011 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001012
Douglas Gregor00b4b032010-05-14 04:53:42 +00001013 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1014 return false;
1015 }
1016 }
1017
Douglas Gregor1df0ee92010-02-05 07:07:10 +00001018 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +00001019 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001020 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001021
John McCallf36e02d2009-10-09 21:13:30 +00001022 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001023}
1024
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001025/// @brief Perform unqualified name lookup starting from a given
1026/// scope.
1027///
1028/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1029/// used to find names within the current scope. For example, 'x' in
1030/// @code
1031/// int x;
1032/// int f() {
1033/// return x; // unqualified name look finds 'x' in the global scope
1034/// }
1035/// @endcode
1036///
1037/// Different lookup criteria can find different names. For example, a
1038/// particular scope can have both a struct and a function of the same
1039/// name, and each can be found by certain lookup criteria. For more
1040/// information about lookup criteria, see the documentation for the
1041/// class LookupCriteria.
1042///
1043/// @param S The scope from which unqualified name lookup will
1044/// begin. If the lookup criteria permits, name lookup may also search
1045/// in the parent scopes.
1046///
1047/// @param Name The name of the entity that we are searching for.
1048///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001049/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001050/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001051/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001052///
1053/// @returns The result of name lookup, which includes zero or more
1054/// declarations and possibly additional information used to diagnose
1055/// ambiguities.
John McCalla24dc2e2009-11-17 02:14:36 +00001056bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1057 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +00001058 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001059
John McCalla24dc2e2009-11-17 02:14:36 +00001060 LookupNameKind NameKind = R.getLookupKind();
1061
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001062 if (!getLangOptions().CPlusPlus) {
1063 // Unqualified name lookup in C/Objective-C is purely lexical, so
1064 // search in the declarations attached to the name.
John McCall1d7c5282009-12-18 10:40:03 +00001065 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001066 // Find the nearest non-transparent declaration scope.
1067 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001068 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001069 static_cast<DeclContext *>(S->getEntity())
1070 ->isTransparentContext()))
1071 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001072 }
1073
John McCall1d7c5282009-12-18 10:40:03 +00001074 unsigned IDNS = R.getIdentifierNamespace();
1075
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001076 // Scan up the scope chain looking for a decl that matches this
1077 // identifier that is in the appropriate namespace. This search
1078 // should not take long, as shadowing of names is uncommon, and
1079 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001080 bool LeftStartingScope = false;
1081
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001082 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +00001083 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001084 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001085 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001086 if (NameKind == LookupRedeclarationWithLinkage) {
1087 // Determine whether this (or a previous) declaration is
1088 // out-of-scope.
John McCalld226f652010-08-21 09:40:31 +00001089 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001090 LeftStartingScope = true;
1091
1092 // If we found something outside of our starting scope that
1093 // does not have linkage, skip it.
1094 if (LeftStartingScope && !((*I)->hasLinkage()))
1095 continue;
1096 }
1097
John McCallf36e02d2009-10-09 21:13:30 +00001098 R.addDecl(*I);
1099
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001100 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00001101 // If this declaration has the "overloadable" attribute, we
1102 // might have a set of overloaded functions.
1103
1104 // Figure out what scope the identifier is in.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001105 while (!(S->getFlags() & Scope::DeclScope) ||
John McCalld226f652010-08-21 09:40:31 +00001106 !S->isDeclScope(*I))
Douglas Gregorf9201e02009-02-11 23:02:49 +00001107 S = S->getParent();
1108
1109 // Find the last declaration in this scope (with the same
1110 // name, naturally).
1111 IdentifierResolver::iterator LastI = I;
1112 for (++LastI; LastI != IEnd; ++LastI) {
John McCalld226f652010-08-21 09:40:31 +00001113 if (!S->isDeclScope(*LastI))
Douglas Gregorf9201e02009-02-11 23:02:49 +00001114 break;
John McCallf36e02d2009-10-09 21:13:30 +00001115 R.addDecl(*LastI);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001116 }
Douglas Gregorf9201e02009-02-11 23:02:49 +00001117 }
1118
John McCallf36e02d2009-10-09 21:13:30 +00001119 R.resolveKind();
1120
1121 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +00001122 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001123 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001124 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +00001125 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +00001126 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001127 }
1128
1129 // If we didn't find a use of this identifier, and if the identifier
1130 // corresponds to a compiler builtin, create the decl object for the builtin
1131 // now, injecting it into translation unit scope, and return it.
Douglas Gregor85910982010-02-12 05:48:04 +00001132 if (AllowBuiltinCreation)
1133 return LookupBuiltin(*this, R);
Douglas Gregor3e41d602009-02-13 23:20:09 +00001134
Axel Naumannf8291a12011-02-24 16:47:47 +00001135 // If we didn't find a use of this identifier, the ExternalSource
1136 // may be able to handle the situation.
1137 // Note: some lookup failures are expected!
1138 // See e.g. R.isForRedeclaration().
1139 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001140}
1141
John McCall6e247262009-10-10 05:48:19 +00001142/// @brief Perform qualified name lookup in the namespaces nominated by
1143/// using directives by the given context.
1144///
1145/// C++98 [namespace.qual]p2:
1146/// Given X::m (where X is a user-declared namespace), or given ::m
1147/// (where X is the global namespace), let S be the set of all
1148/// declarations of m in X and in the transitive closure of all
1149/// namespaces nominated by using-directives in X and its used
1150/// namespaces, except that using-directives are ignored in any
1151/// namespace, including X, directly containing one or more
1152/// declarations of m. No namespace is searched more than once in
1153/// the lookup of a name. If S is the empty set, the program is
1154/// ill-formed. Otherwise, if S has exactly one member, or if the
1155/// context of the reference is a using-declaration
1156/// (namespace.udecl), S is the required set of declarations of
1157/// m. Otherwise if the use of m is not one that allows a unique
1158/// declaration to be chosen from S, the program is ill-formed.
1159/// C++98 [namespace.qual]p5:
1160/// During the lookup of a qualified namespace member name, if the
1161/// lookup finds more than one declaration of the member, and if one
1162/// declaration introduces a class name or enumeration name and the
1163/// other declarations either introduce the same object, the same
1164/// enumerator or a set of functions, the non-type name hides the
1165/// class or enumeration name if and only if the declarations are
1166/// from the same namespace; otherwise (the declarations are from
1167/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +00001168static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +00001169 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +00001170 assert(StartDC->isFileContext() && "start context is not a file context");
1171
1172 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1173 DeclContext::udir_iterator E = StartDC->using_directives_end();
1174
1175 if (I == E) return false;
1176
1177 // We have at least added all these contexts to the queue.
1178 llvm::DenseSet<DeclContext*> Visited;
1179 Visited.insert(StartDC);
1180
1181 // We have not yet looked into these namespaces, much less added
1182 // their "using-children" to the queue.
1183 llvm::SmallVector<NamespaceDecl*, 8> Queue;
1184
1185 // We have already looked into the initial namespace; seed the queue
1186 // with its using-children.
1187 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001188 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6e247262009-10-10 05:48:19 +00001189 if (Visited.insert(ND).second)
1190 Queue.push_back(ND);
1191 }
1192
1193 // The easiest way to implement the restriction in [namespace.qual]p5
1194 // is to check whether any of the individual results found a tag
1195 // and, if so, to declare an ambiguity if the final result is not
1196 // a tag.
1197 bool FoundTag = false;
1198 bool FoundNonTag = false;
1199
John McCall7d384dd2009-11-18 07:57:50 +00001200 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001201
1202 bool Found = false;
1203 while (!Queue.empty()) {
1204 NamespaceDecl *ND = Queue.back();
1205 Queue.pop_back();
1206
1207 // We go through some convolutions here to avoid copying results
1208 // between LookupResults.
1209 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001210 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001211 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001212
1213 if (FoundDirect) {
1214 // First do any local hiding.
1215 DirectR.resolveKind();
1216
1217 // If the local result is a tag, remember that.
1218 if (DirectR.isSingleTagDecl())
1219 FoundTag = true;
1220 else
1221 FoundNonTag = true;
1222
1223 // Append the local results to the total results if necessary.
1224 if (UseLocal) {
1225 R.addAllDecls(LocalR);
1226 LocalR.clear();
1227 }
1228 }
1229
1230 // If we find names in this namespace, ignore its using directives.
1231 if (FoundDirect) {
1232 Found = true;
1233 continue;
1234 }
1235
1236 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1237 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1238 if (Visited.insert(Nom).second)
1239 Queue.push_back(Nom);
1240 }
1241 }
1242
1243 if (Found) {
1244 if (FoundTag && FoundNonTag)
1245 R.setAmbiguousQualifiedTagHiding();
1246 else
1247 R.resolveKind();
1248 }
1249
1250 return Found;
1251}
1252
Douglas Gregor8071e422010-08-15 06:18:01 +00001253/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001254static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor8071e422010-08-15 06:18:01 +00001255 CXXBasePath &Path,
1256 void *Name) {
1257 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001258
Douglas Gregor8071e422010-08-15 06:18:01 +00001259 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1260 Path.Decls = BaseRecord->lookup(N);
1261 return Path.Decls.first != Path.Decls.second;
1262}
1263
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001264/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001265/// static members, nested types, and enumerators.
1266template<typename InputIterator>
1267static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1268 Decl *D = (*First)->getUnderlyingDecl();
1269 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1270 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001271
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001272 if (isa<CXXMethodDecl>(D)) {
1273 // Determine whether all of the methods are static.
1274 bool AllMethodsAreStatic = true;
1275 for(; First != Last; ++First) {
1276 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001277
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001278 if (!isa<CXXMethodDecl>(D)) {
1279 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1280 break;
1281 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001282
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001283 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1284 AllMethodsAreStatic = false;
1285 break;
1286 }
1287 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001288
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001289 if (AllMethodsAreStatic)
1290 return true;
1291 }
1292
1293 return false;
1294}
1295
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001296/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001297///
1298/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1299/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001300/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001301///
1302/// Different lookup criteria can find different names. For example, a
1303/// particular scope can have both a struct and a function of the same
1304/// name, and each can be found by certain lookup criteria. For more
1305/// information about lookup criteria, see the documentation for the
1306/// class LookupCriteria.
1307///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001308/// \param R captures both the lookup criteria and any lookup results found.
1309///
1310/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001311/// search. If the lookup criteria permits, name lookup may also search
1312/// in the parent contexts or (for C++ classes) base classes.
1313///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001314/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001315/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001316///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001317/// \returns true if lookup succeeded, false if it failed.
1318bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1319 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001320 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001321
John McCalla24dc2e2009-11-17 02:14:36 +00001322 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001323 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001324
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001325 // Make sure that the declaration context is complete.
1326 assert((!isa<TagDecl>(LookupCtx) ||
1327 LookupCtx->isDependentContext() ||
1328 cast<TagDecl>(LookupCtx)->isDefinition() ||
1329 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1330 ->isBeingDefined()) &&
1331 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001332
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001333 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001334 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001335 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001336 if (isa<CXXRecordDecl>(LookupCtx))
1337 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001338 return true;
1339 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001340
John McCall6e247262009-10-10 05:48:19 +00001341 // Don't descend into implied contexts for redeclarations.
1342 // C++98 [namespace.qual]p6:
1343 // In a declaration for a namespace member in which the
1344 // declarator-id is a qualified-id, given that the qualified-id
1345 // for the namespace member has the form
1346 // nested-name-specifier unqualified-id
1347 // the unqualified-id shall name a member of the namespace
1348 // designated by the nested-name-specifier.
1349 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001350 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001351 return false;
1352
John McCalla24dc2e2009-11-17 02:14:36 +00001353 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001354 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001355 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001356
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001357 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001358 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001359 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor025291b2010-07-01 00:21:21 +00001360 if (!LookupRec || !LookupRec->getDefinition())
John McCallf36e02d2009-10-09 21:13:30 +00001361 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001362
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001363 // If we're performing qualified name lookup into a dependent class,
1364 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001365 // dependent base classes, then we either have to delay lookup until
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001366 // template instantiation time (at which point all bases will be available)
1367 // or we have to fail.
1368 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1369 LookupRec->hasAnyDependentBases()) {
1370 R.setNotFoundInCurrentInstantiation();
1371 return false;
1372 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001373
Douglas Gregor7176fff2009-01-15 00:26:24 +00001374 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001375 CXXBasePaths Paths;
1376 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001377
1378 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001379 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001380 switch (R.getLookupKind()) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001381 case LookupOrdinaryName:
1382 case LookupMemberName:
1383 case LookupRedeclarationWithLinkage:
1384 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1385 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001386
Douglas Gregora8f32e02009-10-06 17:59:45 +00001387 case LookupTagName:
1388 BaseCallback = &CXXRecordDecl::FindTagMember;
1389 break;
John McCall9f54ad42009-12-10 09:41:52 +00001390
Douglas Gregor8071e422010-08-15 06:18:01 +00001391 case LookupAnyName:
1392 BaseCallback = &LookupAnyMember;
1393 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001394
John McCall9f54ad42009-12-10 09:41:52 +00001395 case LookupUsingDeclName:
1396 // This lookup is for redeclarations only.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001397
Douglas Gregora8f32e02009-10-06 17:59:45 +00001398 case LookupOperatorName:
1399 case LookupNamespaceName:
1400 case LookupObjCProtocolName:
Chris Lattner337e5502011-02-18 01:27:55 +00001401 case LookupLabel:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001402 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001403 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001404
Douglas Gregora8f32e02009-10-06 17:59:45 +00001405 case LookupNestedNameSpecifierName:
1406 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1407 break;
1408 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001409
John McCalla24dc2e2009-11-17 02:14:36 +00001410 if (!LookupRec->lookupInBases(BaseCallback,
1411 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001412 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001413
John McCall92f88312010-01-23 00:46:32 +00001414 R.setNamingClass(LookupRec);
1415
Douglas Gregor7176fff2009-01-15 00:26:24 +00001416 // C++ [class.member.lookup]p2:
1417 // [...] If the resulting set of declarations are not all from
1418 // sub-objects of the same type, or the set has a nonstatic member
1419 // and includes members from distinct sub-objects, there is an
1420 // ambiguity and the program is ill-formed. Otherwise that set is
1421 // the result of the lookup.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001422 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001423 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001424 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001425
Douglas Gregora8f32e02009-10-06 17:59:45 +00001426 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001427 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001428 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001429
John McCall46460a62010-01-20 21:53:11 +00001430 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1431 // across all paths.
1432 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001433
Douglas Gregor7176fff2009-01-15 00:26:24 +00001434 // Determine whether we're looking at a distinct sub-object or not.
1435 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001436 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001437 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1438 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001439 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001440 }
1441
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001442 if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001443 != Context.getCanonicalType(PathElement.Base->getType())) {
1444 // We found members of the given name in two subobjects of
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001445 // different types. If the declaration sets aren't the same, this
1446 // this lookup is ambiguous.
1447 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1448 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1449 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1450 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001451
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001452 while (FirstD != FirstPath->Decls.second &&
1453 CurrentD != Path->Decls.second) {
1454 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1455 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1456 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001457
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001458 ++FirstD;
1459 ++CurrentD;
1460 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001461
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001462 if (FirstD == FirstPath->Decls.second &&
1463 CurrentD == Path->Decls.second)
1464 continue;
1465 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001466
John McCallf36e02d2009-10-09 21:13:30 +00001467 R.setAmbiguousBaseSubobjectTypes(Paths);
1468 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001469 }
1470
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001471 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001472 // We have a different subobject of the same type.
1473
1474 // C++ [class.member.lookup]p5:
1475 // A static member, a nested type or an enumerator defined in
1476 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001477 // has more than one base class subobject of type T.
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001478 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
Douglas Gregor7176fff2009-01-15 00:26:24 +00001479 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001480
Douglas Gregor7176fff2009-01-15 00:26:24 +00001481 // We have found a nonstatic member name in multiple, distinct
1482 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001483 R.setAmbiguousBaseSubobjects(Paths);
1484 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001485 }
1486 }
1487
1488 // Lookup in a base class succeeded; return these results.
1489
John McCallf36e02d2009-10-09 21:13:30 +00001490 DeclContext::lookup_iterator I, E;
John McCall92f88312010-01-23 00:46:32 +00001491 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1492 NamedDecl *D = *I;
1493 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1494 D->getAccess());
1495 R.addDecl(D, AS);
1496 }
John McCallf36e02d2009-10-09 21:13:30 +00001497 R.resolveKind();
1498 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001499}
1500
1501/// @brief Performs name lookup for a name that was parsed in the
1502/// source code, and may contain a C++ scope specifier.
1503///
1504/// This routine is a convenience routine meant to be called from
1505/// contexts that receive a name and an optional C++ scope specifier
1506/// (e.g., "N::M::x"). It will then perform either qualified or
1507/// unqualified name lookup (with LookupQualifiedName or LookupName,
1508/// respectively) on the given name and return those results.
1509///
1510/// @param S The scope from which unqualified name lookup will
1511/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001512///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001513/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001514///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001515/// @param EnteringContext Indicates whether we are going to enter the
1516/// context of the scope-specifier SS (if present).
1517///
John McCallf36e02d2009-10-09 21:13:30 +00001518/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001519bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001520 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001521 if (SS && SS->isInvalid()) {
1522 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001523 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001524 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001525 }
Mike Stump1eb44332009-09-09 15:08:12 +00001526
Douglas Gregor495c35d2009-08-25 22:51:20 +00001527 if (SS && SS->isSet()) {
1528 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001529 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001530 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001531 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001532 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001533
John McCalla24dc2e2009-11-17 02:14:36 +00001534 R.setContextRange(SS->getRange());
1535
1536 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001537 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001538
Douglas Gregor495c35d2009-08-25 22:51:20 +00001539 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001540 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001541 // Name lookup can't find anything in this case.
John McCallf36e02d2009-10-09 21:13:30 +00001542 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001543 }
1544
Mike Stump1eb44332009-09-09 15:08:12 +00001545 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001546 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001547}
1548
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001549
Douglas Gregor7176fff2009-01-15 00:26:24 +00001550/// @brief Produce a diagnostic describing the ambiguity that resulted
1551/// from name lookup.
1552///
1553/// @param Result The ambiguous name lookup result.
Mike Stump1eb44332009-09-09 15:08:12 +00001554///
Douglas Gregor7176fff2009-01-15 00:26:24 +00001555/// @param Name The name of the entity that name lookup was
1556/// searching for.
1557///
1558/// @param NameLoc The location of the name within the source code.
1559///
1560/// @param LookupRange A source range that provides more
1561/// source-location information concerning the lookup itself. For
1562/// example, this range might highlight a nested-name-specifier that
1563/// precedes the name.
1564///
1565/// @returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001566bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001567 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1568
John McCalla24dc2e2009-11-17 02:14:36 +00001569 DeclarationName Name = Result.getLookupName();
1570 SourceLocation NameLoc = Result.getNameLoc();
1571 SourceRange LookupRange = Result.getContextRange();
1572
John McCall6e247262009-10-10 05:48:19 +00001573 switch (Result.getAmbiguityKind()) {
1574 case LookupResult::AmbiguousBaseSubobjects: {
1575 CXXBasePaths *Paths = Result.getBasePaths();
1576 QualType SubobjectType = Paths->front().back().Base->getType();
1577 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1578 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1579 << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001580
John McCall6e247262009-10-10 05:48:19 +00001581 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1582 while (isa<CXXMethodDecl>(*Found) &&
1583 cast<CXXMethodDecl>(*Found)->isStatic())
1584 ++Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001585
John McCall6e247262009-10-10 05:48:19 +00001586 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001587
John McCall6e247262009-10-10 05:48:19 +00001588 return true;
1589 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001590
John McCall6e247262009-10-10 05:48:19 +00001591 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001592 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1593 << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001594
John McCall6e247262009-10-10 05:48:19 +00001595 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001596 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001597 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1598 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001599 Path != PathEnd; ++Path) {
1600 Decl *D = *Path->Decls.first;
1601 if (DeclsPrinted.insert(D).second)
1602 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1603 }
1604
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001605 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001606 }
1607
John McCall6e247262009-10-10 05:48:19 +00001608 case LookupResult::AmbiguousTagHiding: {
1609 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001610
John McCall6e247262009-10-10 05:48:19 +00001611 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1612
1613 LookupResult::iterator DI, DE = Result.end();
1614 for (DI = Result.begin(); DI != DE; ++DI)
1615 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1616 TagDecls.insert(TD);
1617 Diag(TD->getLocation(), diag::note_hidden_tag);
1618 }
1619
1620 for (DI = Result.begin(); DI != DE; ++DI)
1621 if (!isa<TagDecl>(*DI))
1622 Diag((*DI)->getLocation(), diag::note_hiding_object);
1623
1624 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001625 LookupResult::Filter F = Result.makeFilter();
1626 while (F.hasNext()) {
1627 if (TagDecls.count(F.next()))
1628 F.erase();
1629 }
1630 F.done();
John McCall6e247262009-10-10 05:48:19 +00001631
1632 return true;
1633 }
1634
1635 case LookupResult::AmbiguousReference: {
1636 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001637
John McCall6e247262009-10-10 05:48:19 +00001638 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1639 for (; DI != DE; ++DI)
1640 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001641
John McCall6e247262009-10-10 05:48:19 +00001642 return true;
1643 }
1644 }
1645
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001646 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001647 return true;
1648}
Douglas Gregorfa047642009-02-04 00:32:51 +00001649
John McCallc7e04da2010-05-28 18:45:08 +00001650namespace {
1651 struct AssociatedLookup {
1652 AssociatedLookup(Sema &S,
1653 Sema::AssociatedNamespaceSet &Namespaces,
1654 Sema::AssociatedClassSet &Classes)
1655 : S(S), Namespaces(Namespaces), Classes(Classes) {
1656 }
1657
1658 Sema &S;
1659 Sema::AssociatedNamespaceSet &Namespaces;
1660 Sema::AssociatedClassSet &Classes;
1661 };
1662}
1663
Mike Stump1eb44332009-09-09 15:08:12 +00001664static void
John McCallc7e04da2010-05-28 18:45:08 +00001665addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCall6ff07852009-08-07 22:18:02 +00001666
Douglas Gregor54022952010-04-30 07:08:38 +00001667static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1668 DeclContext *Ctx) {
1669 // Add the associated namespace for this class.
1670
1671 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1672 // be a locally scoped record.
1673
Sebastian Redl410c4f22010-08-31 20:53:31 +00001674 // We skip out of inline namespaces. The innermost non-inline namespace
1675 // contains all names of all its nested inline namespaces anyway, so we can
1676 // replace the entire inline namespace tree with its root.
1677 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1678 Ctx->isInlineNamespace())
Douglas Gregor54022952010-04-30 07:08:38 +00001679 Ctx = Ctx->getParent();
1680
John McCall6ff07852009-08-07 22:18:02 +00001681 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001682 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001683}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001684
Mike Stump1eb44332009-09-09 15:08:12 +00001685// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001686// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001687static void
John McCallc7e04da2010-05-28 18:45:08 +00001688addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1689 const TemplateArgument &Arg) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001690 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001691 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001692 switch (Arg.getKind()) {
1693 case TemplateArgument::Null:
1694 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001695
Douglas Gregor69be8d62009-07-08 07:51:57 +00001696 case TemplateArgument::Type:
1697 // [...] the namespaces and classes associated with the types of the
1698 // template arguments provided for template type parameters (excluding
1699 // template template parameters)
John McCallc7e04da2010-05-28 18:45:08 +00001700 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor69be8d62009-07-08 07:51:57 +00001701 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001702
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001703 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001704 case TemplateArgument::TemplateExpansion: {
Mike Stump1eb44332009-09-09 15:08:12 +00001705 // [...] the namespaces in which any template template arguments are
1706 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001707 // template template arguments are defined.
Douglas Gregora7fc9012011-01-05 18:58:31 +00001708 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump1eb44332009-09-09 15:08:12 +00001709 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001710 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001711 DeclContext *Ctx = ClassTemplate->getDeclContext();
1712 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001713 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001714 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001715 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001716 }
1717 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001718 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001719
Douglas Gregor788cd062009-11-11 01:00:40 +00001720 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001721 case TemplateArgument::Integral:
1722 case TemplateArgument::Expression:
Mike Stump1eb44332009-09-09 15:08:12 +00001723 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001724 // associated namespaces. ]
1725 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001726
Douglas Gregor69be8d62009-07-08 07:51:57 +00001727 case TemplateArgument::Pack:
1728 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1729 PEnd = Arg.pack_end();
1730 P != PEnd; ++P)
John McCallc7e04da2010-05-28 18:45:08 +00001731 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001732 break;
1733 }
1734}
1735
Douglas Gregorfa047642009-02-04 00:32:51 +00001736// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001737// argument-dependent lookup with an argument of class type
1738// (C++ [basic.lookup.koenig]p2).
1739static void
John McCallc7e04da2010-05-28 18:45:08 +00001740addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1741 CXXRecordDecl *Class) {
1742
1743 // Just silently ignore anything whose name is __va_list_tag.
1744 if (Class->getDeclName() == Result.S.VAListTagName)
1745 return;
1746
Douglas Gregorfa047642009-02-04 00:32:51 +00001747 // C++ [basic.lookup.koenig]p2:
1748 // [...]
1749 // -- If T is a class type (including unions), its associated
1750 // classes are: the class itself; the class of which it is a
1751 // member, if any; and its direct and indirect base
1752 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001753 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001754
1755 // Add the class of which it is a member, if any.
1756 DeclContext *Ctx = Class->getDeclContext();
1757 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001758 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001759 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001760 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Douglas Gregorfa047642009-02-04 00:32:51 +00001762 // Add the class itself. If we've already seen this class, we don't
1763 // need to visit base classes.
John McCallc7e04da2010-05-28 18:45:08 +00001764 if (!Result.Classes.insert(Class))
Douglas Gregorfa047642009-02-04 00:32:51 +00001765 return;
1766
Mike Stump1eb44332009-09-09 15:08:12 +00001767 // -- If T is a template-id, its associated namespaces and classes are
1768 // the namespace in which the template is defined; for member
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001769 // templates, the member template's class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001770 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001771 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001772 // namespaces in which any template template arguments are defined; and
1773 // the classes in which any member templates used as template template
1774 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001775 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001776 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001777 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1778 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1779 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001780 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001781 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001782 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001783
Douglas Gregor69be8d62009-07-08 07:51:57 +00001784 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1785 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallc7e04da2010-05-28 18:45:08 +00001786 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001787 }
Mike Stump1eb44332009-09-09 15:08:12 +00001788
John McCall86ff3082010-02-04 22:26:26 +00001789 // Only recurse into base classes for complete types.
1790 if (!Class->hasDefinition()) {
1791 // FIXME: we might need to instantiate templates here
1792 return;
1793 }
1794
Douglas Gregorfa047642009-02-04 00:32:51 +00001795 // Add direct and indirect base classes along with their associated
1796 // namespaces.
1797 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1798 Bases.push_back(Class);
1799 while (!Bases.empty()) {
1800 // Pop this class off the stack.
1801 Class = Bases.back();
1802 Bases.pop_back();
1803
1804 // Visit the base classes.
1805 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1806 BaseEnd = Class->bases_end();
1807 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001808 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001809 // In dependent contexts, we do ADL twice, and the first time around,
1810 // the base type might be a dependent TemplateSpecializationType, or a
1811 // TemplateTypeParmType. If that happens, simply ignore it.
1812 // FIXME: If we want to support export, we probably need to add the
1813 // namespace of the template in a TemplateSpecializationType, or even
1814 // the classes and namespaces of known non-dependent arguments.
1815 if (!BaseType)
1816 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001817 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001818 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001819 // Find the associated namespace for this base class.
1820 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallc7e04da2010-05-28 18:45:08 +00001821 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001822
1823 // Make sure we visit the bases of this base class.
1824 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1825 Bases.push_back(BaseDecl);
1826 }
1827 }
1828 }
1829}
1830
1831// \brief Add the associated classes and namespaces for
1832// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001833// (C++ [basic.lookup.koenig]p2).
1834static void
John McCallc7e04da2010-05-28 18:45:08 +00001835addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001836 // C++ [basic.lookup.koenig]p2:
1837 //
1838 // For each argument type T in the function call, there is a set
1839 // of zero or more associated namespaces and a set of zero or more
1840 // associated classes to be considered. The sets of namespaces and
1841 // classes is determined entirely by the types of the function
1842 // arguments (and the namespace of any template template
1843 // argument). Typedef names and using-declarations used to specify
1844 // the types do not contribute to this set. The sets of namespaces
1845 // and classes are determined in the following way:
Douglas Gregorfa047642009-02-04 00:32:51 +00001846
John McCallfa4edcf2010-05-28 06:08:54 +00001847 llvm::SmallVector<const Type *, 16> Queue;
1848 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1849
Douglas Gregorfa047642009-02-04 00:32:51 +00001850 while (true) {
John McCallfa4edcf2010-05-28 06:08:54 +00001851 switch (T->getTypeClass()) {
1852
1853#define TYPE(Class, Base)
1854#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1855#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1856#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1857#define ABSTRACT_TYPE(Class, Base)
1858#include "clang/AST/TypeNodes.def"
1859 // T is canonical. We can also ignore dependent types because
1860 // we don't need to do ADL at the definition point, but if we
1861 // wanted to implement template export (or if we find some other
1862 // use for associated classes and namespaces...) this would be
1863 // wrong.
Douglas Gregorfa047642009-02-04 00:32:51 +00001864 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00001865
John McCallfa4edcf2010-05-28 06:08:54 +00001866 // -- If T is a pointer to U or an array of U, its associated
1867 // namespaces and classes are those associated with U.
1868 case Type::Pointer:
1869 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1870 continue;
1871 case Type::ConstantArray:
1872 case Type::IncompleteArray:
1873 case Type::VariableArray:
1874 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1875 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001876
John McCallfa4edcf2010-05-28 06:08:54 +00001877 // -- If T is a fundamental type, its associated sets of
1878 // namespaces and classes are both empty.
1879 case Type::Builtin:
1880 break;
1881
1882 // -- If T is a class type (including unions), its associated
1883 // classes are: the class itself; the class of which it is a
1884 // member, if any; and its direct and indirect base
1885 // classes. Its associated namespaces are the namespaces in
1886 // which its associated classes are defined.
1887 case Type::Record: {
1888 CXXRecordDecl *Class
1889 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001890 addAssociatedClassesAndNamespaces(Result, Class);
John McCallfa4edcf2010-05-28 06:08:54 +00001891 break;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001892 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00001893
John McCallfa4edcf2010-05-28 06:08:54 +00001894 // -- If T is an enumeration type, its associated namespace is
1895 // the namespace in which it is defined. If it is class
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001896 // member, its associated class is the member's class; else
John McCallfa4edcf2010-05-28 06:08:54 +00001897 // it has no associated class.
1898 case Type::Enum: {
1899 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001900
John McCallfa4edcf2010-05-28 06:08:54 +00001901 DeclContext *Ctx = Enum->getDeclContext();
1902 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001903 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001904
John McCallfa4edcf2010-05-28 06:08:54 +00001905 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001906 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001907
John McCallfa4edcf2010-05-28 06:08:54 +00001908 break;
1909 }
1910
1911 // -- If T is a function type, its associated namespaces and
1912 // classes are those associated with the function parameter
1913 // types and those associated with the return type.
1914 case Type::FunctionProto: {
1915 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1916 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1917 ArgEnd = Proto->arg_type_end();
1918 Arg != ArgEnd; ++Arg)
1919 Queue.push_back(Arg->getTypePtr());
1920 // fallthrough
1921 }
1922 case Type::FunctionNoProto: {
1923 const FunctionType *FnType = cast<FunctionType>(T);
1924 T = FnType->getResultType().getTypePtr();
1925 continue;
1926 }
1927
1928 // -- If T is a pointer to a member function of a class X, its
1929 // associated namespaces and classes are those associated
1930 // with the function parameter types and return type,
1931 // together with those associated with X.
1932 //
1933 // -- If T is a pointer to a data member of class X, its
1934 // associated namespaces and classes are those associated
1935 // with the member type together with those associated with
1936 // X.
1937 case Type::MemberPointer: {
1938 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1939
1940 // Queue up the class type into which this points.
1941 Queue.push_back(MemberPtr->getClass());
1942
1943 // And directly continue with the pointee type.
1944 T = MemberPtr->getPointeeType().getTypePtr();
1945 continue;
1946 }
1947
1948 // As an extension, treat this like a normal pointer.
1949 case Type::BlockPointer:
1950 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1951 continue;
1952
1953 // References aren't covered by the standard, but that's such an
1954 // obvious defect that we cover them anyway.
1955 case Type::LValueReference:
1956 case Type::RValueReference:
1957 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1958 continue;
1959
1960 // These are fundamental types.
1961 case Type::Vector:
1962 case Type::ExtVector:
1963 case Type::Complex:
1964 break;
1965
1966 // These are ignored by ADL.
1967 case Type::ObjCObject:
1968 case Type::ObjCInterface:
1969 case Type::ObjCObjectPointer:
1970 break;
1971 }
1972
1973 if (Queue.empty()) break;
1974 T = Queue.back();
1975 Queue.pop_back();
Douglas Gregorfa047642009-02-04 00:32:51 +00001976 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001977}
1978
1979/// \brief Find the associated classes and namespaces for
1980/// argument-dependent lookup for a call with the given set of
1981/// arguments.
1982///
1983/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00001984/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00001985/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001986void
Douglas Gregorfa047642009-02-04 00:32:51 +00001987Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1988 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001989 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001990 AssociatedNamespaces.clear();
1991 AssociatedClasses.clear();
1992
John McCallc7e04da2010-05-28 18:45:08 +00001993 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
1994
Douglas Gregorfa047642009-02-04 00:32:51 +00001995 // C++ [basic.lookup.koenig]p2:
1996 // For each argument type T in the function call, there is a set
1997 // of zero or more associated namespaces and a set of zero or more
1998 // associated classes to be considered. The sets of namespaces and
1999 // classes is determined entirely by the types of the function
2000 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00002001 // argument).
Douglas Gregorfa047642009-02-04 00:32:51 +00002002 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
2003 Expr *Arg = Args[ArgIdx];
2004
2005 if (Arg->getType() != Context.OverloadTy) {
John McCallc7e04da2010-05-28 18:45:08 +00002006 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002007 continue;
2008 }
2009
2010 // [...] In addition, if the argument is the name or address of a
2011 // set of overloaded functions and/or function templates, its
2012 // associated classes and namespaces are the union of those
2013 // associated with each of the members of the set: the namespace
2014 // in which the function or function template is defined and the
2015 // classes and namespaces associated with its (non-dependent)
2016 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00002017 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00002018 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCall2de56d12010-08-25 11:45:40 +00002019 if (unaryOp->getOpcode() == UO_AddrOf)
John McCallba135432009-11-21 08:51:07 +00002020 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002021
John McCallc7e04da2010-05-28 18:45:08 +00002022 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2023 if (!ULE) continue;
John McCallba135432009-11-21 08:51:07 +00002024
John McCallc7e04da2010-05-28 18:45:08 +00002025 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2026 I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00002027 // Look through any using declarations to find the underlying function.
2028 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002029
Chandler Carruthbd647292009-12-29 06:17:27 +00002030 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2031 if (!FDecl)
2032 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002033
2034 // Add the classes and namespaces associated with the parameter
2035 // types and return type of this function.
John McCallc7e04da2010-05-28 18:45:08 +00002036 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002037 }
2038 }
2039}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002040
2041/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2042/// an acceptable non-member overloaded operator for a call whose
2043/// arguments have types T1 (and, if non-empty, T2). This routine
2044/// implements the check in C++ [over.match.oper]p3b2 concerning
2045/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00002046static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002047IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2048 QualType T1, QualType T2,
2049 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00002050 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2051 return true;
2052
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002053 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2054 return true;
2055
John McCall183700f2009-09-21 23:43:11 +00002056 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002057 if (Proto->getNumArgs() < 1)
2058 return false;
2059
2060 if (T1->isEnumeralType()) {
2061 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002062 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002063 return true;
2064 }
2065
2066 if (Proto->getNumArgs() < 2)
2067 return false;
2068
2069 if (!T2.isNull() && T2->isEnumeralType()) {
2070 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002071 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002072 return true;
2073 }
2074
2075 return false;
2076}
2077
John McCall7d384dd2009-11-18 07:57:50 +00002078NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002079 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00002080 LookupNameKind NameKind,
2081 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002082 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00002083 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00002084 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00002085}
2086
Douglas Gregor6e378de2009-04-23 23:18:26 +00002087/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002088ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002089 SourceLocation IdLoc) {
2090 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2091 LookupObjCProtocolName);
Douglas Gregor6e378de2009-04-23 23:18:26 +00002092 return cast_or_null<ObjCProtocolDecl>(D);
2093}
2094
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002095void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00002096 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00002097 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002098 // C++ [over.match.oper]p3:
2099 // -- The set of non-member candidates is the result of the
2100 // unqualified lookup of operator@ in the context of the
2101 // expression according to the usual rules for name lookup in
2102 // unqualified function calls (3.4.2) except that all member
2103 // functions are ignored. However, if no operand has a class
2104 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00002105 // that have a first parameter of type T1 or "reference to
2106 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002107 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00002108 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002109 // when T2 is an enumeration type, are candidate functions.
2110 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00002111 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2112 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002113
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002114 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2115
John McCallf36e02d2009-10-09 21:13:30 +00002116 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002117 return;
2118
2119 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2120 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002121 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2122 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002123 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002124 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00002125 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002126 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00002127 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00002128 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00002129 // later?
2130 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002131 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00002132 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002133 }
2134}
2135
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002136/// \brief Look up the constructors for the given class.
2137DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Douglas Gregor22584312010-07-02 23:41:54 +00002138 // If the copy constructor has not yet been declared, do so now.
Douglas Gregor18274032010-07-03 00:47:00 +00002139 if (CanDeclareSpecialMemberFunction(Context, Class)) {
2140 if (!Class->hasDeclaredDefaultConstructor())
2141 DeclareImplicitDefaultConstructor(Class);
2142 if (!Class->hasDeclaredCopyConstructor())
2143 DeclareImplicitCopyConstructor(Class);
2144 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002145
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002146 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2147 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2148 return Class->lookup(Name);
2149}
2150
Douglas Gregordb89f282010-07-01 22:47:18 +00002151/// \brief Look for the destructor of the given class.
2152///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002153/// During semantic analysis, this routine should be used in lieu of
Douglas Gregordb89f282010-07-01 22:47:18 +00002154/// CXXRecordDecl::getDestructor().
2155///
2156/// \returns The destructor for this class.
2157CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Douglas Gregor4923aa22010-07-02 20:37:36 +00002158 // If the destructor has not yet been declared, do so now.
2159 if (CanDeclareSpecialMemberFunction(Context, Class) &&
2160 !Class->hasDeclaredDestructor())
2161 DeclareImplicitDestructor(Class);
2162
Douglas Gregordb89f282010-07-01 22:47:18 +00002163 return Class->getDestructor();
2164}
2165
John McCall7edb5fd2010-01-26 07:16:45 +00002166void ADLResult::insert(NamedDecl *New) {
2167 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2168
2169 // If we haven't yet seen a decl for this key, or the last decl
2170 // was exactly this one, we're done.
2171 if (Old == 0 || Old == New) {
2172 Old = New;
2173 return;
2174 }
2175
2176 // Otherwise, decide which is a more recent redeclaration.
2177 FunctionDecl *OldFD, *NewFD;
2178 if (isa<FunctionTemplateDecl>(New)) {
2179 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2180 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2181 } else {
2182 OldFD = cast<FunctionDecl>(Old);
2183 NewFD = cast<FunctionDecl>(New);
2184 }
2185
2186 FunctionDecl *Cursor = NewFD;
2187 while (true) {
2188 Cursor = Cursor->getPreviousDeclaration();
2189
2190 // If we got to the end without finding OldFD, OldFD is the newer
2191 // declaration; leave things as they are.
2192 if (!Cursor) return;
2193
2194 // If we do find OldFD, then NewFD is newer.
2195 if (Cursor == OldFD) break;
2196
2197 // Otherwise, keep looking.
2198 }
2199
2200 Old = New;
2201}
2202
Sebastian Redl644be852009-10-23 19:23:15 +00002203void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002204 Expr **Args, unsigned NumArgs,
John McCall7edb5fd2010-01-26 07:16:45 +00002205 ADLResult &Result) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002206 // Find all of the associated namespaces and classes based on the
2207 // arguments we have.
2208 AssociatedNamespaceSet AssociatedNamespaces;
2209 AssociatedClassSet AssociatedClasses;
Mike Stump1eb44332009-09-09 15:08:12 +00002210 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCall6ff07852009-08-07 22:18:02 +00002211 AssociatedNamespaces,
2212 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002213
Sebastian Redl644be852009-10-23 19:23:15 +00002214 QualType T1, T2;
2215 if (Operator) {
2216 T1 = Args[0]->getType();
2217 if (NumArgs >= 2)
2218 T2 = Args[1]->getType();
2219 }
2220
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002221 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002222 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2223 // and let Y be the lookup set produced by argument dependent
2224 // lookup (defined as follows). If X contains [...] then Y is
2225 // empty. Otherwise Y is the set of declarations found in the
2226 // namespaces associated with the argument types as described
2227 // below. The set of declarations found by the lookup of the name
2228 // is the union of X and Y.
2229 //
2230 // Here, we compute Y and add its members to the overloaded
2231 // candidate set.
2232 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002233 NSEnd = AssociatedNamespaces.end();
2234 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002235 // When considering an associated namespace, the lookup is the
2236 // same as the lookup performed when the associated namespace is
2237 // used as a qualifier (3.4.3.2) except that:
2238 //
2239 // -- Any using-directives in the associated namespace are
2240 // ignored.
2241 //
John McCall6ff07852009-08-07 22:18:02 +00002242 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002243 // associated classes are visible within their respective
2244 // namespaces even if they are not visible during an ordinary
2245 // lookup (11.4).
2246 DeclContext::lookup_iterator I, E;
John McCall3f9a8a62009-08-11 06:59:38 +00002247 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall6e266892010-01-26 03:27:55 +00002248 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00002249 // If the only declaration here is an ordinary friend, consider
2250 // it only if it was declared in an associated classes.
2251 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00002252 DeclContext *LexDC = D->getLexicalDeclContext();
2253 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2254 continue;
2255 }
Mike Stump1eb44332009-09-09 15:08:12 +00002256
John McCalla113e722010-01-26 06:04:06 +00002257 if (isa<UsingShadowDecl>(D))
2258 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00002259
John McCalla113e722010-01-26 06:04:06 +00002260 if (isa<FunctionDecl>(D)) {
2261 if (Operator &&
2262 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2263 T1, T2, Context))
2264 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00002265 } else if (!isa<FunctionTemplateDecl>(D))
2266 continue;
2267
2268 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00002269 }
2270 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002271}
Douglas Gregor546be3c2009-12-30 17:04:44 +00002272
2273//----------------------------------------------------------------------------
2274// Search for all visible declarations.
2275//----------------------------------------------------------------------------
2276VisibleDeclConsumer::~VisibleDeclConsumer() { }
2277
2278namespace {
2279
2280class ShadowContextRAII;
2281
2282class VisibleDeclsRecord {
2283public:
2284 /// \brief An entry in the shadow map, which is optimized to store a
2285 /// single declaration (the common case) but can also store a list
2286 /// of declarations.
2287 class ShadowMapEntry {
2288 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002289
Douglas Gregor546be3c2009-12-30 17:04:44 +00002290 /// \brief Contains either the solitary NamedDecl * or a vector
2291 /// of declarations.
2292 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2293
2294 public:
2295 ShadowMapEntry() : DeclOrVector() { }
2296
2297 void Add(NamedDecl *ND);
2298 void Destroy();
2299
2300 // Iteration.
Argyrios Kyrtzidisaef05d72011-02-19 04:02:34 +00002301 typedef NamedDecl * const *iterator;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002302 iterator begin();
2303 iterator end();
2304 };
2305
2306private:
2307 /// \brief A mapping from declaration names to the declarations that have
2308 /// this name within a particular scope.
2309 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2310
2311 /// \brief A list of shadow maps, which is used to model name hiding.
2312 std::list<ShadowMap> ShadowMaps;
2313
2314 /// \brief The declaration contexts we have already visited.
2315 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2316
2317 friend class ShadowContextRAII;
2318
2319public:
2320 /// \brief Determine whether we have already visited this context
2321 /// (and, if not, note that we are going to visit that context now).
2322 bool visitedContext(DeclContext *Ctx) {
2323 return !VisitedContexts.insert(Ctx);
2324 }
2325
Douglas Gregor8071e422010-08-15 06:18:01 +00002326 bool alreadyVisitedContext(DeclContext *Ctx) {
2327 return VisitedContexts.count(Ctx);
2328 }
2329
Douglas Gregor546be3c2009-12-30 17:04:44 +00002330 /// \brief Determine whether the given declaration is hidden in the
2331 /// current scope.
2332 ///
2333 /// \returns the declaration that hides the given declaration, or
2334 /// NULL if no such declaration exists.
2335 NamedDecl *checkHidden(NamedDecl *ND);
2336
2337 /// \brief Add a declaration to the current shadow map.
2338 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2339};
2340
2341/// \brief RAII object that records when we've entered a shadow context.
2342class ShadowContextRAII {
2343 VisibleDeclsRecord &Visible;
2344
2345 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2346
2347public:
2348 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2349 Visible.ShadowMaps.push_back(ShadowMap());
2350 }
2351
2352 ~ShadowContextRAII() {
2353 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2354 EEnd = Visible.ShadowMaps.back().end();
2355 E != EEnd;
2356 ++E)
2357 E->second.Destroy();
2358
2359 Visible.ShadowMaps.pop_back();
2360 }
2361};
2362
2363} // end anonymous namespace
2364
2365void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2366 if (DeclOrVector.isNull()) {
2367 // 0 - > 1 elements: just set the single element information.
2368 DeclOrVector = ND;
2369 return;
2370 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002371
Douglas Gregor546be3c2009-12-30 17:04:44 +00002372 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2373 // 1 -> 2 elements: create the vector of results and push in the
2374 // existing declaration.
2375 DeclVector *Vec = new DeclVector;
2376 Vec->push_back(PrevND);
2377 DeclOrVector = Vec;
2378 }
2379
2380 // Add the new element to the end of the vector.
2381 DeclOrVector.get<DeclVector*>()->push_back(ND);
2382}
2383
2384void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2385 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2386 delete Vec;
2387 DeclOrVector = ((NamedDecl *)0);
2388 }
2389}
2390
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002391VisibleDeclsRecord::ShadowMapEntry::iterator
Douglas Gregor546be3c2009-12-30 17:04:44 +00002392VisibleDeclsRecord::ShadowMapEntry::begin() {
2393 if (DeclOrVector.isNull())
2394 return 0;
2395
Argyrios Kyrtzidisaef05d72011-02-19 04:02:34 +00002396 if (DeclOrVector.is<NamedDecl *>())
2397 return DeclOrVector.getAddrOf<NamedDecl *>();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002398
2399 return DeclOrVector.get<DeclVector *>()->begin();
2400}
2401
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002402VisibleDeclsRecord::ShadowMapEntry::iterator
Douglas Gregor546be3c2009-12-30 17:04:44 +00002403VisibleDeclsRecord::ShadowMapEntry::end() {
2404 if (DeclOrVector.isNull())
2405 return 0;
2406
2407 if (DeclOrVector.dyn_cast<NamedDecl *>())
2408 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2409
2410 return DeclOrVector.get<DeclVector *>()->end();
2411}
2412
2413NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002414 // Look through using declarations.
2415 ND = ND->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002416
Douglas Gregor546be3c2009-12-30 17:04:44 +00002417 unsigned IDNS = ND->getIdentifierNamespace();
2418 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2419 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2420 SM != SMEnd; ++SM) {
2421 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2422 if (Pos == SM->end())
2423 continue;
2424
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002425 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00002426 IEnd = Pos->second.end();
2427 I != IEnd; ++I) {
2428 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002429 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002430 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor546be3c2009-12-30 17:04:44 +00002431 Decl::IDNS_ObjCProtocol)))
2432 continue;
2433
2434 // Protocols are in distinct namespaces from everything else.
2435 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2436 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2437 (*I)->getIdentifierNamespace() != IDNS)
2438 continue;
2439
Douglas Gregor0cc84042010-01-14 15:47:35 +00002440 // Functions and function templates in the same scope overload
2441 // rather than hide. FIXME: Look for hiding based on function
2442 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002443 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002444 ND->isFunctionOrFunctionTemplate() &&
2445 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002446 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002447
Douglas Gregor546be3c2009-12-30 17:04:44 +00002448 // We've found a declaration that hides this one.
2449 return *I;
2450 }
2451 }
2452
2453 return 0;
2454}
2455
2456static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2457 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002458 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002459 VisibleDeclConsumer &Consumer,
2460 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00002461 if (!Ctx)
2462 return;
2463
Douglas Gregor546be3c2009-12-30 17:04:44 +00002464 // Make sure we don't visit the same context twice.
2465 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2466 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002467
Douglas Gregor4923aa22010-07-02 20:37:36 +00002468 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2469 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2470
Douglas Gregor546be3c2009-12-30 17:04:44 +00002471 // Enumerate all of the results in this context.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002472 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002473 CurCtx = CurCtx->getNextContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002474 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00002475 DEnd = CurCtx->decls_end();
2476 D != DEnd; ++D) {
Douglas Gregor70c23352010-12-09 21:44:02 +00002477 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002478 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002479 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002480 Visited.add(ND);
2481 }
Douglas Gregor70c23352010-12-09 21:44:02 +00002482 } else if (ObjCForwardProtocolDecl *ForwardProto
2483 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
2484 for (ObjCForwardProtocolDecl::protocol_iterator
2485 P = ForwardProto->protocol_begin(),
2486 PEnd = ForwardProto->protocol_end();
2487 P != PEnd;
2488 ++P) {
2489 if (Result.isAcceptableDecl(*P)) {
2490 Consumer.FoundDecl(*P, Visited.checkHidden(*P), InBaseClass);
2491 Visited.add(*P);
2492 }
2493 }
Douglas Gregord98abd82011-02-16 01:39:26 +00002494 } else if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D)) {
2495 for (ObjCClassDecl::iterator I = Class->begin(), IEnd = Class->end();
2496 I != IEnd; ++I) {
2497 ObjCInterfaceDecl *IFace = I->getInterface();
2498 if (Result.isAcceptableDecl(IFace)) {
2499 Consumer.FoundDecl(IFace, Visited.checkHidden(IFace), InBaseClass);
2500 Visited.add(IFace);
2501 }
2502 }
Douglas Gregor70c23352010-12-09 21:44:02 +00002503 }
Douglas Gregord98abd82011-02-16 01:39:26 +00002504
Sebastian Redl410c4f22010-08-31 20:53:31 +00002505 // Visit transparent contexts and inline namespaces inside this context.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002506 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
Sebastian Redl410c4f22010-08-31 20:53:31 +00002507 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Douglas Gregor0cc84042010-01-14 15:47:35 +00002508 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002509 Consumer, Visited);
2510 }
2511 }
2512 }
2513
2514 // Traverse using directives for qualified name lookup.
2515 if (QualifiedNameLookup) {
2516 ShadowContextRAII Shadow(Visited);
2517 DeclContext::udir_iterator I, E;
2518 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002519 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002520 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002521 }
2522 }
2523
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002524 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002525 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00002526 if (!Record->hasDefinition())
2527 return;
2528
Douglas Gregor546be3c2009-12-30 17:04:44 +00002529 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2530 BEnd = Record->bases_end();
2531 B != BEnd; ++B) {
2532 QualType BaseType = B->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002533
Douglas Gregor546be3c2009-12-30 17:04:44 +00002534 // Don't look into dependent bases, because name lookup can't look
2535 // there anyway.
2536 if (BaseType->isDependentType())
2537 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002538
Douglas Gregor546be3c2009-12-30 17:04:44 +00002539 const RecordType *Record = BaseType->getAs<RecordType>();
2540 if (!Record)
2541 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002542
Douglas Gregor546be3c2009-12-30 17:04:44 +00002543 // FIXME: It would be nice to be able to determine whether referencing
2544 // a particular member would be ambiguous. For example, given
2545 //
2546 // struct A { int member; };
2547 // struct B { int member; };
2548 // struct C : A, B { };
2549 //
2550 // void f(C *c) { c->### }
2551 //
2552 // accessing 'member' would result in an ambiguity. However, we
2553 // could be smart enough to qualify the member with the base
2554 // class, e.g.,
2555 //
2556 // c->B::member
2557 //
2558 // or
2559 //
2560 // c->A::member
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002561
Douglas Gregor546be3c2009-12-30 17:04:44 +00002562 // Find results in this base class (and its bases).
2563 ShadowContextRAII Shadow(Visited);
2564 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002565 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002566 }
2567 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002568
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002569 // Traverse the contexts of Objective-C classes.
2570 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2571 // Traverse categories.
2572 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2573 Category; Category = Category->getNextClassCategory()) {
2574 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002575 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002576 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002577 }
2578
2579 // Traverse protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00002580 for (ObjCInterfaceDecl::all_protocol_iterator
2581 I = IFace->all_referenced_protocol_begin(),
2582 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002583 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002584 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002585 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002586 }
2587
2588 // Traverse the superclass.
2589 if (IFace->getSuperClass()) {
2590 ShadowContextRAII Shadow(Visited);
2591 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002592 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002593 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002594
Douglas Gregorc220a182010-04-19 18:02:19 +00002595 // If there is an implementation, traverse it. We do this to find
2596 // synthesized ivars.
2597 if (IFace->getImplementation()) {
2598 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002599 LookupVisibleDecls(IFace->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00002600 QualifiedNameLookup, true, Consumer, Visited);
2601 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002602 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2603 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2604 E = Protocol->protocol_end(); I != E; ++I) {
2605 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002606 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002607 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002608 }
2609 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2610 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2611 E = Category->protocol_end(); I != E; ++I) {
2612 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002613 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002614 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002615 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002616
Douglas Gregorc220a182010-04-19 18:02:19 +00002617 // If there is an implementation, traverse it.
2618 if (Category->getImplementation()) {
2619 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002620 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00002621 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002622 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002623 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002624}
2625
2626static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2627 UnqualUsingDirectiveSet &UDirs,
2628 VisibleDeclConsumer &Consumer,
2629 VisibleDeclsRecord &Visited) {
2630 if (!S)
2631 return;
2632
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002633 if (!S->getEntity() ||
2634 (!S->getParent() &&
Douglas Gregor8071e422010-08-15 06:18:01 +00002635 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor539c5c32010-01-07 00:31:29 +00002636 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2637 // Walk through the declarations in this Scope.
2638 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2639 D != DEnd; ++D) {
John McCalld226f652010-08-21 09:40:31 +00002640 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor539c5c32010-01-07 00:31:29 +00002641 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002642 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002643 Visited.add(ND);
2644 }
2645 }
2646 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002647
Douglas Gregor711be1e2010-03-15 14:33:29 +00002648 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00002649 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00002650 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002651 // Look into this scope's declaration context, along with any of its
2652 // parent lookup contexts (e.g., enclosing classes), up to the point
2653 // where we hit the context stored in the next outer scope.
2654 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00002655 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002656
Douglas Gregordbdf5e72010-03-15 15:26:48 +00002657 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002658 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002659 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2660 if (Method->isInstanceMethod()) {
2661 // For instance methods, look for ivars in the method's interface.
2662 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2663 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregorca45da02010-11-02 20:36:02 +00002664 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002665 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Douglas Gregor62021192010-02-04 23:42:48 +00002666 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002667
Douglas Gregorca45da02010-11-02 20:36:02 +00002668 // Look for properties from which we can synthesize ivars, if
2669 // permitted.
2670 if (Result.getSema().getLangOptions().ObjCNonFragileABI2 &&
2671 IFace->getImplementation() &&
2672 Result.getLookupKind() == Sema::LookupOrdinaryName) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002673 for (ObjCInterfaceDecl::prop_iterator
Douglas Gregorca45da02010-11-02 20:36:02 +00002674 P = IFace->prop_begin(),
2675 PEnd = IFace->prop_end();
2676 P != PEnd; ++P) {
2677 if (Result.getSema().canSynthesizeProvisionalIvar(*P) &&
2678 !IFace->lookupInstanceVariable((*P)->getIdentifier())) {
2679 Consumer.FoundDecl(*P, Visited.checkHidden(*P), false);
2680 Visited.add(*P);
2681 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002682 }
2683 }
Douglas Gregorca45da02010-11-02 20:36:02 +00002684 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002685 }
2686
2687 // We've already performed all of the name lookup that we need
2688 // to for Objective-C methods; the next context will be the
2689 // outer scope.
2690 break;
2691 }
2692
Douglas Gregor546be3c2009-12-30 17:04:44 +00002693 if (Ctx->isFunctionOrMethod())
2694 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002695
2696 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002697 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002698 }
2699 } else if (!S->getParent()) {
2700 // Look into the translation unit scope. We walk through the translation
2701 // unit's declaration context, because the Scope itself won't have all of
2702 // the declarations if we loaded a precompiled header.
2703 // FIXME: We would like the translation unit's Scope object to point to the
2704 // translation unit, so we don't need this special "if" branch. However,
2705 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002706 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002707 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00002708 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002709 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002710 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002711 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002712 }
2713
Douglas Gregor546be3c2009-12-30 17:04:44 +00002714 if (Entity) {
2715 // Lookup visible declarations in any namespaces found by using
2716 // directives.
2717 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2718 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2719 for (; UI != UEnd; ++UI)
2720 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002721 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002722 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002723 }
2724
2725 // Lookup names in the parent scope.
2726 ShadowContextRAII Shadow(Visited);
2727 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2728}
2729
2730void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00002731 VisibleDeclConsumer &Consumer,
2732 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002733 // Determine the set of using directives available during
2734 // unqualified name lookup.
2735 Scope *Initial = S;
2736 UnqualUsingDirectiveSet UDirs;
2737 if (getLangOptions().CPlusPlus) {
2738 // Find the first namespace or translation-unit scope.
2739 while (S && !isNamespaceOrTranslationUnitScope(S))
2740 S = S->getParent();
2741
2742 UDirs.visitScopeChain(Initial, S);
2743 }
2744 UDirs.done();
2745
2746 // Look for visible declarations.
2747 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2748 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00002749 if (!IncludeGlobalScope)
2750 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00002751 ShadowContextRAII Shadow(Visited);
2752 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2753}
2754
2755void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00002756 VisibleDeclConsumer &Consumer,
2757 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002758 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2759 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00002760 if (!IncludeGlobalScope)
2761 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00002762 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002763 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002764 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002765}
2766
Chris Lattner4ae493c2011-02-18 02:08:43 +00002767/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara67843042011-03-05 18:21:20 +00002768/// If GnuLabelLoc is a valid source location, then this is a definition
2769/// of an __label__ label name, otherwise it is a normal label definition
2770/// or use.
Chris Lattner4ae493c2011-02-18 02:08:43 +00002771LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara67843042011-03-05 18:21:20 +00002772 SourceLocation GnuLabelLoc) {
Chris Lattner337e5502011-02-18 01:27:55 +00002773 // Do a lookup to see if we have a label with this name already.
Chris Lattner4ae493c2011-02-18 02:08:43 +00002774 NamedDecl *Res = 0;
Abramo Bagnara67843042011-03-05 18:21:20 +00002775
2776 if (GnuLabelLoc.isValid()) {
2777 // Local label definitions always shadow existing labels.
2778 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
2779 Scope *S = CurScope;
2780 PushOnScopeChains(Res, S, true);
2781 return cast<LabelDecl>(Res);
2782 }
2783
2784 // Not a GNU local label.
2785 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
2786 // If we found a label, check to see if it is in the same context as us.
2787 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattner337e5502011-02-18 01:27:55 +00002788 if (Res && Res->getDeclContext() != CurContext)
2789 Res = 0;
Chris Lattner337e5502011-02-18 01:27:55 +00002790 if (Res == 0) {
2791 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara67843042011-03-05 18:21:20 +00002792 Res = LabelDecl::Create(Context, CurContext, Loc, II);
2793 Scope *S = CurScope->getFnParent();
Chris Lattnerfebb5b82011-02-18 21:16:39 +00002794 assert(S && "Not in a function?");
2795 PushOnScopeChains(Res, S, true);
Chris Lattner337e5502011-02-18 01:27:55 +00002796 }
Chris Lattner337e5502011-02-18 01:27:55 +00002797 return cast<LabelDecl>(Res);
2798}
2799
2800//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00002801// Typo correction
Chris Lattner337e5502011-02-18 01:27:55 +00002802//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00002803
2804namespace {
2805class TypoCorrectionConsumer : public VisibleDeclConsumer {
2806 /// \brief The name written that is a typo in the source.
2807 llvm::StringRef Typo;
2808
2809 /// \brief The results found that have the smallest edit distance
2810 /// found (so far) with the typo name.
Douglas Gregore24b5752010-10-14 20:34:08 +00002811 ///
2812 /// The boolean value indicates whether there is a keyword with this name.
2813 llvm::StringMap<bool, llvm::BumpPtrAllocator> BestResults;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002814
2815 /// \brief The best edit distance found so far.
2816 unsigned BestEditDistance;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002817
Douglas Gregor546be3c2009-12-30 17:04:44 +00002818public:
2819 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002820 : Typo(Typo->getName()),
Douglas Gregore24b5752010-10-14 20:34:08 +00002821 BestEditDistance((std::numeric_limits<unsigned>::max)()) { }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002822
Douglas Gregor0cc84042010-01-14 15:47:35 +00002823 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregor95f42922010-10-14 22:11:03 +00002824 void FoundName(llvm::StringRef Name);
Douglas Gregoraaf87162010-04-14 20:04:41 +00002825 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002826
Douglas Gregore24b5752010-10-14 20:34:08 +00002827 typedef llvm::StringMap<bool, llvm::BumpPtrAllocator>::iterator iterator;
2828 iterator begin() { return BestResults.begin(); }
2829 iterator end() { return BestResults.end(); }
2830 void erase(iterator I) { BestResults.erase(I); }
2831 unsigned size() const { return BestResults.size(); }
2832 bool empty() const { return BestResults.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002833
Douglas Gregor7b824e82010-10-15 13:35:25 +00002834 bool &operator[](llvm::StringRef Name) {
2835 return BestResults[Name];
2836 }
2837
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002838 unsigned getBestEditDistance() const { return BestEditDistance; }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002839};
2840
2841}
2842
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002843void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002844 bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002845 // Don't consider hidden names for typo correction.
2846 if (Hiding)
2847 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002848
Douglas Gregor546be3c2009-12-30 17:04:44 +00002849 // Only consider entities with identifiers for names, ignoring
2850 // special names (constructors, overloaded operators, selectors,
2851 // etc.).
2852 IdentifierInfo *Name = ND->getIdentifier();
2853 if (!Name)
2854 return;
2855
Douglas Gregor95f42922010-10-14 22:11:03 +00002856 FoundName(Name->getName());
2857}
2858
2859void TypoCorrectionConsumer::FoundName(llvm::StringRef Name) {
Douglas Gregora1194772010-10-19 22:14:33 +00002860 using namespace std;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002861
Douglas Gregor362a8f22010-10-19 19:39:10 +00002862 // Use a simple length-based heuristic to determine the minimum possible
2863 // edit distance. If the minimum isn't good enough, bail out early.
2864 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
2865 if (MinED > BestEditDistance || (MinED && Typo.size() / MinED < 3))
2866 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002867
Douglas Gregora1194772010-10-19 22:14:33 +00002868 // Compute an upper bound on the allowable edit distance, so that the
2869 // edit-distance algorithm can short-circuit.
2870 unsigned UpperBound = min(unsigned((Typo.size() + 2) / 3), BestEditDistance);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002871
Douglas Gregor546be3c2009-12-30 17:04:44 +00002872 // Compute the edit distance between the typo and the name of this
2873 // entity. If this edit distance is not worse than the best edit
2874 // distance we've seen so far, add it to the list of results.
Douglas Gregora1194772010-10-19 22:14:33 +00002875 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
Douglas Gregor95f42922010-10-14 22:11:03 +00002876 if (ED == 0)
2877 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002878
Douglas Gregore24b5752010-10-14 20:34:08 +00002879 if (ED < BestEditDistance) {
2880 // This result is better than any we've seen before; clear out
2881 // the previous results.
2882 BestResults.clear();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002883 BestEditDistance = ED;
Douglas Gregore24b5752010-10-14 20:34:08 +00002884 } else if (ED > BestEditDistance) {
2885 // This result is worse than the best results we've seen so far;
2886 // ignore it.
2887 return;
2888 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002889
Douglas Gregore24b5752010-10-14 20:34:08 +00002890 // Add this name to the list of results. By not assigning a value, we
2891 // keep the current value if we've seen this name before (either as a
2892 // keyword or as a declaration), or get the default value (not a keyword)
2893 // if we haven't seen it before.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002894 (void)BestResults[Name];
Douglas Gregor546be3c2009-12-30 17:04:44 +00002895}
2896
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002897void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
Douglas Gregoraaf87162010-04-14 20:04:41 +00002898 llvm::StringRef Keyword) {
2899 // Compute the edit distance between the typo and this keyword.
2900 // If this edit distance is not worse than the best edit
2901 // distance we've seen so far, add it to the list of results.
2902 unsigned ED = Typo.edit_distance(Keyword);
Douglas Gregore24b5752010-10-14 20:34:08 +00002903 if (ED < BestEditDistance) {
2904 BestResults.clear();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002905 BestEditDistance = ED;
Douglas Gregore24b5752010-10-14 20:34:08 +00002906 } else if (ED > BestEditDistance) {
2907 // This result is worse than the best results we've seen so far;
2908 // ignore it.
2909 return;
2910 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002911
Douglas Gregore24b5752010-10-14 20:34:08 +00002912 BestResults[Keyword] = true;
Douglas Gregoraaf87162010-04-14 20:04:41 +00002913}
2914
Douglas Gregor9a632ea2010-10-20 03:06:34 +00002915/// \brief Perform name lookup for a possible result for typo correction.
2916static void LookupPotentialTypoResult(Sema &SemaRef,
2917 LookupResult &Res,
2918 IdentifierInfo *Name,
2919 Scope *S, CXXScopeSpec *SS,
2920 DeclContext *MemberContext,
2921 bool EnteringContext,
2922 Sema::CorrectTypoContext CTC) {
2923 Res.suppressDiagnostics();
2924 Res.clear();
2925 Res.setLookupName(Name);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002926 if (MemberContext) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00002927 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
2928 if (CTC == Sema::CTC_ObjCIvarLookup) {
2929 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
2930 Res.addDecl(Ivar);
2931 Res.resolveKind();
2932 return;
2933 }
2934 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002935
Douglas Gregor9a632ea2010-10-20 03:06:34 +00002936 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
2937 Res.addDecl(Prop);
2938 Res.resolveKind();
2939 return;
2940 }
2941 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002942
Douglas Gregor9a632ea2010-10-20 03:06:34 +00002943 SemaRef.LookupQualifiedName(Res, MemberContext);
2944 return;
2945 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002946
2947 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00002948 EnteringContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002949
Douglas Gregor9a632ea2010-10-20 03:06:34 +00002950 // Fake ivar lookup; this should really be part of
2951 // LookupParsedName.
2952 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2953 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002954 (Res.empty() ||
Douglas Gregor9a632ea2010-10-20 03:06:34 +00002955 (Res.isSingleResult() &&
2956 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002957 if (ObjCIvarDecl *IV
Douglas Gregor9a632ea2010-10-20 03:06:34 +00002958 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
2959 Res.addDecl(IV);
2960 Res.resolveKind();
2961 }
2962 }
2963 }
2964}
2965
Douglas Gregor546be3c2009-12-30 17:04:44 +00002966/// \brief Try to "correct" a typo in the source code by finding
2967/// visible declarations whose names are similar to the name that was
2968/// present in the source code.
2969///
2970/// \param Res the \c LookupResult structure that contains the name
2971/// that was present in the source code along with the name-lookup
2972/// criteria used to search for the name. On success, this structure
2973/// will contain the results of name lookup.
2974///
2975/// \param S the scope in which name lookup occurs.
2976///
2977/// \param SS the nested-name-specifier that precedes the name we're
2978/// looking for, if present.
2979///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002980/// \param MemberContext if non-NULL, the context in which to look for
2981/// a member access expression.
2982///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002983/// \param EnteringContext whether we're entering the context described by
Douglas Gregorbb092ba2009-12-31 05:20:13 +00002984/// the nested-name-specifier SS.
2985///
Douglas Gregoraaf87162010-04-14 20:04:41 +00002986/// \param CTC The context in which typo correction occurs, which impacts the
2987/// set of keywords permitted.
2988///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002989/// \param OPT when non-NULL, the search for visible declarations will
2990/// also walk the protocols in the qualified interfaces of \p OPT.
2991///
Douglas Gregor931f98a2010-04-14 17:09:22 +00002992/// \returns the corrected name if the typo was corrected, otherwise returns an
2993/// empty \c DeclarationName. When a typo was corrected, the result structure
2994/// may contain the results of name lookup for the correct name or it may be
2995/// empty.
2996DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002997 DeclContext *MemberContext,
Douglas Gregoraaf87162010-04-14 20:04:41 +00002998 bool EnteringContext,
2999 CorrectTypoContext CTC,
3000 const ObjCObjectPointerType *OPT) {
Douglas Gregora0068fc2010-07-09 17:35:33 +00003001 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregor931f98a2010-04-14 17:09:22 +00003002 return DeclarationName();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003003
Douglas Gregor546be3c2009-12-30 17:04:44 +00003004 // We only attempt to correct typos for identifiers.
3005 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
3006 if (!Typo)
Douglas Gregor931f98a2010-04-14 17:09:22 +00003007 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003008
3009 // If the scope specifier itself was invalid, don't try to correct
3010 // typos.
3011 if (SS && SS->isInvalid())
Douglas Gregor931f98a2010-04-14 17:09:22 +00003012 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003013
3014 // Never try to correct typos during template deduction or
3015 // instantiation.
3016 if (!ActiveTemplateInstantiations.empty())
Douglas Gregor931f98a2010-04-14 17:09:22 +00003017 return DeclarationName();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003018
Douglas Gregor546be3c2009-12-30 17:04:44 +00003019 TypoCorrectionConsumer Consumer(Typo);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003020
Douglas Gregoraaf87162010-04-14 20:04:41 +00003021 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003022 bool IsUnqualifiedLookup = false;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003023 if (MemberContext) {
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003024 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003025
3026 // Look in qualified interfaces.
3027 if (OPT) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003028 for (ObjCObjectPointerType::qual_iterator
3029 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003030 I != E; ++I)
3031 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
3032 }
3033 } else if (SS && SS->isSet()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003034 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
3035 if (!DC)
Douglas Gregor931f98a2010-04-14 17:09:22 +00003036 return DeclarationName();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003037
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003038 // Provide a stop gap for files that are just seriously broken. Trying
3039 // to correct all typos can turn into a HUGE performance penalty, causing
3040 // some files to take minutes to get rejected by the parser.
3041 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
3042 return DeclarationName();
3043 ++TyposCorrected;
3044
Douglas Gregor546be3c2009-12-30 17:04:44 +00003045 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
3046 } else {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003047 IsUnqualifiedLookup = true;
3048 UnqualifiedTyposCorrectedMap::iterator Cached
3049 = UnqualifiedTyposCorrected.find(Typo);
3050 if (Cached == UnqualifiedTyposCorrected.end()) {
3051 // Provide a stop gap for files that are just seriously broken. Trying
3052 // to correct all typos can turn into a HUGE performance penalty, causing
3053 // some files to take minutes to get rejected by the parser.
3054 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
3055 return DeclarationName();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003056
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003057 // For unqualified lookup, look through all of the names that we have
3058 // seen in this translation unit.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003059 for (IdentifierTable::iterator I = Context.Idents.begin(),
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003060 IEnd = Context.Idents.end();
3061 I != IEnd; ++I)
3062 Consumer.FoundName(I->getKey());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003063
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003064 // Walk through identifiers in external identifier sources.
3065 if (IdentifierInfoLookup *External
Douglas Gregor95f42922010-10-14 22:11:03 +00003066 = Context.Idents.getExternalIdentifierLookup()) {
Ted Kremenek7a054b12010-11-07 06:11:33 +00003067 llvm::OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003068 do {
3069 llvm::StringRef Name = Iter->Next();
3070 if (Name.empty())
3071 break;
Douglas Gregor95f42922010-10-14 22:11:03 +00003072
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003073 Consumer.FoundName(Name);
3074 } while (true);
3075 }
3076 } else {
3077 // Use the cached value, unless it's a keyword. In the keyword case, we'll
3078 // end up adding the keyword below.
3079 if (Cached->second.first.empty())
3080 return DeclarationName();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003081
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003082 if (!Cached->second.second)
3083 Consumer.FoundName(Cached->second.first);
Douglas Gregor95f42922010-10-14 22:11:03 +00003084 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003085 }
3086
Douglas Gregoraaf87162010-04-14 20:04:41 +00003087 // Add context-dependent keywords.
3088 bool WantTypeSpecifiers = false;
3089 bool WantExpressionKeywords = false;
3090 bool WantCXXNamedCasts = false;
3091 bool WantRemainingKeywords = false;
3092 switch (CTC) {
3093 case CTC_Unknown:
3094 WantTypeSpecifiers = true;
3095 WantExpressionKeywords = true;
3096 WantCXXNamedCasts = true;
3097 WantRemainingKeywords = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003098
Douglas Gregor91f7ac72010-05-18 16:14:23 +00003099 if (ObjCMethodDecl *Method = getCurMethodDecl())
3100 if (Method->getClassInterface() &&
3101 Method->getClassInterface()->getSuperClass())
3102 Consumer.addKeywordResult(Context, "super");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003103
Douglas Gregoraaf87162010-04-14 20:04:41 +00003104 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003105
Douglas Gregoraaf87162010-04-14 20:04:41 +00003106 case CTC_NoKeywords:
3107 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003108
Douglas Gregoraaf87162010-04-14 20:04:41 +00003109 case CTC_Type:
3110 WantTypeSpecifiers = true;
3111 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003112
Douglas Gregoraaf87162010-04-14 20:04:41 +00003113 case CTC_ObjCMessageReceiver:
3114 Consumer.addKeywordResult(Context, "super");
3115 // Fall through to handle message receivers like expressions.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003116
Douglas Gregoraaf87162010-04-14 20:04:41 +00003117 case CTC_Expression:
3118 if (getLangOptions().CPlusPlus)
3119 WantTypeSpecifiers = true;
3120 WantExpressionKeywords = true;
3121 // Fall through to get C++ named casts.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003122
Douglas Gregoraaf87162010-04-14 20:04:41 +00003123 case CTC_CXXCasts:
3124 WantCXXNamedCasts = true;
3125 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003126
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003127 case CTC_ObjCPropertyLookup:
3128 // FIXME: Add "isa"?
3129 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003130
Douglas Gregoraaf87162010-04-14 20:04:41 +00003131 case CTC_MemberLookup:
3132 if (getLangOptions().CPlusPlus)
3133 Consumer.addKeywordResult(Context, "template");
3134 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003135
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003136 case CTC_ObjCIvarLookup:
3137 break;
Douglas Gregoraaf87162010-04-14 20:04:41 +00003138 }
3139
3140 if (WantTypeSpecifiers) {
3141 // Add type-specifier keywords to the set of results.
3142 const char *CTypeSpecs[] = {
3143 "char", "const", "double", "enum", "float", "int", "long", "short",
3144 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
3145 "_Complex", "_Imaginary",
3146 // storage-specifiers as well
3147 "extern", "inline", "static", "typedef"
3148 };
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003149
Douglas Gregoraaf87162010-04-14 20:04:41 +00003150 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3151 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3152 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003153
Douglas Gregoraaf87162010-04-14 20:04:41 +00003154 if (getLangOptions().C99)
3155 Consumer.addKeywordResult(Context, "restrict");
3156 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
3157 Consumer.addKeywordResult(Context, "bool");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003158
Douglas Gregoraaf87162010-04-14 20:04:41 +00003159 if (getLangOptions().CPlusPlus) {
3160 Consumer.addKeywordResult(Context, "class");
3161 Consumer.addKeywordResult(Context, "typename");
3162 Consumer.addKeywordResult(Context, "wchar_t");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003163
Douglas Gregoraaf87162010-04-14 20:04:41 +00003164 if (getLangOptions().CPlusPlus0x) {
3165 Consumer.addKeywordResult(Context, "char16_t");
3166 Consumer.addKeywordResult(Context, "char32_t");
3167 Consumer.addKeywordResult(Context, "constexpr");
3168 Consumer.addKeywordResult(Context, "decltype");
3169 Consumer.addKeywordResult(Context, "thread_local");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003170 }
Douglas Gregoraaf87162010-04-14 20:04:41 +00003171 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003172
Douglas Gregoraaf87162010-04-14 20:04:41 +00003173 if (getLangOptions().GNUMode)
3174 Consumer.addKeywordResult(Context, "typeof");
3175 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003176
Douglas Gregord0785ea2010-05-18 16:30:22 +00003177 if (WantCXXNamedCasts && getLangOptions().CPlusPlus) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00003178 Consumer.addKeywordResult(Context, "const_cast");
3179 Consumer.addKeywordResult(Context, "dynamic_cast");
3180 Consumer.addKeywordResult(Context, "reinterpret_cast");
3181 Consumer.addKeywordResult(Context, "static_cast");
3182 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003183
Douglas Gregoraaf87162010-04-14 20:04:41 +00003184 if (WantExpressionKeywords) {
3185 Consumer.addKeywordResult(Context, "sizeof");
3186 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
3187 Consumer.addKeywordResult(Context, "false");
3188 Consumer.addKeywordResult(Context, "true");
3189 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003190
Douglas Gregoraaf87162010-04-14 20:04:41 +00003191 if (getLangOptions().CPlusPlus) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003192 const char *CXXExprs[] = {
3193 "delete", "new", "operator", "throw", "typeid"
Douglas Gregoraaf87162010-04-14 20:04:41 +00003194 };
3195 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3196 for (unsigned I = 0; I != NumCXXExprs; ++I)
3197 Consumer.addKeywordResult(Context, CXXExprs[I]);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003198
Douglas Gregoraaf87162010-04-14 20:04:41 +00003199 if (isa<CXXMethodDecl>(CurContext) &&
3200 cast<CXXMethodDecl>(CurContext)->isInstance())
3201 Consumer.addKeywordResult(Context, "this");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003202
Douglas Gregoraaf87162010-04-14 20:04:41 +00003203 if (getLangOptions().CPlusPlus0x) {
3204 Consumer.addKeywordResult(Context, "alignof");
3205 Consumer.addKeywordResult(Context, "nullptr");
3206 }
3207 }
3208 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003209
Douglas Gregoraaf87162010-04-14 20:04:41 +00003210 if (WantRemainingKeywords) {
3211 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
3212 // Statements.
3213 const char *CStmts[] = {
3214 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3215 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3216 for (unsigned I = 0; I != NumCStmts; ++I)
3217 Consumer.addKeywordResult(Context, CStmts[I]);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003218
Douglas Gregoraaf87162010-04-14 20:04:41 +00003219 if (getLangOptions().CPlusPlus) {
3220 Consumer.addKeywordResult(Context, "catch");
3221 Consumer.addKeywordResult(Context, "try");
3222 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003223
Douglas Gregoraaf87162010-04-14 20:04:41 +00003224 if (S && S->getBreakParent())
3225 Consumer.addKeywordResult(Context, "break");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003226
Douglas Gregoraaf87162010-04-14 20:04:41 +00003227 if (S && S->getContinueParent())
3228 Consumer.addKeywordResult(Context, "continue");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003229
John McCall781472f2010-08-25 08:40:02 +00003230 if (!getCurFunction()->SwitchStack.empty()) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00003231 Consumer.addKeywordResult(Context, "case");
3232 Consumer.addKeywordResult(Context, "default");
3233 }
3234 } else {
3235 if (getLangOptions().CPlusPlus) {
3236 Consumer.addKeywordResult(Context, "namespace");
3237 Consumer.addKeywordResult(Context, "template");
3238 }
3239
3240 if (S && S->isClassScope()) {
3241 Consumer.addKeywordResult(Context, "explicit");
3242 Consumer.addKeywordResult(Context, "friend");
3243 Consumer.addKeywordResult(Context, "mutable");
3244 Consumer.addKeywordResult(Context, "private");
3245 Consumer.addKeywordResult(Context, "protected");
3246 Consumer.addKeywordResult(Context, "public");
3247 Consumer.addKeywordResult(Context, "virtual");
3248 }
3249 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003250
Douglas Gregoraaf87162010-04-14 20:04:41 +00003251 if (getLangOptions().CPlusPlus) {
3252 Consumer.addKeywordResult(Context, "using");
3253
3254 if (getLangOptions().CPlusPlus0x)
3255 Consumer.addKeywordResult(Context, "static_assert");
3256 }
3257 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003258
Douglas Gregoraaf87162010-04-14 20:04:41 +00003259 // If we haven't found anything, we're done.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003260 if (Consumer.empty()) {
3261 // If this was an unqualified lookup, note that no correction was found.
3262 if (IsUnqualifiedLookup)
3263 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003264
Douglas Gregor931f98a2010-04-14 17:09:22 +00003265 return DeclarationName();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003266 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003267
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003268 // Make sure that the user typed at least 3 characters for each correction
Douglas Gregore24b5752010-10-14 20:34:08 +00003269 // made. Otherwise, we don't even both looking at the results.
Douglas Gregor53e4b552010-10-26 17:18:00 +00003270
3271 // We also suppress exact matches; those should be handled by a
3272 // different mechanism (e.g., one that introduces qualification in
3273 // C++).
Douglas Gregore24b5752010-10-14 20:34:08 +00003274 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003275 if (ED > 0 && Typo->getName().size() / ED < 3) {
3276 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregor157a3ff2010-10-27 14:20:34 +00003277 if (IsUnqualifiedLookup)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003278 (void)UnqualifiedTyposCorrected[Typo];
3279
Douglas Gregore24b5752010-10-14 20:34:08 +00003280 return DeclarationName();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003281 }
Douglas Gregore24b5752010-10-14 20:34:08 +00003282
3283 // Weed out any names that could not be found by name lookup.
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003284 bool LastLookupWasAccepted = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003285 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
Douglas Gregoraaf87162010-04-14 20:04:41 +00003286 IEnd = Consumer.end();
Douglas Gregore24b5752010-10-14 20:34:08 +00003287 I != IEnd; /* Increment in loop. */) {
3288 // Keywords are always found.
3289 if (I->second) {
3290 ++I;
3291 continue;
Douglas Gregoraaf87162010-04-14 20:04:41 +00003292 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003293
Douglas Gregore24b5752010-10-14 20:34:08 +00003294 // Perform name lookup on this name.
3295 IdentifierInfo *Name = &Context.Idents.get(I->getKey());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003296 LookupPotentialTypoResult(*this, Res, Name, S, SS, MemberContext,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003297 EnteringContext, CTC);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003298
Douglas Gregore24b5752010-10-14 20:34:08 +00003299 switch (Res.getResultKind()) {
3300 case LookupResult::NotFound:
3301 case LookupResult::NotFoundInCurrentInstantiation:
3302 case LookupResult::Ambiguous:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003303 // We didn't find this name in our scope, or didn't like what we found;
Douglas Gregore24b5752010-10-14 20:34:08 +00003304 // ignore it.
3305 Res.suppressDiagnostics();
3306 {
3307 TypoCorrectionConsumer::iterator Next = I;
3308 ++Next;
3309 Consumer.erase(I);
3310 I = Next;
3311 }
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003312 LastLookupWasAccepted = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003313 break;
3314
Douglas Gregore24b5752010-10-14 20:34:08 +00003315 case LookupResult::Found:
3316 case LookupResult::FoundOverloaded:
3317 case LookupResult::FoundUnresolvedValue:
3318 ++I;
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003319 LastLookupWasAccepted = true;
Douglas Gregoraaf87162010-04-14 20:04:41 +00003320 break;
Douglas Gregore24b5752010-10-14 20:34:08 +00003321 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003322
Douglas Gregore24b5752010-10-14 20:34:08 +00003323 if (Res.isAmbiguous()) {
3324 // We don't deal with ambiguities.
3325 Res.suppressDiagnostics();
3326 Res.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003327 return DeclarationName();
3328 }
Douglas Gregoraaf87162010-04-14 20:04:41 +00003329 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003330
Douglas Gregore24b5752010-10-14 20:34:08 +00003331 // If only a single name remains, return that result.
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003332 if (Consumer.size() == 1) {
3333 IdentifierInfo *Name = &Context.Idents.get(Consumer.begin()->getKey());
Douglas Gregorf98402d2010-10-20 01:01:57 +00003334 if (Consumer.begin()->second) {
3335 Res.suppressDiagnostics();
3336 Res.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003337
Douglas Gregor53e4b552010-10-26 17:18:00 +00003338 // Don't correct to a keyword that's the same as the typo; the keyword
3339 // wasn't actually in scope.
3340 if (ED == 0) {
3341 Res.setLookupName(Typo);
3342 return DeclarationName();
3343 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003344
Douglas Gregorf98402d2010-10-20 01:01:57 +00003345 } else if (!LastLookupWasAccepted) {
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003346 // Perform name lookup on this name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003347 LookupPotentialTypoResult(*this, Res, Name, S, SS, MemberContext,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003348 EnteringContext, CTC);
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003349 }
3350
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003351 // Record the correction for unqualified lookup.
3352 if (IsUnqualifiedLookup)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003353 UnqualifiedTyposCorrected[Typo]
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003354 = std::make_pair(Name->getName(), Consumer.begin()->second);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003355
3356 return &Context.Idents.get(Consumer.begin()->getKey());
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003357 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003358 else if (Consumer.size() > 1 && CTC == CTC_ObjCMessageReceiver
Douglas Gregor7b824e82010-10-15 13:35:25 +00003359 && Consumer["super"]) {
3360 // Prefix 'super' when we're completing in a message-receiver
3361 // context.
3362 Res.suppressDiagnostics();
3363 Res.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003364
Douglas Gregor53e4b552010-10-26 17:18:00 +00003365 // Don't correct to a keyword that's the same as the typo; the keyword
3366 // wasn't actually in scope.
3367 if (ED == 0) {
3368 Res.setLookupName(Typo);
3369 return DeclarationName();
3370 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003371
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003372 // Record the correction for unqualified lookup.
3373 if (IsUnqualifiedLookup)
3374 UnqualifiedTyposCorrected[Typo]
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003375 = std::make_pair("super", Consumer.begin()->second);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003376
Douglas Gregor7b824e82010-10-15 13:35:25 +00003377 return &Context.Idents.get("super");
3378 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003379
Douglas Gregore24b5752010-10-14 20:34:08 +00003380 Res.suppressDiagnostics();
3381 Res.setLookupName(Typo);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003382 Res.clear();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003383 // Record the correction for unqualified lookup.
3384 if (IsUnqualifiedLookup)
3385 (void)UnqualifiedTyposCorrected[Typo];
3386
Douglas Gregor931f98a2010-04-14 17:09:22 +00003387 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003388}