blob: 0fd0e08ac83097163a67fae86ca20b2994a772ff [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"
Douglas Gregor7176fff2009-01-15 00:26:24 +000021#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000023#include "clang/AST/Decl.h"
24#include "clang/AST/DeclCXX.h"
25#include "clang/AST/DeclObjC.h"
Douglas Gregor42af25f2009-05-11 19:58:34 +000026#include "clang/AST/DeclTemplate.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000027#include "clang/AST/Expr.h"
Douglas Gregordaa439a2009-07-08 10:57:20 +000028#include "clang/AST/ExprCXX.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000029#include "clang/Basic/Builtins.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000030#include "clang/Basic/LangOptions.h"
John McCall50df6ae2010-08-25 07:03:20 +000031#include "llvm/ADT/DenseSet.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000032#include "llvm/ADT/STLExtras.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000033#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregore24b5752010-10-14 20:34:08 +000034#include "llvm/ADT/StringMap.h"
John McCall6e247262009-10-10 05:48:19 +000035#include "llvm/Support/ErrorHandling.h"
Douglas Gregore24b5752010-10-14 20:34:08 +000036#include <limits>
Douglas Gregor546be3c2009-12-30 17:04:44 +000037#include <list>
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +000038#include <set>
Douglas Gregor2a3009a2009-02-03 19:21:40 +000039#include <vector>
40#include <iterator>
41#include <utility>
42#include <algorithm>
Douglas Gregoreb11cd02009-01-14 22:20:51 +000043
44using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000045using namespace sema;
Douglas Gregoreb11cd02009-01-14 22:20:51 +000046
John McCalld7be78a2009-11-10 07:01:13 +000047namespace {
48 class UnqualUsingEntry {
49 const DeclContext *Nominated;
50 const DeclContext *CommonAncestor;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000051
John McCalld7be78a2009-11-10 07:01:13 +000052 public:
53 UnqualUsingEntry(const DeclContext *Nominated,
54 const DeclContext *CommonAncestor)
55 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
56 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000057
John McCalld7be78a2009-11-10 07:01:13 +000058 const DeclContext *getCommonAncestor() const {
59 return CommonAncestor;
60 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000061
John McCalld7be78a2009-11-10 07:01:13 +000062 const DeclContext *getNominatedNamespace() const {
63 return Nominated;
64 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000065
John McCalld7be78a2009-11-10 07:01:13 +000066 // Sort by the pointer value of the common ancestor.
67 struct Comparator {
68 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
69 return L.getCommonAncestor() < R.getCommonAncestor();
70 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000071
John McCalld7be78a2009-11-10 07:01:13 +000072 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
73 return E.getCommonAncestor() < DC;
74 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000075
John McCalld7be78a2009-11-10 07:01:13 +000076 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
77 return DC < E.getCommonAncestor();
78 }
79 };
80 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +000081
John McCalld7be78a2009-11-10 07:01:13 +000082 /// A collection of using directives, as used by C++ unqualified
83 /// lookup.
84 class UnqualUsingDirectiveSet {
85 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000086
John McCalld7be78a2009-11-10 07:01:13 +000087 ListTy list;
88 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000089
John McCalld7be78a2009-11-10 07:01:13 +000090 public:
91 UnqualUsingDirectiveSet() {}
Douglas Gregor2a3009a2009-02-03 19:21:40 +000092
John McCalld7be78a2009-11-10 07:01:13 +000093 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000094 // C++ [namespace.udir]p1:
John McCalld7be78a2009-11-10 07:01:13 +000095 // During unqualified name lookup, the names appear as if they
96 // were declared in the nearest enclosing namespace which contains
97 // both the using-directive and the nominated namespace.
98 DeclContext *InnermostFileDC
99 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
100 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000101
John McCalld7be78a2009-11-10 07:01:13 +0000102 for (; S; S = S->getParent()) {
John McCalld7be78a2009-11-10 07:01:13 +0000103 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
104 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
105 visit(Ctx, EffectiveDC);
106 } else {
107 Scope::udir_iterator I = S->using_directives_begin(),
108 End = S->using_directives_end();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000109
John McCalld7be78a2009-11-10 07:01:13 +0000110 for (; I != End; ++I)
John McCalld226f652010-08-21 09:40:31 +0000111 visit(*I, InnermostFileDC);
John McCalld7be78a2009-11-10 07:01:13 +0000112 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000113 }
114 }
John McCalld7be78a2009-11-10 07:01:13 +0000115
116 // Visits a context and collect all of its using directives
117 // recursively. Treats all using directives as if they were
118 // declared in the context.
119 //
120 // A given context is only every visited once, so it is important
121 // that contexts be visited from the inside out in order to get
122 // the effective DCs right.
123 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
124 if (!visited.insert(DC))
125 return;
126
127 addUsingDirectives(DC, EffectiveDC);
128 }
129
130 // Visits a using directive and collects all of its using
131 // directives recursively. Treats all using directives as if they
132 // were declared in the effective DC.
133 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
134 DeclContext *NS = UD->getNominatedNamespace();
135 if (!visited.insert(NS))
136 return;
137
138 addUsingDirective(UD, EffectiveDC);
139 addUsingDirectives(NS, EffectiveDC);
140 }
141
142 // Adds all the using directives in a context (and those nominated
143 // by its using directives, transitively) as if they appeared in
144 // the given effective context.
145 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
146 llvm::SmallVector<DeclContext*,4> queue;
147 while (true) {
148 DeclContext::udir_iterator I, End;
149 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
150 UsingDirectiveDecl *UD = *I;
151 DeclContext *NS = UD->getNominatedNamespace();
152 if (visited.insert(NS)) {
153 addUsingDirective(UD, EffectiveDC);
154 queue.push_back(NS);
155 }
156 }
157
158 if (queue.empty())
159 return;
160
161 DC = queue.back();
162 queue.pop_back();
163 }
164 }
165
166 // Add a using directive as if it had been declared in the given
167 // context. This helps implement C++ [namespace.udir]p3:
168 // The using-directive is transitive: if a scope contains a
169 // using-directive that nominates a second namespace that itself
170 // contains using-directives, the effect is as if the
171 // using-directives from the second namespace also appeared in
172 // the first.
173 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
174 // Find the common ancestor between the effective context and
175 // the nominated namespace.
176 DeclContext *Common = UD->getNominatedNamespace();
177 while (!Common->Encloses(EffectiveDC))
178 Common = Common->getParent();
John McCall12ea5782009-11-10 09:20:04 +0000179 Common = Common->getPrimaryContext();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000180
John McCalld7be78a2009-11-10 07:01:13 +0000181 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
182 }
183
184 void done() {
185 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
186 }
187
John McCalld7be78a2009-11-10 07:01:13 +0000188 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000189
John McCalld7be78a2009-11-10 07:01:13 +0000190 const_iterator begin() const { return list.begin(); }
191 const_iterator end() const { return list.end(); }
192
193 std::pair<const_iterator,const_iterator>
194 getNamespacesFor(DeclContext *DC) const {
John McCall12ea5782009-11-10 09:20:04 +0000195 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCalld7be78a2009-11-10 07:01:13 +0000196 UnqualUsingEntry::Comparator());
197 }
198 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000199}
200
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000201// Retrieve the set of identifier namespaces that correspond to a
202// specific kind of name lookup.
John McCall1d7c5282009-12-18 10:40:03 +0000203static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
204 bool CPlusPlus,
205 bool Redeclaration) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000206 unsigned IDNS = 0;
207 switch (NameKind) {
208 case Sema::LookupOrdinaryName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000209 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000210 IDNS = Decl::IDNS_Ordinary;
John McCall1d7c5282009-12-18 10:40:03 +0000211 if (CPlusPlus) {
John McCall0d6b1642010-04-23 18:46:30 +0000212 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattner337e5502011-02-18 01:27:55 +0000213 if (Redeclaration)
214 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCall1d7c5282009-12-18 10:40:03 +0000215 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000216 break;
217
John McCall76d32642010-04-24 01:30:58 +0000218 case Sema::LookupOperatorName:
219 // Operator lookup is its own crazy thing; it is not the same
220 // as (e.g.) looking up an operator name for redeclaration.
221 assert(!Redeclaration && "cannot do redeclaration operator lookup");
222 IDNS = Decl::IDNS_NonMemberOperator;
223 break;
224
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000225 case Sema::LookupTagName:
John McCall0d6b1642010-04-23 18:46:30 +0000226 if (CPlusPlus) {
227 IDNS = Decl::IDNS_Type;
228
229 // When looking for a redeclaration of a tag name, we add:
230 // 1) TagFriend to find undeclared friend decls
231 // 2) Namespace because they can't "overload" with tag decls.
232 // 3) Tag because it includes class templates, which can't
233 // "overload" with tag decls.
234 if (Redeclaration)
235 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
236 } else {
237 IDNS = Decl::IDNS_Tag;
238 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000239 break;
Chris Lattner337e5502011-02-18 01:27:55 +0000240 case Sema::LookupLabel:
241 IDNS = Decl::IDNS_Label;
242 break;
243
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000244 case Sema::LookupMemberName:
245 IDNS = Decl::IDNS_Member;
246 if (CPlusPlus)
Mike Stump1eb44332009-09-09 15:08:12 +0000247 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000248 break;
249
250 case Sema::LookupNestedNameSpecifierName:
John McCall0d6b1642010-04-23 18:46:30 +0000251 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
252 break;
253
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000254 case Sema::LookupNamespaceName:
John McCall0d6b1642010-04-23 18:46:30 +0000255 IDNS = Decl::IDNS_Namespace;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000256 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000257
John McCall9f54ad42009-12-10 09:41:52 +0000258 case Sema::LookupUsingDeclName:
259 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
260 | Decl::IDNS_Member | Decl::IDNS_Using;
261 break;
262
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000263 case Sema::LookupObjCProtocolName:
264 IDNS = Decl::IDNS_ObjCProtocol;
265 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000266
Douglas Gregor8071e422010-08-15 06:18:01 +0000267 case Sema::LookupAnyName:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000268 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor8071e422010-08-15 06:18:01 +0000269 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
270 | Decl::IDNS_Type;
271 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000272 }
273 return IDNS;
274}
275
John McCall1d7c5282009-12-18 10:40:03 +0000276void LookupResult::configure() {
Chris Lattner337e5502011-02-18 01:27:55 +0000277 IDNS = getIDNS(LookupKind, SemaRef.getLangOptions().CPlusPlus,
John McCall1d7c5282009-12-18 10:40:03 +0000278 isForRedeclaration());
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000279
280 // If we're looking for one of the allocation or deallocation
281 // operators, make sure that the implicitly-declared new and delete
282 // operators can be found.
283 if (!isForRedeclaration()) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000284 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000285 case OO_New:
286 case OO_Delete:
287 case OO_Array_New:
288 case OO_Array_Delete:
289 SemaRef.DeclareGlobalNewDelete();
290 break;
291
292 default:
293 break;
294 }
295 }
John McCall1d7c5282009-12-18 10:40:03 +0000296}
297
John McCall2a7fb272010-08-25 05:32:35 +0000298void LookupResult::sanity() const {
299 assert(ResultKind != NotFound || Decls.size() == 0);
300 assert(ResultKind != Found || Decls.size() == 1);
301 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
302 (Decls.size() == 1 &&
303 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
304 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
305 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorf17b58c2010-10-22 22:08:47 +0000306 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
307 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall2a7fb272010-08-25 05:32:35 +0000308 assert((Paths != NULL) == (ResultKind == Ambiguous &&
309 (Ambiguity == AmbiguousBaseSubobjectTypes ||
310 Ambiguity == AmbiguousBaseSubobjects)));
311}
John McCall2a7fb272010-08-25 05:32:35 +0000312
John McCallf36e02d2009-10-09 21:13:30 +0000313// Necessary because CXXBasePaths is not complete in Sema.h
John McCall7d384dd2009-11-18 07:57:50 +0000314void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCallf36e02d2009-10-09 21:13:30 +0000315 delete Paths;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000316}
317
John McCall7453ed42009-11-22 00:44:51 +0000318/// Resolves the result kind of this lookup.
John McCall7d384dd2009-11-18 07:57:50 +0000319void LookupResult::resolveKind() {
John McCallf36e02d2009-10-09 21:13:30 +0000320 unsigned N = Decls.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000321
John McCallf36e02d2009-10-09 21:13:30 +0000322 // Fast case: no possible ambiguity.
John McCall68263142009-11-18 22:49:29 +0000323 if (N == 0) {
John McCalldc5c7862010-01-15 21:27:01 +0000324 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall68263142009-11-18 22:49:29 +0000325 return;
326 }
327
John McCall7453ed42009-11-22 00:44:51 +0000328 // If there's a single decl, we need to examine it to decide what
329 // kind of lookup this is.
John McCall7ba107a2009-11-18 02:36:19 +0000330 if (N == 1) {
Douglas Gregor2b147f02010-04-25 21:15:30 +0000331 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
332 if (isa<FunctionTemplateDecl>(D))
John McCall7453ed42009-11-22 00:44:51 +0000333 ResultKind = FoundOverloaded;
Douglas Gregor2b147f02010-04-25 21:15:30 +0000334 else if (isa<UnresolvedUsingValueDecl>(D))
John McCall7ba107a2009-11-18 02:36:19 +0000335 ResultKind = FoundUnresolvedValue;
336 return;
337 }
John McCallf36e02d2009-10-09 21:13:30 +0000338
John McCall6e247262009-10-10 05:48:19 +0000339 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000340 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000341
John McCallf36e02d2009-10-09 21:13:30 +0000342 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000343 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000344
John McCallf36e02d2009-10-09 21:13:30 +0000345 bool Ambiguous = false;
346 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000347 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000348
349 unsigned UniqueTagIndex = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000350
John McCallf36e02d2009-10-09 21:13:30 +0000351 unsigned I = 0;
352 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000353 NamedDecl *D = Decls[I]->getUnderlyingDecl();
354 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000355
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000356 // Redeclarations of types via typedef can occur both within a scope
357 // and, through using declarations and directives, across scopes. There is
358 // no ambiguity if they all refer to the same type, so unique based on the
359 // canonical type.
360 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
361 if (!TD->getDeclContext()->isRecord()) {
362 QualType T = SemaRef.Context.getTypeDeclType(TD);
363 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
364 // The type is not unique; pull something off the back and continue
365 // at this index.
366 Decls[I] = Decls[--N];
367 continue;
368 }
369 }
370 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000371
John McCall314be4e2009-11-17 07:50:12 +0000372 if (!Unique.insert(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000373 // If it's not unique, pull something off the back (and
374 // continue at this index).
375 Decls[I] = Decls[--N];
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000376 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000377 }
378
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000379 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000380
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000381 if (isa<UnresolvedUsingValueDecl>(D)) {
382 HasUnresolved = true;
383 } else if (isa<TagDecl>(D)) {
384 if (HasTag)
385 Ambiguous = true;
386 UniqueTagIndex = I;
387 HasTag = true;
388 } else if (isa<FunctionTemplateDecl>(D)) {
389 HasFunction = true;
390 HasFunctionTemplate = true;
391 } else if (isa<FunctionDecl>(D)) {
392 HasFunction = true;
393 } else {
394 if (HasNonFunction)
395 Ambiguous = true;
396 HasNonFunction = true;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000397 }
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000398 I++;
Mike Stump1eb44332009-09-09 15:08:12 +0000399 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000400
John McCallf36e02d2009-10-09 21:13:30 +0000401 // C++ [basic.scope.hiding]p2:
402 // A class name or enumeration name can be hidden by the name of
403 // an object, function, or enumerator declared in the same
404 // scope. If a class or enumeration name and an object, function,
405 // or enumerator are declared in the same scope (in any order)
406 // with the same name, the class or enumeration name is hidden
407 // wherever the object, function, or enumerator name is visible.
408 // But it's still an error if there are distinct tag types found,
409 // even if they're not visible. (ref?)
John McCallfda8e122009-12-03 00:58:24 +0000410 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregor77a1a882010-10-23 16:06:17 +0000411 (HasFunction || HasNonFunction || HasUnresolved)) {
412 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
413 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
414 Decls[UniqueTagIndex] = Decls[--N];
415 else
416 Ambiguous = true;
417 }
Anders Carlsson8b50d012009-06-26 03:37:05 +0000418
John McCallf36e02d2009-10-09 21:13:30 +0000419 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000420
John McCallfda8e122009-12-03 00:58:24 +0000421 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000422 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000423
John McCallf36e02d2009-10-09 21:13:30 +0000424 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000425 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000426 else if (HasUnresolved)
427 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000428 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000429 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000430 else
John McCalla24dc2e2009-11-17 02:14:36 +0000431 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000432}
433
John McCall7d384dd2009-11-18 07:57:50 +0000434void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall6b2accb2010-02-10 09:31:12 +0000435 CXXBasePaths::const_paths_iterator I, E;
John McCallf36e02d2009-10-09 21:13:30 +0000436 DeclContext::lookup_iterator DI, DE;
437 for (I = P.begin(), E = P.end(); I != E; ++I)
438 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
439 addDecl(*DI);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000440}
441
John McCall7d384dd2009-11-18 07:57:50 +0000442void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000443 Paths = new CXXBasePaths;
444 Paths->swap(P);
445 addDeclsFromBasePaths(*Paths);
446 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000447 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000448}
449
John McCall7d384dd2009-11-18 07:57:50 +0000450void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000451 Paths = new CXXBasePaths;
452 Paths->swap(P);
453 addDeclsFromBasePaths(*Paths);
454 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000455 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000456}
457
John McCall7d384dd2009-11-18 07:57:50 +0000458void LookupResult::print(llvm::raw_ostream &Out) {
John McCallf36e02d2009-10-09 21:13:30 +0000459 Out << Decls.size() << " result(s)";
460 if (isAmbiguous()) Out << ", ambiguous";
461 if (Paths) Out << ", base paths present";
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000462
John McCallf36e02d2009-10-09 21:13:30 +0000463 for (iterator I = begin(), E = end(); I != E; ++I) {
464 Out << "\n";
465 (*I)->print(Out, 2);
466 }
467}
468
Douglas Gregor85910982010-02-12 05:48:04 +0000469/// \brief Lookup a builtin function, when name lookup would otherwise
470/// fail.
471static bool LookupBuiltin(Sema &S, LookupResult &R) {
472 Sema::LookupNameKind NameKind = R.getLookupKind();
473
474 // If we didn't find a use of this identifier, and if the identifier
475 // corresponds to a compiler builtin, create the decl object for the builtin
476 // now, injecting it into translation unit scope, and return it.
477 if (NameKind == Sema::LookupOrdinaryName ||
478 NameKind == Sema::LookupRedeclarationWithLinkage) {
479 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
480 if (II) {
481 // If this is a builtin on this (or all) targets, create the decl.
482 if (unsigned BuiltinID = II->getBuiltinID()) {
483 // In C++, we don't have any predefined library functions like
484 // 'malloc'. Instead, we'll just error.
485 if (S.getLangOptions().CPlusPlus &&
486 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
487 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000488
489 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
490 BuiltinID, S.TUScope,
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000491 R.isForRedeclaration(),
492 R.getNameLoc())) {
Douglas Gregor85910982010-02-12 05:48:04 +0000493 R.addDecl(D);
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000494 return true;
495 }
496
497 if (R.isForRedeclaration()) {
498 // If we're redeclaring this function anyway, forget that
499 // this was a builtin at all.
500 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
501 }
502
503 return false;
Douglas Gregor85910982010-02-12 05:48:04 +0000504 }
505 }
506 }
507
508 return false;
509}
510
Douglas Gregor4923aa22010-07-02 20:37:36 +0000511/// \brief Determine whether we can declare a special member function within
512/// the class at this point.
513static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
514 const CXXRecordDecl *Class) {
John McCallb3b50a82010-08-11 23:52:36 +0000515 // Don't do it if the class is invalid.
516 if (Class->isInvalidDecl())
517 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000518
Douglas Gregor4923aa22010-07-02 20:37:36 +0000519 // We need to have a definition for the class.
520 if (!Class->getDefinition() || Class->isDependentContext())
521 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000522
Douglas Gregor4923aa22010-07-02 20:37:36 +0000523 // We can't be in the middle of defining the class.
524 if (const RecordType *RecordTy
525 = Context.getTypeDeclType(Class)->getAs<RecordType>())
526 return !RecordTy->isBeingDefined();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000527
Douglas Gregor4923aa22010-07-02 20:37:36 +0000528 return false;
529}
530
531void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregor22584312010-07-02 23:41:54 +0000532 if (!CanDeclareSpecialMemberFunction(Context, Class))
533 return;
Douglas Gregor18274032010-07-03 00:47:00 +0000534
535 // If the default constructor has not yet been declared, do so now.
536 if (!Class->hasDeclaredDefaultConstructor())
537 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000538
Douglas Gregor22584312010-07-02 23:41:54 +0000539 // If the copy constructor has not yet been declared, do so now.
540 if (!Class->hasDeclaredCopyConstructor())
541 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000542
Douglas Gregora376d102010-07-02 21:50:04 +0000543 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000544 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +0000545 DeclareImplicitCopyAssignment(Class);
546
Douglas Gregor4923aa22010-07-02 20:37:36 +0000547 // If the destructor has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000548 if (!Class->hasDeclaredDestructor())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000549 DeclareImplicitDestructor(Class);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000550}
551
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000552/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregora376d102010-07-02 21:50:04 +0000553/// special member function.
554static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
555 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000556 case DeclarationName::CXXConstructorName:
Douglas Gregora376d102010-07-02 21:50:04 +0000557 case DeclarationName::CXXDestructorName:
558 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000559
Douglas Gregora376d102010-07-02 21:50:04 +0000560 case DeclarationName::CXXOperatorName:
561 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000562
Douglas Gregora376d102010-07-02 21:50:04 +0000563 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000564 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000565 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000566
Douglas Gregora376d102010-07-02 21:50:04 +0000567 return false;
568}
569
570/// \brief If there are any implicit member functions with the given name
571/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000572static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregora376d102010-07-02 21:50:04 +0000573 DeclarationName Name,
574 const DeclContext *DC) {
575 if (!DC)
576 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000577
Douglas Gregora376d102010-07-02 21:50:04 +0000578 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000579 case DeclarationName::CXXConstructorName:
580 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor18274032010-07-03 00:47:00 +0000581 if (Record->getDefinition() &&
582 CanDeclareSpecialMemberFunction(S.Context, Record)) {
583 if (!Record->hasDeclaredDefaultConstructor())
584 S.DeclareImplicitDefaultConstructor(
585 const_cast<CXXRecordDecl *>(Record));
586 if (!Record->hasDeclaredCopyConstructor())
587 S.DeclareImplicitCopyConstructor(const_cast<CXXRecordDecl *>(Record));
588 }
Douglas Gregor22584312010-07-02 23:41:54 +0000589 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000590
Douglas Gregora376d102010-07-02 21:50:04 +0000591 case DeclarationName::CXXDestructorName:
592 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
593 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
594 CanDeclareSpecialMemberFunction(S.Context, Record))
595 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregora376d102010-07-02 21:50:04 +0000596 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000597
Douglas Gregora376d102010-07-02 21:50:04 +0000598 case DeclarationName::CXXOperatorName:
599 if (Name.getCXXOverloadedOperator() != OO_Equal)
600 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000601
Douglas Gregora376d102010-07-02 21:50:04 +0000602 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
603 if (Record->getDefinition() && !Record->hasDeclaredCopyAssignment() &&
604 CanDeclareSpecialMemberFunction(S.Context, Record))
605 S.DeclareImplicitCopyAssignment(const_cast<CXXRecordDecl *>(Record));
606 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000607
Douglas Gregora376d102010-07-02 21:50:04 +0000608 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000609 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000610 }
611}
Douglas Gregor4923aa22010-07-02 20:37:36 +0000612
John McCallf36e02d2009-10-09 21:13:30 +0000613// Adds all qualifying matches for a name within a decl context to the
614// given lookup result. Returns true if any matches were found.
Douglas Gregor85910982010-02-12 05:48:04 +0000615static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000616 bool Found = false;
617
Douglas Gregor4923aa22010-07-02 20:37:36 +0000618 // Lazily declare C++ special member functions.
Douglas Gregora376d102010-07-02 21:50:04 +0000619 if (S.getLangOptions().CPlusPlus)
620 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000621
Douglas Gregor4923aa22010-07-02 20:37:36 +0000622 // Perform lookup into this declaration context.
John McCalld7be78a2009-11-10 07:01:13 +0000623 DeclContext::lookup_const_iterator I, E;
Douglas Gregor48026d22010-01-11 18:40:55 +0000624 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall46460a62010-01-20 21:53:11 +0000625 NamedDecl *D = *I;
626 if (R.isAcceptableDecl(D)) {
627 R.addDecl(D);
Douglas Gregor48026d22010-01-11 18:40:55 +0000628 Found = true;
629 }
630 }
John McCallf36e02d2009-10-09 21:13:30 +0000631
Douglas Gregor85910982010-02-12 05:48:04 +0000632 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
633 return true;
634
Douglas Gregor48026d22010-01-11 18:40:55 +0000635 if (R.getLookupName().getNameKind()
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000636 != DeclarationName::CXXConversionFunctionName ||
637 R.getLookupName().getCXXNameType()->isDependentType() ||
638 !isa<CXXRecordDecl>(DC))
639 return Found;
640
641 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000642 // A specialization of a conversion function template is not found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000643 // name lookup. Instead, any conversion function templates visible in the
644 // context of the use are considered. [...]
645 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
646 if (!Record->isDefinition())
647 return Found;
648
649 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000650 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000651 UEnd = Unresolved->end(); U != UEnd; ++U) {
652 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
653 if (!ConvTemplate)
654 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000655
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000656 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000657 // add the conversion function template. When we deduce template
658 // arguments for specializations, we'll end up unifying the return
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000659 // type of the new declaration with the type of the function template.
660 if (R.isForRedeclaration()) {
661 R.addDecl(ConvTemplate);
662 Found = true;
663 continue;
664 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000665
Douglas Gregor48026d22010-01-11 18:40:55 +0000666 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000667 // [...] For each such operator, if argument deduction succeeds
668 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000669 // name lookup.
670 //
671 // When referencing a conversion function for any purpose other than
672 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000673 // result), perform template argument deduction and place the
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000674 // specialization into the result set. We do this to avoid forcing all
675 // callers to perform special deduction for conversion functions.
John McCall2a7fb272010-08-25 05:32:35 +0000676 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000677 FunctionDecl *Specialization = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000678
679 const FunctionProtoType *ConvProto
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000680 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
681 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3f477a12010-01-12 01:17:50 +0000682
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000683 // Compute the type of the function that we would expect the conversion
684 // function to have, if it were to match the name given.
685 // FIXME: Calling convention!
John McCalle23cf432010-12-14 08:05:40 +0000686 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
687 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
688 EPI.HasExceptionSpec = false;
689 EPI.HasAnyExceptionSpec = false;
690 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
John McCallf36e02d2009-10-09 21:13:30 +00001135 return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001136}
1137
John McCall6e247262009-10-10 05:48:19 +00001138/// @brief Perform qualified name lookup in the namespaces nominated by
1139/// using directives by the given context.
1140///
1141/// C++98 [namespace.qual]p2:
1142/// Given X::m (where X is a user-declared namespace), or given ::m
1143/// (where X is the global namespace), let S be the set of all
1144/// declarations of m in X and in the transitive closure of all
1145/// namespaces nominated by using-directives in X and its used
1146/// namespaces, except that using-directives are ignored in any
1147/// namespace, including X, directly containing one or more
1148/// declarations of m. No namespace is searched more than once in
1149/// the lookup of a name. If S is the empty set, the program is
1150/// ill-formed. Otherwise, if S has exactly one member, or if the
1151/// context of the reference is a using-declaration
1152/// (namespace.udecl), S is the required set of declarations of
1153/// m. Otherwise if the use of m is not one that allows a unique
1154/// declaration to be chosen from S, the program is ill-formed.
1155/// C++98 [namespace.qual]p5:
1156/// During the lookup of a qualified namespace member name, if the
1157/// lookup finds more than one declaration of the member, and if one
1158/// declaration introduces a class name or enumeration name and the
1159/// other declarations either introduce the same object, the same
1160/// enumerator or a set of functions, the non-type name hides the
1161/// class or enumeration name if and only if the declarations are
1162/// from the same namespace; otherwise (the declarations are from
1163/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +00001164static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +00001165 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +00001166 assert(StartDC->isFileContext() && "start context is not a file context");
1167
1168 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1169 DeclContext::udir_iterator E = StartDC->using_directives_end();
1170
1171 if (I == E) return false;
1172
1173 // We have at least added all these contexts to the queue.
1174 llvm::DenseSet<DeclContext*> Visited;
1175 Visited.insert(StartDC);
1176
1177 // We have not yet looked into these namespaces, much less added
1178 // their "using-children" to the queue.
1179 llvm::SmallVector<NamespaceDecl*, 8> Queue;
1180
1181 // We have already looked into the initial namespace; seed the queue
1182 // with its using-children.
1183 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001184 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6e247262009-10-10 05:48:19 +00001185 if (Visited.insert(ND).second)
1186 Queue.push_back(ND);
1187 }
1188
1189 // The easiest way to implement the restriction in [namespace.qual]p5
1190 // is to check whether any of the individual results found a tag
1191 // and, if so, to declare an ambiguity if the final result is not
1192 // a tag.
1193 bool FoundTag = false;
1194 bool FoundNonTag = false;
1195
John McCall7d384dd2009-11-18 07:57:50 +00001196 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001197
1198 bool Found = false;
1199 while (!Queue.empty()) {
1200 NamespaceDecl *ND = Queue.back();
1201 Queue.pop_back();
1202
1203 // We go through some convolutions here to avoid copying results
1204 // between LookupResults.
1205 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001206 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001207 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001208
1209 if (FoundDirect) {
1210 // First do any local hiding.
1211 DirectR.resolveKind();
1212
1213 // If the local result is a tag, remember that.
1214 if (DirectR.isSingleTagDecl())
1215 FoundTag = true;
1216 else
1217 FoundNonTag = true;
1218
1219 // Append the local results to the total results if necessary.
1220 if (UseLocal) {
1221 R.addAllDecls(LocalR);
1222 LocalR.clear();
1223 }
1224 }
1225
1226 // If we find names in this namespace, ignore its using directives.
1227 if (FoundDirect) {
1228 Found = true;
1229 continue;
1230 }
1231
1232 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1233 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1234 if (Visited.insert(Nom).second)
1235 Queue.push_back(Nom);
1236 }
1237 }
1238
1239 if (Found) {
1240 if (FoundTag && FoundNonTag)
1241 R.setAmbiguousQualifiedTagHiding();
1242 else
1243 R.resolveKind();
1244 }
1245
1246 return Found;
1247}
1248
Douglas Gregor8071e422010-08-15 06:18:01 +00001249/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001250static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor8071e422010-08-15 06:18:01 +00001251 CXXBasePath &Path,
1252 void *Name) {
1253 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001254
Douglas Gregor8071e422010-08-15 06:18:01 +00001255 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1256 Path.Decls = BaseRecord->lookup(N);
1257 return Path.Decls.first != Path.Decls.second;
1258}
1259
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001260/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001261/// static members, nested types, and enumerators.
1262template<typename InputIterator>
1263static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1264 Decl *D = (*First)->getUnderlyingDecl();
1265 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1266 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001267
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001268 if (isa<CXXMethodDecl>(D)) {
1269 // Determine whether all of the methods are static.
1270 bool AllMethodsAreStatic = true;
1271 for(; First != Last; ++First) {
1272 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001273
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001274 if (!isa<CXXMethodDecl>(D)) {
1275 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1276 break;
1277 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001278
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001279 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1280 AllMethodsAreStatic = false;
1281 break;
1282 }
1283 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001284
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001285 if (AllMethodsAreStatic)
1286 return true;
1287 }
1288
1289 return false;
1290}
1291
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001292/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001293///
1294/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1295/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001296/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001297///
1298/// Different lookup criteria can find different names. For example, a
1299/// particular scope can have both a struct and a function of the same
1300/// name, and each can be found by certain lookup criteria. For more
1301/// information about lookup criteria, see the documentation for the
1302/// class LookupCriteria.
1303///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001304/// \param R captures both the lookup criteria and any lookup results found.
1305///
1306/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001307/// search. If the lookup criteria permits, name lookup may also search
1308/// in the parent contexts or (for C++ classes) base classes.
1309///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001310/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001311/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001312///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001313/// \returns true if lookup succeeded, false if it failed.
1314bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1315 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001316 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001317
John McCalla24dc2e2009-11-17 02:14:36 +00001318 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001319 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001320
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001321 // Make sure that the declaration context is complete.
1322 assert((!isa<TagDecl>(LookupCtx) ||
1323 LookupCtx->isDependentContext() ||
1324 cast<TagDecl>(LookupCtx)->isDefinition() ||
1325 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1326 ->isBeingDefined()) &&
1327 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001328
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001329 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001330 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001331 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001332 if (isa<CXXRecordDecl>(LookupCtx))
1333 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001334 return true;
1335 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001336
John McCall6e247262009-10-10 05:48:19 +00001337 // Don't descend into implied contexts for redeclarations.
1338 // C++98 [namespace.qual]p6:
1339 // In a declaration for a namespace member in which the
1340 // declarator-id is a qualified-id, given that the qualified-id
1341 // for the namespace member has the form
1342 // nested-name-specifier unqualified-id
1343 // the unqualified-id shall name a member of the namespace
1344 // designated by the nested-name-specifier.
1345 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001346 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001347 return false;
1348
John McCalla24dc2e2009-11-17 02:14:36 +00001349 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001350 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001351 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001352
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001353 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001354 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001355 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor025291b2010-07-01 00:21:21 +00001356 if (!LookupRec || !LookupRec->getDefinition())
John McCallf36e02d2009-10-09 21:13:30 +00001357 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001358
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001359 // If we're performing qualified name lookup into a dependent class,
1360 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001361 // dependent base classes, then we either have to delay lookup until
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001362 // template instantiation time (at which point all bases will be available)
1363 // or we have to fail.
1364 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1365 LookupRec->hasAnyDependentBases()) {
1366 R.setNotFoundInCurrentInstantiation();
1367 return false;
1368 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001369
Douglas Gregor7176fff2009-01-15 00:26:24 +00001370 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001371 CXXBasePaths Paths;
1372 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001373
1374 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001375 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001376 switch (R.getLookupKind()) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001377 case LookupOrdinaryName:
1378 case LookupMemberName:
1379 case LookupRedeclarationWithLinkage:
1380 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1381 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001382
Douglas Gregora8f32e02009-10-06 17:59:45 +00001383 case LookupTagName:
1384 BaseCallback = &CXXRecordDecl::FindTagMember;
1385 break;
John McCall9f54ad42009-12-10 09:41:52 +00001386
Douglas Gregor8071e422010-08-15 06:18:01 +00001387 case LookupAnyName:
1388 BaseCallback = &LookupAnyMember;
1389 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001390
John McCall9f54ad42009-12-10 09:41:52 +00001391 case LookupUsingDeclName:
1392 // This lookup is for redeclarations only.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001393
Douglas Gregora8f32e02009-10-06 17:59:45 +00001394 case LookupOperatorName:
1395 case LookupNamespaceName:
1396 case LookupObjCProtocolName:
Chris Lattner337e5502011-02-18 01:27:55 +00001397 case LookupLabel:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001398 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001399 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001400
Douglas Gregora8f32e02009-10-06 17:59:45 +00001401 case LookupNestedNameSpecifierName:
1402 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1403 break;
1404 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001405
John McCalla24dc2e2009-11-17 02:14:36 +00001406 if (!LookupRec->lookupInBases(BaseCallback,
1407 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001408 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001409
John McCall92f88312010-01-23 00:46:32 +00001410 R.setNamingClass(LookupRec);
1411
Douglas Gregor7176fff2009-01-15 00:26:24 +00001412 // C++ [class.member.lookup]p2:
1413 // [...] If the resulting set of declarations are not all from
1414 // sub-objects of the same type, or the set has a nonstatic member
1415 // and includes members from distinct sub-objects, there is an
1416 // ambiguity and the program is ill-formed. Otherwise that set is
1417 // the result of the lookup.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001418 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001419 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001420 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001421
Douglas Gregora8f32e02009-10-06 17:59:45 +00001422 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001423 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001424 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001425
John McCall46460a62010-01-20 21:53:11 +00001426 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1427 // across all paths.
1428 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001429
Douglas Gregor7176fff2009-01-15 00:26:24 +00001430 // Determine whether we're looking at a distinct sub-object or not.
1431 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001432 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001433 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1434 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001435 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001436 }
1437
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001438 if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001439 != Context.getCanonicalType(PathElement.Base->getType())) {
1440 // We found members of the given name in two subobjects of
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001441 // different types. If the declaration sets aren't the same, this
1442 // this lookup is ambiguous.
1443 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1444 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1445 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1446 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001447
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001448 while (FirstD != FirstPath->Decls.second &&
1449 CurrentD != Path->Decls.second) {
1450 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1451 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1452 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001453
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001454 ++FirstD;
1455 ++CurrentD;
1456 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001457
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001458 if (FirstD == FirstPath->Decls.second &&
1459 CurrentD == Path->Decls.second)
1460 continue;
1461 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001462
John McCallf36e02d2009-10-09 21:13:30 +00001463 R.setAmbiguousBaseSubobjectTypes(Paths);
1464 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001465 }
1466
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001467 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001468 // We have a different subobject of the same type.
1469
1470 // C++ [class.member.lookup]p5:
1471 // A static member, a nested type or an enumerator defined in
1472 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001473 // has more than one base class subobject of type T.
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001474 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
Douglas Gregor7176fff2009-01-15 00:26:24 +00001475 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001476
Douglas Gregor7176fff2009-01-15 00:26:24 +00001477 // We have found a nonstatic member name in multiple, distinct
1478 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001479 R.setAmbiguousBaseSubobjects(Paths);
1480 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001481 }
1482 }
1483
1484 // Lookup in a base class succeeded; return these results.
1485
John McCallf36e02d2009-10-09 21:13:30 +00001486 DeclContext::lookup_iterator I, E;
John McCall92f88312010-01-23 00:46:32 +00001487 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1488 NamedDecl *D = *I;
1489 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1490 D->getAccess());
1491 R.addDecl(D, AS);
1492 }
John McCallf36e02d2009-10-09 21:13:30 +00001493 R.resolveKind();
1494 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001495}
1496
1497/// @brief Performs name lookup for a name that was parsed in the
1498/// source code, and may contain a C++ scope specifier.
1499///
1500/// This routine is a convenience routine meant to be called from
1501/// contexts that receive a name and an optional C++ scope specifier
1502/// (e.g., "N::M::x"). It will then perform either qualified or
1503/// unqualified name lookup (with LookupQualifiedName or LookupName,
1504/// respectively) on the given name and return those results.
1505///
1506/// @param S The scope from which unqualified name lookup will
1507/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001508///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001509/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001510///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001511/// @param EnteringContext Indicates whether we are going to enter the
1512/// context of the scope-specifier SS (if present).
1513///
John McCallf36e02d2009-10-09 21:13:30 +00001514/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001515bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001516 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001517 if (SS && SS->isInvalid()) {
1518 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001519 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001520 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001521 }
Mike Stump1eb44332009-09-09 15:08:12 +00001522
Douglas Gregor495c35d2009-08-25 22:51:20 +00001523 if (SS && SS->isSet()) {
1524 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001525 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001526 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001527 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001528 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001529
John McCalla24dc2e2009-11-17 02:14:36 +00001530 R.setContextRange(SS->getRange());
1531
1532 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001533 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001534
Douglas Gregor495c35d2009-08-25 22:51:20 +00001535 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001536 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001537 // Name lookup can't find anything in this case.
John McCallf36e02d2009-10-09 21:13:30 +00001538 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001539 }
1540
Mike Stump1eb44332009-09-09 15:08:12 +00001541 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001542 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001543}
1544
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001545
Douglas Gregor7176fff2009-01-15 00:26:24 +00001546/// @brief Produce a diagnostic describing the ambiguity that resulted
1547/// from name lookup.
1548///
1549/// @param Result The ambiguous name lookup result.
Mike Stump1eb44332009-09-09 15:08:12 +00001550///
Douglas Gregor7176fff2009-01-15 00:26:24 +00001551/// @param Name The name of the entity that name lookup was
1552/// searching for.
1553///
1554/// @param NameLoc The location of the name within the source code.
1555///
1556/// @param LookupRange A source range that provides more
1557/// source-location information concerning the lookup itself. For
1558/// example, this range might highlight a nested-name-specifier that
1559/// precedes the name.
1560///
1561/// @returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001562bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001563 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1564
John McCalla24dc2e2009-11-17 02:14:36 +00001565 DeclarationName Name = Result.getLookupName();
1566 SourceLocation NameLoc = Result.getNameLoc();
1567 SourceRange LookupRange = Result.getContextRange();
1568
John McCall6e247262009-10-10 05:48:19 +00001569 switch (Result.getAmbiguityKind()) {
1570 case LookupResult::AmbiguousBaseSubobjects: {
1571 CXXBasePaths *Paths = Result.getBasePaths();
1572 QualType SubobjectType = Paths->front().back().Base->getType();
1573 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1574 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1575 << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001576
John McCall6e247262009-10-10 05:48:19 +00001577 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1578 while (isa<CXXMethodDecl>(*Found) &&
1579 cast<CXXMethodDecl>(*Found)->isStatic())
1580 ++Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001581
John McCall6e247262009-10-10 05:48:19 +00001582 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001583
John McCall6e247262009-10-10 05:48:19 +00001584 return true;
1585 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001586
John McCall6e247262009-10-10 05:48:19 +00001587 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001588 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1589 << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001590
John McCall6e247262009-10-10 05:48:19 +00001591 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001592 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001593 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1594 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001595 Path != PathEnd; ++Path) {
1596 Decl *D = *Path->Decls.first;
1597 if (DeclsPrinted.insert(D).second)
1598 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1599 }
1600
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001601 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001602 }
1603
John McCall6e247262009-10-10 05:48:19 +00001604 case LookupResult::AmbiguousTagHiding: {
1605 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001606
John McCall6e247262009-10-10 05:48:19 +00001607 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1608
1609 LookupResult::iterator DI, DE = Result.end();
1610 for (DI = Result.begin(); DI != DE; ++DI)
1611 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1612 TagDecls.insert(TD);
1613 Diag(TD->getLocation(), diag::note_hidden_tag);
1614 }
1615
1616 for (DI = Result.begin(); DI != DE; ++DI)
1617 if (!isa<TagDecl>(*DI))
1618 Diag((*DI)->getLocation(), diag::note_hiding_object);
1619
1620 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001621 LookupResult::Filter F = Result.makeFilter();
1622 while (F.hasNext()) {
1623 if (TagDecls.count(F.next()))
1624 F.erase();
1625 }
1626 F.done();
John McCall6e247262009-10-10 05:48:19 +00001627
1628 return true;
1629 }
1630
1631 case LookupResult::AmbiguousReference: {
1632 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001633
John McCall6e247262009-10-10 05:48:19 +00001634 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1635 for (; DI != DE; ++DI)
1636 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001637
John McCall6e247262009-10-10 05:48:19 +00001638 return true;
1639 }
1640 }
1641
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001642 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001643 return true;
1644}
Douglas Gregorfa047642009-02-04 00:32:51 +00001645
John McCallc7e04da2010-05-28 18:45:08 +00001646namespace {
1647 struct AssociatedLookup {
1648 AssociatedLookup(Sema &S,
1649 Sema::AssociatedNamespaceSet &Namespaces,
1650 Sema::AssociatedClassSet &Classes)
1651 : S(S), Namespaces(Namespaces), Classes(Classes) {
1652 }
1653
1654 Sema &S;
1655 Sema::AssociatedNamespaceSet &Namespaces;
1656 Sema::AssociatedClassSet &Classes;
1657 };
1658}
1659
Mike Stump1eb44332009-09-09 15:08:12 +00001660static void
John McCallc7e04da2010-05-28 18:45:08 +00001661addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCall6ff07852009-08-07 22:18:02 +00001662
Douglas Gregor54022952010-04-30 07:08:38 +00001663static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1664 DeclContext *Ctx) {
1665 // Add the associated namespace for this class.
1666
1667 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1668 // be a locally scoped record.
1669
Sebastian Redl410c4f22010-08-31 20:53:31 +00001670 // We skip out of inline namespaces. The innermost non-inline namespace
1671 // contains all names of all its nested inline namespaces anyway, so we can
1672 // replace the entire inline namespace tree with its root.
1673 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1674 Ctx->isInlineNamespace())
Douglas Gregor54022952010-04-30 07:08:38 +00001675 Ctx = Ctx->getParent();
1676
John McCall6ff07852009-08-07 22:18:02 +00001677 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001678 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001679}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001680
Mike Stump1eb44332009-09-09 15:08:12 +00001681// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001682// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001683static void
John McCallc7e04da2010-05-28 18:45:08 +00001684addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1685 const TemplateArgument &Arg) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001686 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001687 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001688 switch (Arg.getKind()) {
1689 case TemplateArgument::Null:
1690 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001691
Douglas Gregor69be8d62009-07-08 07:51:57 +00001692 case TemplateArgument::Type:
1693 // [...] the namespaces and classes associated with the types of the
1694 // template arguments provided for template type parameters (excluding
1695 // template template parameters)
John McCallc7e04da2010-05-28 18:45:08 +00001696 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor69be8d62009-07-08 07:51:57 +00001697 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001698
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001699 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001700 case TemplateArgument::TemplateExpansion: {
Mike Stump1eb44332009-09-09 15:08:12 +00001701 // [...] the namespaces in which any template template arguments are
1702 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001703 // template template arguments are defined.
Douglas Gregora7fc9012011-01-05 18:58:31 +00001704 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump1eb44332009-09-09 15:08:12 +00001705 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001706 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001707 DeclContext *Ctx = ClassTemplate->getDeclContext();
1708 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001709 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001710 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001711 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001712 }
1713 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001714 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001715
Douglas Gregor788cd062009-11-11 01:00:40 +00001716 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001717 case TemplateArgument::Integral:
1718 case TemplateArgument::Expression:
Mike Stump1eb44332009-09-09 15:08:12 +00001719 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001720 // associated namespaces. ]
1721 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001722
Douglas Gregor69be8d62009-07-08 07:51:57 +00001723 case TemplateArgument::Pack:
1724 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1725 PEnd = Arg.pack_end();
1726 P != PEnd; ++P)
John McCallc7e04da2010-05-28 18:45:08 +00001727 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001728 break;
1729 }
1730}
1731
Douglas Gregorfa047642009-02-04 00:32:51 +00001732// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001733// argument-dependent lookup with an argument of class type
1734// (C++ [basic.lookup.koenig]p2).
1735static void
John McCallc7e04da2010-05-28 18:45:08 +00001736addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1737 CXXRecordDecl *Class) {
1738
1739 // Just silently ignore anything whose name is __va_list_tag.
1740 if (Class->getDeclName() == Result.S.VAListTagName)
1741 return;
1742
Douglas Gregorfa047642009-02-04 00:32:51 +00001743 // C++ [basic.lookup.koenig]p2:
1744 // [...]
1745 // -- If T is a class type (including unions), its associated
1746 // classes are: the class itself; the class of which it is a
1747 // member, if any; and its direct and indirect base
1748 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001749 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001750
1751 // Add the class of which it is a member, if any.
1752 DeclContext *Ctx = Class->getDeclContext();
1753 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001754 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001755 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001756 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001757
Douglas Gregorfa047642009-02-04 00:32:51 +00001758 // Add the class itself. If we've already seen this class, we don't
1759 // need to visit base classes.
John McCallc7e04da2010-05-28 18:45:08 +00001760 if (!Result.Classes.insert(Class))
Douglas Gregorfa047642009-02-04 00:32:51 +00001761 return;
1762
Mike Stump1eb44332009-09-09 15:08:12 +00001763 // -- If T is a template-id, its associated namespaces and classes are
1764 // the namespace in which the template is defined; for member
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001765 // templates, the member template's class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001766 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001767 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001768 // namespaces in which any template template arguments are defined; and
1769 // the classes in which any member templates used as template template
1770 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001771 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001772 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001773 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1774 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1775 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001776 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001777 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001778 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001779
Douglas Gregor69be8d62009-07-08 07:51:57 +00001780 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1781 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallc7e04da2010-05-28 18:45:08 +00001782 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001783 }
Mike Stump1eb44332009-09-09 15:08:12 +00001784
John McCall86ff3082010-02-04 22:26:26 +00001785 // Only recurse into base classes for complete types.
1786 if (!Class->hasDefinition()) {
1787 // FIXME: we might need to instantiate templates here
1788 return;
1789 }
1790
Douglas Gregorfa047642009-02-04 00:32:51 +00001791 // Add direct and indirect base classes along with their associated
1792 // namespaces.
1793 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1794 Bases.push_back(Class);
1795 while (!Bases.empty()) {
1796 // Pop this class off the stack.
1797 Class = Bases.back();
1798 Bases.pop_back();
1799
1800 // Visit the base classes.
1801 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1802 BaseEnd = Class->bases_end();
1803 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001804 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001805 // In dependent contexts, we do ADL twice, and the first time around,
1806 // the base type might be a dependent TemplateSpecializationType, or a
1807 // TemplateTypeParmType. If that happens, simply ignore it.
1808 // FIXME: If we want to support export, we probably need to add the
1809 // namespace of the template in a TemplateSpecializationType, or even
1810 // the classes and namespaces of known non-dependent arguments.
1811 if (!BaseType)
1812 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001813 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001814 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001815 // Find the associated namespace for this base class.
1816 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallc7e04da2010-05-28 18:45:08 +00001817 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001818
1819 // Make sure we visit the bases of this base class.
1820 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1821 Bases.push_back(BaseDecl);
1822 }
1823 }
1824 }
1825}
1826
1827// \brief Add the associated classes and namespaces for
1828// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001829// (C++ [basic.lookup.koenig]p2).
1830static void
John McCallc7e04da2010-05-28 18:45:08 +00001831addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001832 // C++ [basic.lookup.koenig]p2:
1833 //
1834 // For each argument type T in the function call, there is a set
1835 // of zero or more associated namespaces and a set of zero or more
1836 // associated classes to be considered. The sets of namespaces and
1837 // classes is determined entirely by the types of the function
1838 // arguments (and the namespace of any template template
1839 // argument). Typedef names and using-declarations used to specify
1840 // the types do not contribute to this set. The sets of namespaces
1841 // and classes are determined in the following way:
Douglas Gregorfa047642009-02-04 00:32:51 +00001842
John McCallfa4edcf2010-05-28 06:08:54 +00001843 llvm::SmallVector<const Type *, 16> Queue;
1844 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1845
Douglas Gregorfa047642009-02-04 00:32:51 +00001846 while (true) {
John McCallfa4edcf2010-05-28 06:08:54 +00001847 switch (T->getTypeClass()) {
1848
1849#define TYPE(Class, Base)
1850#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1851#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1852#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1853#define ABSTRACT_TYPE(Class, Base)
1854#include "clang/AST/TypeNodes.def"
1855 // T is canonical. We can also ignore dependent types because
1856 // we don't need to do ADL at the definition point, but if we
1857 // wanted to implement template export (or if we find some other
1858 // use for associated classes and namespaces...) this would be
1859 // wrong.
Douglas Gregorfa047642009-02-04 00:32:51 +00001860 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00001861
John McCallfa4edcf2010-05-28 06:08:54 +00001862 // -- If T is a pointer to U or an array of U, its associated
1863 // namespaces and classes are those associated with U.
1864 case Type::Pointer:
1865 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1866 continue;
1867 case Type::ConstantArray:
1868 case Type::IncompleteArray:
1869 case Type::VariableArray:
1870 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1871 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001872
John McCallfa4edcf2010-05-28 06:08:54 +00001873 // -- If T is a fundamental type, its associated sets of
1874 // namespaces and classes are both empty.
1875 case Type::Builtin:
1876 break;
1877
1878 // -- If T is a class type (including unions), its associated
1879 // classes are: the class itself; the class of which it is a
1880 // member, if any; and its direct and indirect base
1881 // classes. Its associated namespaces are the namespaces in
1882 // which its associated classes are defined.
1883 case Type::Record: {
1884 CXXRecordDecl *Class
1885 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001886 addAssociatedClassesAndNamespaces(Result, Class);
John McCallfa4edcf2010-05-28 06:08:54 +00001887 break;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001888 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00001889
John McCallfa4edcf2010-05-28 06:08:54 +00001890 // -- If T is an enumeration type, its associated namespace is
1891 // the namespace in which it is defined. If it is class
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001892 // member, its associated class is the member's class; else
John McCallfa4edcf2010-05-28 06:08:54 +00001893 // it has no associated class.
1894 case Type::Enum: {
1895 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001896
John McCallfa4edcf2010-05-28 06:08:54 +00001897 DeclContext *Ctx = Enum->getDeclContext();
1898 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001899 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001900
John McCallfa4edcf2010-05-28 06:08:54 +00001901 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001902 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001903
John McCallfa4edcf2010-05-28 06:08:54 +00001904 break;
1905 }
1906
1907 // -- If T is a function type, its associated namespaces and
1908 // classes are those associated with the function parameter
1909 // types and those associated with the return type.
1910 case Type::FunctionProto: {
1911 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1912 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1913 ArgEnd = Proto->arg_type_end();
1914 Arg != ArgEnd; ++Arg)
1915 Queue.push_back(Arg->getTypePtr());
1916 // fallthrough
1917 }
1918 case Type::FunctionNoProto: {
1919 const FunctionType *FnType = cast<FunctionType>(T);
1920 T = FnType->getResultType().getTypePtr();
1921 continue;
1922 }
1923
1924 // -- If T is a pointer to a member function of a class X, its
1925 // associated namespaces and classes are those associated
1926 // with the function parameter types and return type,
1927 // together with those associated with X.
1928 //
1929 // -- If T is a pointer to a data member of class X, its
1930 // associated namespaces and classes are those associated
1931 // with the member type together with those associated with
1932 // X.
1933 case Type::MemberPointer: {
1934 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1935
1936 // Queue up the class type into which this points.
1937 Queue.push_back(MemberPtr->getClass());
1938
1939 // And directly continue with the pointee type.
1940 T = MemberPtr->getPointeeType().getTypePtr();
1941 continue;
1942 }
1943
1944 // As an extension, treat this like a normal pointer.
1945 case Type::BlockPointer:
1946 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1947 continue;
1948
1949 // References aren't covered by the standard, but that's such an
1950 // obvious defect that we cover them anyway.
1951 case Type::LValueReference:
1952 case Type::RValueReference:
1953 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1954 continue;
1955
1956 // These are fundamental types.
1957 case Type::Vector:
1958 case Type::ExtVector:
1959 case Type::Complex:
1960 break;
1961
1962 // These are ignored by ADL.
1963 case Type::ObjCObject:
1964 case Type::ObjCInterface:
1965 case Type::ObjCObjectPointer:
1966 break;
1967 }
1968
1969 if (Queue.empty()) break;
1970 T = Queue.back();
1971 Queue.pop_back();
Douglas Gregorfa047642009-02-04 00:32:51 +00001972 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001973}
1974
1975/// \brief Find the associated classes and namespaces for
1976/// argument-dependent lookup for a call with the given set of
1977/// arguments.
1978///
1979/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00001980/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00001981/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001982void
Douglas Gregorfa047642009-02-04 00:32:51 +00001983Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1984 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001985 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001986 AssociatedNamespaces.clear();
1987 AssociatedClasses.clear();
1988
John McCallc7e04da2010-05-28 18:45:08 +00001989 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
1990
Douglas Gregorfa047642009-02-04 00:32:51 +00001991 // C++ [basic.lookup.koenig]p2:
1992 // For each argument type T in the function call, there is a set
1993 // of zero or more associated namespaces and a set of zero or more
1994 // associated classes to be considered. The sets of namespaces and
1995 // classes is determined entirely by the types of the function
1996 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00001997 // argument).
Douglas Gregorfa047642009-02-04 00:32:51 +00001998 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1999 Expr *Arg = Args[ArgIdx];
2000
2001 if (Arg->getType() != Context.OverloadTy) {
John McCallc7e04da2010-05-28 18:45:08 +00002002 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002003 continue;
2004 }
2005
2006 // [...] In addition, if the argument is the name or address of a
2007 // set of overloaded functions and/or function templates, its
2008 // associated classes and namespaces are the union of those
2009 // associated with each of the members of the set: the namespace
2010 // in which the function or function template is defined and the
2011 // classes and namespaces associated with its (non-dependent)
2012 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00002013 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00002014 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCall2de56d12010-08-25 11:45:40 +00002015 if (unaryOp->getOpcode() == UO_AddrOf)
John McCallba135432009-11-21 08:51:07 +00002016 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002017
John McCallc7e04da2010-05-28 18:45:08 +00002018 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2019 if (!ULE) continue;
John McCallba135432009-11-21 08:51:07 +00002020
John McCallc7e04da2010-05-28 18:45:08 +00002021 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2022 I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00002023 // Look through any using declarations to find the underlying function.
2024 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002025
Chandler Carruthbd647292009-12-29 06:17:27 +00002026 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2027 if (!FDecl)
2028 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002029
2030 // Add the classes and namespaces associated with the parameter
2031 // types and return type of this function.
John McCallc7e04da2010-05-28 18:45:08 +00002032 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002033 }
2034 }
2035}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002036
2037/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2038/// an acceptable non-member overloaded operator for a call whose
2039/// arguments have types T1 (and, if non-empty, T2). This routine
2040/// implements the check in C++ [over.match.oper]p3b2 concerning
2041/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00002042static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002043IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2044 QualType T1, QualType T2,
2045 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00002046 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2047 return true;
2048
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002049 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2050 return true;
2051
John McCall183700f2009-09-21 23:43:11 +00002052 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002053 if (Proto->getNumArgs() < 1)
2054 return false;
2055
2056 if (T1->isEnumeralType()) {
2057 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002058 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002059 return true;
2060 }
2061
2062 if (Proto->getNumArgs() < 2)
2063 return false;
2064
2065 if (!T2.isNull() && T2->isEnumeralType()) {
2066 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002067 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002068 return true;
2069 }
2070
2071 return false;
2072}
2073
John McCall7d384dd2009-11-18 07:57:50 +00002074NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002075 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00002076 LookupNameKind NameKind,
2077 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002078 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00002079 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00002080 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00002081}
2082
Douglas Gregor6e378de2009-04-23 23:18:26 +00002083/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002084ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002085 SourceLocation IdLoc) {
2086 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2087 LookupObjCProtocolName);
Douglas Gregor6e378de2009-04-23 23:18:26 +00002088 return cast_or_null<ObjCProtocolDecl>(D);
2089}
2090
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002091void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00002092 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00002093 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002094 // C++ [over.match.oper]p3:
2095 // -- The set of non-member candidates is the result of the
2096 // unqualified lookup of operator@ in the context of the
2097 // expression according to the usual rules for name lookup in
2098 // unqualified function calls (3.4.2) except that all member
2099 // functions are ignored. However, if no operand has a class
2100 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00002101 // that have a first parameter of type T1 or "reference to
2102 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002103 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00002104 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002105 // when T2 is an enumeration type, are candidate functions.
2106 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00002107 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2108 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002109
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002110 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2111
John McCallf36e02d2009-10-09 21:13:30 +00002112 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002113 return;
2114
2115 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2116 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002117 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2118 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002119 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002120 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00002121 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002122 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00002123 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00002124 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00002125 // later?
2126 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002127 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00002128 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002129 }
2130}
2131
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002132/// \brief Look up the constructors for the given class.
2133DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Douglas Gregor22584312010-07-02 23:41:54 +00002134 // If the copy constructor has not yet been declared, do so now.
Douglas Gregor18274032010-07-03 00:47:00 +00002135 if (CanDeclareSpecialMemberFunction(Context, Class)) {
2136 if (!Class->hasDeclaredDefaultConstructor())
2137 DeclareImplicitDefaultConstructor(Class);
2138 if (!Class->hasDeclaredCopyConstructor())
2139 DeclareImplicitCopyConstructor(Class);
2140 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002141
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002142 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2143 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2144 return Class->lookup(Name);
2145}
2146
Douglas Gregordb89f282010-07-01 22:47:18 +00002147/// \brief Look for the destructor of the given class.
2148///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002149/// During semantic analysis, this routine should be used in lieu of
Douglas Gregordb89f282010-07-01 22:47:18 +00002150/// CXXRecordDecl::getDestructor().
2151///
2152/// \returns The destructor for this class.
2153CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Douglas Gregor4923aa22010-07-02 20:37:36 +00002154 // If the destructor has not yet been declared, do so now.
2155 if (CanDeclareSpecialMemberFunction(Context, Class) &&
2156 !Class->hasDeclaredDestructor())
2157 DeclareImplicitDestructor(Class);
2158
Douglas Gregordb89f282010-07-01 22:47:18 +00002159 return Class->getDestructor();
2160}
2161
John McCall7edb5fd2010-01-26 07:16:45 +00002162void ADLResult::insert(NamedDecl *New) {
2163 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2164
2165 // If we haven't yet seen a decl for this key, or the last decl
2166 // was exactly this one, we're done.
2167 if (Old == 0 || Old == New) {
2168 Old = New;
2169 return;
2170 }
2171
2172 // Otherwise, decide which is a more recent redeclaration.
2173 FunctionDecl *OldFD, *NewFD;
2174 if (isa<FunctionTemplateDecl>(New)) {
2175 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2176 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2177 } else {
2178 OldFD = cast<FunctionDecl>(Old);
2179 NewFD = cast<FunctionDecl>(New);
2180 }
2181
2182 FunctionDecl *Cursor = NewFD;
2183 while (true) {
2184 Cursor = Cursor->getPreviousDeclaration();
2185
2186 // If we got to the end without finding OldFD, OldFD is the newer
2187 // declaration; leave things as they are.
2188 if (!Cursor) return;
2189
2190 // If we do find OldFD, then NewFD is newer.
2191 if (Cursor == OldFD) break;
2192
2193 // Otherwise, keep looking.
2194 }
2195
2196 Old = New;
2197}
2198
Sebastian Redl644be852009-10-23 19:23:15 +00002199void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002200 Expr **Args, unsigned NumArgs,
John McCall7edb5fd2010-01-26 07:16:45 +00002201 ADLResult &Result) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002202 // Find all of the associated namespaces and classes based on the
2203 // arguments we have.
2204 AssociatedNamespaceSet AssociatedNamespaces;
2205 AssociatedClassSet AssociatedClasses;
Mike Stump1eb44332009-09-09 15:08:12 +00002206 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCall6ff07852009-08-07 22:18:02 +00002207 AssociatedNamespaces,
2208 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002209
Sebastian Redl644be852009-10-23 19:23:15 +00002210 QualType T1, T2;
2211 if (Operator) {
2212 T1 = Args[0]->getType();
2213 if (NumArgs >= 2)
2214 T2 = Args[1]->getType();
2215 }
2216
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002217 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002218 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2219 // and let Y be the lookup set produced by argument dependent
2220 // lookup (defined as follows). If X contains [...] then Y is
2221 // empty. Otherwise Y is the set of declarations found in the
2222 // namespaces associated with the argument types as described
2223 // below. The set of declarations found by the lookup of the name
2224 // is the union of X and Y.
2225 //
2226 // Here, we compute Y and add its members to the overloaded
2227 // candidate set.
2228 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002229 NSEnd = AssociatedNamespaces.end();
2230 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002231 // When considering an associated namespace, the lookup is the
2232 // same as the lookup performed when the associated namespace is
2233 // used as a qualifier (3.4.3.2) except that:
2234 //
2235 // -- Any using-directives in the associated namespace are
2236 // ignored.
2237 //
John McCall6ff07852009-08-07 22:18:02 +00002238 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002239 // associated classes are visible within their respective
2240 // namespaces even if they are not visible during an ordinary
2241 // lookup (11.4).
2242 DeclContext::lookup_iterator I, E;
John McCall3f9a8a62009-08-11 06:59:38 +00002243 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall6e266892010-01-26 03:27:55 +00002244 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00002245 // If the only declaration here is an ordinary friend, consider
2246 // it only if it was declared in an associated classes.
2247 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00002248 DeclContext *LexDC = D->getLexicalDeclContext();
2249 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2250 continue;
2251 }
Mike Stump1eb44332009-09-09 15:08:12 +00002252
John McCalla113e722010-01-26 06:04:06 +00002253 if (isa<UsingShadowDecl>(D))
2254 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00002255
John McCalla113e722010-01-26 06:04:06 +00002256 if (isa<FunctionDecl>(D)) {
2257 if (Operator &&
2258 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2259 T1, T2, Context))
2260 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00002261 } else if (!isa<FunctionTemplateDecl>(D))
2262 continue;
2263
2264 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00002265 }
2266 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002267}
Douglas Gregor546be3c2009-12-30 17:04:44 +00002268
2269//----------------------------------------------------------------------------
2270// Search for all visible declarations.
2271//----------------------------------------------------------------------------
2272VisibleDeclConsumer::~VisibleDeclConsumer() { }
2273
2274namespace {
2275
2276class ShadowContextRAII;
2277
2278class VisibleDeclsRecord {
2279public:
2280 /// \brief An entry in the shadow map, which is optimized to store a
2281 /// single declaration (the common case) but can also store a list
2282 /// of declarations.
2283 class ShadowMapEntry {
2284 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002285
Douglas Gregor546be3c2009-12-30 17:04:44 +00002286 /// \brief Contains either the solitary NamedDecl * or a vector
2287 /// of declarations.
2288 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2289
2290 public:
2291 ShadowMapEntry() : DeclOrVector() { }
2292
2293 void Add(NamedDecl *ND);
2294 void Destroy();
2295
2296 // Iteration.
Argyrios Kyrtzidisaef05d72011-02-19 04:02:34 +00002297 typedef NamedDecl * const *iterator;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002298 iterator begin();
2299 iterator end();
2300 };
2301
2302private:
2303 /// \brief A mapping from declaration names to the declarations that have
2304 /// this name within a particular scope.
2305 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2306
2307 /// \brief A list of shadow maps, which is used to model name hiding.
2308 std::list<ShadowMap> ShadowMaps;
2309
2310 /// \brief The declaration contexts we have already visited.
2311 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2312
2313 friend class ShadowContextRAII;
2314
2315public:
2316 /// \brief Determine whether we have already visited this context
2317 /// (and, if not, note that we are going to visit that context now).
2318 bool visitedContext(DeclContext *Ctx) {
2319 return !VisitedContexts.insert(Ctx);
2320 }
2321
Douglas Gregor8071e422010-08-15 06:18:01 +00002322 bool alreadyVisitedContext(DeclContext *Ctx) {
2323 return VisitedContexts.count(Ctx);
2324 }
2325
Douglas Gregor546be3c2009-12-30 17:04:44 +00002326 /// \brief Determine whether the given declaration is hidden in the
2327 /// current scope.
2328 ///
2329 /// \returns the declaration that hides the given declaration, or
2330 /// NULL if no such declaration exists.
2331 NamedDecl *checkHidden(NamedDecl *ND);
2332
2333 /// \brief Add a declaration to the current shadow map.
2334 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2335};
2336
2337/// \brief RAII object that records when we've entered a shadow context.
2338class ShadowContextRAII {
2339 VisibleDeclsRecord &Visible;
2340
2341 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2342
2343public:
2344 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2345 Visible.ShadowMaps.push_back(ShadowMap());
2346 }
2347
2348 ~ShadowContextRAII() {
2349 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2350 EEnd = Visible.ShadowMaps.back().end();
2351 E != EEnd;
2352 ++E)
2353 E->second.Destroy();
2354
2355 Visible.ShadowMaps.pop_back();
2356 }
2357};
2358
2359} // end anonymous namespace
2360
2361void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2362 if (DeclOrVector.isNull()) {
2363 // 0 - > 1 elements: just set the single element information.
2364 DeclOrVector = ND;
2365 return;
2366 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002367
Douglas Gregor546be3c2009-12-30 17:04:44 +00002368 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2369 // 1 -> 2 elements: create the vector of results and push in the
2370 // existing declaration.
2371 DeclVector *Vec = new DeclVector;
2372 Vec->push_back(PrevND);
2373 DeclOrVector = Vec;
2374 }
2375
2376 // Add the new element to the end of the vector.
2377 DeclOrVector.get<DeclVector*>()->push_back(ND);
2378}
2379
2380void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2381 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2382 delete Vec;
2383 DeclOrVector = ((NamedDecl *)0);
2384 }
2385}
2386
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002387VisibleDeclsRecord::ShadowMapEntry::iterator
Douglas Gregor546be3c2009-12-30 17:04:44 +00002388VisibleDeclsRecord::ShadowMapEntry::begin() {
2389 if (DeclOrVector.isNull())
2390 return 0;
2391
Argyrios Kyrtzidisaef05d72011-02-19 04:02:34 +00002392 if (DeclOrVector.is<NamedDecl *>())
2393 return DeclOrVector.getAddrOf<NamedDecl *>();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002394
2395 return DeclOrVector.get<DeclVector *>()->begin();
2396}
2397
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002398VisibleDeclsRecord::ShadowMapEntry::iterator
Douglas Gregor546be3c2009-12-30 17:04:44 +00002399VisibleDeclsRecord::ShadowMapEntry::end() {
2400 if (DeclOrVector.isNull())
2401 return 0;
2402
2403 if (DeclOrVector.dyn_cast<NamedDecl *>())
2404 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2405
2406 return DeclOrVector.get<DeclVector *>()->end();
2407}
2408
2409NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002410 // Look through using declarations.
2411 ND = ND->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002412
Douglas Gregor546be3c2009-12-30 17:04:44 +00002413 unsigned IDNS = ND->getIdentifierNamespace();
2414 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2415 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2416 SM != SMEnd; ++SM) {
2417 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2418 if (Pos == SM->end())
2419 continue;
2420
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002421 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00002422 IEnd = Pos->second.end();
2423 I != IEnd; ++I) {
2424 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002425 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002426 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor546be3c2009-12-30 17:04:44 +00002427 Decl::IDNS_ObjCProtocol)))
2428 continue;
2429
2430 // Protocols are in distinct namespaces from everything else.
2431 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2432 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2433 (*I)->getIdentifierNamespace() != IDNS)
2434 continue;
2435
Douglas Gregor0cc84042010-01-14 15:47:35 +00002436 // Functions and function templates in the same scope overload
2437 // rather than hide. FIXME: Look for hiding based on function
2438 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002439 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002440 ND->isFunctionOrFunctionTemplate() &&
2441 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002442 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002443
Douglas Gregor546be3c2009-12-30 17:04:44 +00002444 // We've found a declaration that hides this one.
2445 return *I;
2446 }
2447 }
2448
2449 return 0;
2450}
2451
2452static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2453 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002454 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002455 VisibleDeclConsumer &Consumer,
2456 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00002457 if (!Ctx)
2458 return;
2459
Douglas Gregor546be3c2009-12-30 17:04:44 +00002460 // Make sure we don't visit the same context twice.
2461 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2462 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002463
Douglas Gregor4923aa22010-07-02 20:37:36 +00002464 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2465 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2466
Douglas Gregor546be3c2009-12-30 17:04:44 +00002467 // Enumerate all of the results in this context.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002468 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002469 CurCtx = CurCtx->getNextContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002470 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00002471 DEnd = CurCtx->decls_end();
2472 D != DEnd; ++D) {
Douglas Gregor70c23352010-12-09 21:44:02 +00002473 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002474 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002475 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002476 Visited.add(ND);
2477 }
Douglas Gregor70c23352010-12-09 21:44:02 +00002478 } else if (ObjCForwardProtocolDecl *ForwardProto
2479 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
2480 for (ObjCForwardProtocolDecl::protocol_iterator
2481 P = ForwardProto->protocol_begin(),
2482 PEnd = ForwardProto->protocol_end();
2483 P != PEnd;
2484 ++P) {
2485 if (Result.isAcceptableDecl(*P)) {
2486 Consumer.FoundDecl(*P, Visited.checkHidden(*P), InBaseClass);
2487 Visited.add(*P);
2488 }
2489 }
Douglas Gregord98abd82011-02-16 01:39:26 +00002490 } else if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D)) {
2491 for (ObjCClassDecl::iterator I = Class->begin(), IEnd = Class->end();
2492 I != IEnd; ++I) {
2493 ObjCInterfaceDecl *IFace = I->getInterface();
2494 if (Result.isAcceptableDecl(IFace)) {
2495 Consumer.FoundDecl(IFace, Visited.checkHidden(IFace), InBaseClass);
2496 Visited.add(IFace);
2497 }
2498 }
Douglas Gregor70c23352010-12-09 21:44:02 +00002499 }
Douglas Gregord98abd82011-02-16 01:39:26 +00002500
Sebastian Redl410c4f22010-08-31 20:53:31 +00002501 // Visit transparent contexts and inline namespaces inside this context.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002502 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
Sebastian Redl410c4f22010-08-31 20:53:31 +00002503 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Douglas Gregor0cc84042010-01-14 15:47:35 +00002504 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002505 Consumer, Visited);
2506 }
2507 }
2508 }
2509
2510 // Traverse using directives for qualified name lookup.
2511 if (QualifiedNameLookup) {
2512 ShadowContextRAII Shadow(Visited);
2513 DeclContext::udir_iterator I, E;
2514 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002515 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002516 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002517 }
2518 }
2519
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002520 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002521 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00002522 if (!Record->hasDefinition())
2523 return;
2524
Douglas Gregor546be3c2009-12-30 17:04:44 +00002525 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2526 BEnd = Record->bases_end();
2527 B != BEnd; ++B) {
2528 QualType BaseType = B->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002529
Douglas Gregor546be3c2009-12-30 17:04:44 +00002530 // Don't look into dependent bases, because name lookup can't look
2531 // there anyway.
2532 if (BaseType->isDependentType())
2533 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002534
Douglas Gregor546be3c2009-12-30 17:04:44 +00002535 const RecordType *Record = BaseType->getAs<RecordType>();
2536 if (!Record)
2537 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002538
Douglas Gregor546be3c2009-12-30 17:04:44 +00002539 // FIXME: It would be nice to be able to determine whether referencing
2540 // a particular member would be ambiguous. For example, given
2541 //
2542 // struct A { int member; };
2543 // struct B { int member; };
2544 // struct C : A, B { };
2545 //
2546 // void f(C *c) { c->### }
2547 //
2548 // accessing 'member' would result in an ambiguity. However, we
2549 // could be smart enough to qualify the member with the base
2550 // class, e.g.,
2551 //
2552 // c->B::member
2553 //
2554 // or
2555 //
2556 // c->A::member
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002557
Douglas Gregor546be3c2009-12-30 17:04:44 +00002558 // Find results in this base class (and its bases).
2559 ShadowContextRAII Shadow(Visited);
2560 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002561 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002562 }
2563 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002564
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002565 // Traverse the contexts of Objective-C classes.
2566 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2567 // Traverse categories.
2568 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2569 Category; Category = Category->getNextClassCategory()) {
2570 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002571 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002572 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002573 }
2574
2575 // Traverse protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00002576 for (ObjCInterfaceDecl::all_protocol_iterator
2577 I = IFace->all_referenced_protocol_begin(),
2578 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002579 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002580 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002581 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002582 }
2583
2584 // Traverse the superclass.
2585 if (IFace->getSuperClass()) {
2586 ShadowContextRAII Shadow(Visited);
2587 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002588 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002589 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002590
Douglas Gregorc220a182010-04-19 18:02:19 +00002591 // If there is an implementation, traverse it. We do this to find
2592 // synthesized ivars.
2593 if (IFace->getImplementation()) {
2594 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002595 LookupVisibleDecls(IFace->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00002596 QualifiedNameLookup, true, Consumer, Visited);
2597 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002598 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2599 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2600 E = Protocol->protocol_end(); I != E; ++I) {
2601 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002602 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002603 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002604 }
2605 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2606 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2607 E = Category->protocol_end(); I != E; ++I) {
2608 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002609 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002610 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002611 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002612
Douglas Gregorc220a182010-04-19 18:02:19 +00002613 // If there is an implementation, traverse it.
2614 if (Category->getImplementation()) {
2615 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002616 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00002617 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002618 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002619 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002620}
2621
2622static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2623 UnqualUsingDirectiveSet &UDirs,
2624 VisibleDeclConsumer &Consumer,
2625 VisibleDeclsRecord &Visited) {
2626 if (!S)
2627 return;
2628
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002629 if (!S->getEntity() ||
2630 (!S->getParent() &&
Douglas Gregor8071e422010-08-15 06:18:01 +00002631 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor539c5c32010-01-07 00:31:29 +00002632 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2633 // Walk through the declarations in this Scope.
2634 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2635 D != DEnd; ++D) {
John McCalld226f652010-08-21 09:40:31 +00002636 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor539c5c32010-01-07 00:31:29 +00002637 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002638 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002639 Visited.add(ND);
2640 }
2641 }
2642 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002643
Douglas Gregor711be1e2010-03-15 14:33:29 +00002644 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00002645 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00002646 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002647 // Look into this scope's declaration context, along with any of its
2648 // parent lookup contexts (e.g., enclosing classes), up to the point
2649 // where we hit the context stored in the next outer scope.
2650 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00002651 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002652
Douglas Gregordbdf5e72010-03-15 15:26:48 +00002653 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002654 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002655 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2656 if (Method->isInstanceMethod()) {
2657 // For instance methods, look for ivars in the method's interface.
2658 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2659 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregorca45da02010-11-02 20:36:02 +00002660 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002661 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Douglas Gregor62021192010-02-04 23:42:48 +00002662 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002663
Douglas Gregorca45da02010-11-02 20:36:02 +00002664 // Look for properties from which we can synthesize ivars, if
2665 // permitted.
2666 if (Result.getSema().getLangOptions().ObjCNonFragileABI2 &&
2667 IFace->getImplementation() &&
2668 Result.getLookupKind() == Sema::LookupOrdinaryName) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002669 for (ObjCInterfaceDecl::prop_iterator
Douglas Gregorca45da02010-11-02 20:36:02 +00002670 P = IFace->prop_begin(),
2671 PEnd = IFace->prop_end();
2672 P != PEnd; ++P) {
2673 if (Result.getSema().canSynthesizeProvisionalIvar(*P) &&
2674 !IFace->lookupInstanceVariable((*P)->getIdentifier())) {
2675 Consumer.FoundDecl(*P, Visited.checkHidden(*P), false);
2676 Visited.add(*P);
2677 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002678 }
2679 }
Douglas Gregorca45da02010-11-02 20:36:02 +00002680 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002681 }
2682
2683 // We've already performed all of the name lookup that we need
2684 // to for Objective-C methods; the next context will be the
2685 // outer scope.
2686 break;
2687 }
2688
Douglas Gregor546be3c2009-12-30 17:04:44 +00002689 if (Ctx->isFunctionOrMethod())
2690 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002691
2692 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002693 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002694 }
2695 } else if (!S->getParent()) {
2696 // Look into the translation unit scope. We walk through the translation
2697 // unit's declaration context, because the Scope itself won't have all of
2698 // the declarations if we loaded a precompiled header.
2699 // FIXME: We would like the translation unit's Scope object to point to the
2700 // translation unit, so we don't need this special "if" branch. However,
2701 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002702 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002703 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00002704 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002705 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002706 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002707 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002708 }
2709
Douglas Gregor546be3c2009-12-30 17:04:44 +00002710 if (Entity) {
2711 // Lookup visible declarations in any namespaces found by using
2712 // directives.
2713 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2714 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2715 for (; UI != UEnd; ++UI)
2716 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002717 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002718 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002719 }
2720
2721 // Lookup names in the parent scope.
2722 ShadowContextRAII Shadow(Visited);
2723 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2724}
2725
2726void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00002727 VisibleDeclConsumer &Consumer,
2728 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002729 // Determine the set of using directives available during
2730 // unqualified name lookup.
2731 Scope *Initial = S;
2732 UnqualUsingDirectiveSet UDirs;
2733 if (getLangOptions().CPlusPlus) {
2734 // Find the first namespace or translation-unit scope.
2735 while (S && !isNamespaceOrTranslationUnitScope(S))
2736 S = S->getParent();
2737
2738 UDirs.visitScopeChain(Initial, S);
2739 }
2740 UDirs.done();
2741
2742 // Look for visible declarations.
2743 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2744 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00002745 if (!IncludeGlobalScope)
2746 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00002747 ShadowContextRAII Shadow(Visited);
2748 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2749}
2750
2751void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00002752 VisibleDeclConsumer &Consumer,
2753 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002754 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2755 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00002756 if (!IncludeGlobalScope)
2757 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00002758 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002759 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002760 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002761}
2762
Chris Lattner4ae493c2011-02-18 02:08:43 +00002763/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
2764/// If isLocalLabel is true, then this is a definition of an __label__ label
2765/// name, otherwise it is a normal label definition or use.
2766LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
2767 bool isLocalLabel) {
Chris Lattner337e5502011-02-18 01:27:55 +00002768 // Do a lookup to see if we have a label with this name already.
Chris Lattner4ae493c2011-02-18 02:08:43 +00002769 NamedDecl *Res = 0;
2770
2771 // Local label definitions always shadow existing labels.
2772 if (!isLocalLabel)
2773 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
2774
Chris Lattner337e5502011-02-18 01:27:55 +00002775 // If we found a label, check to see if it is in the same context as us. When
2776 // in a Block, we don't want to reuse a label in an enclosing function.
2777 if (Res && Res->getDeclContext() != CurContext)
2778 Res = 0;
2779
2780 if (Res == 0) {
2781 // If not forward referenced or defined already, create the backing decl.
2782 Res = LabelDecl::Create(Context, CurContext, Loc, II);
Chris Lattnerfebb5b82011-02-18 21:16:39 +00002783 Scope *S = isLocalLabel ? CurScope : CurScope->getFnParent();
2784 assert(S && "Not in a function?");
2785 PushOnScopeChains(Res, S, true);
Chris Lattner337e5502011-02-18 01:27:55 +00002786 }
2787
2788 return cast<LabelDecl>(Res);
2789}
2790
2791//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00002792// Typo correction
Chris Lattner337e5502011-02-18 01:27:55 +00002793//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00002794
2795namespace {
2796class TypoCorrectionConsumer : public VisibleDeclConsumer {
2797 /// \brief The name written that is a typo in the source.
2798 llvm::StringRef Typo;
2799
2800 /// \brief The results found that have the smallest edit distance
2801 /// found (so far) with the typo name.
Douglas Gregore24b5752010-10-14 20:34:08 +00002802 ///
2803 /// The boolean value indicates whether there is a keyword with this name.
2804 llvm::StringMap<bool, llvm::BumpPtrAllocator> BestResults;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002805
2806 /// \brief The best edit distance found so far.
2807 unsigned BestEditDistance;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002808
Douglas Gregor546be3c2009-12-30 17:04:44 +00002809public:
2810 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002811 : Typo(Typo->getName()),
Douglas Gregore24b5752010-10-14 20:34:08 +00002812 BestEditDistance((std::numeric_limits<unsigned>::max)()) { }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002813
Douglas Gregor0cc84042010-01-14 15:47:35 +00002814 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregor95f42922010-10-14 22:11:03 +00002815 void FoundName(llvm::StringRef Name);
Douglas Gregoraaf87162010-04-14 20:04:41 +00002816 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002817
Douglas Gregore24b5752010-10-14 20:34:08 +00002818 typedef llvm::StringMap<bool, llvm::BumpPtrAllocator>::iterator iterator;
2819 iterator begin() { return BestResults.begin(); }
2820 iterator end() { return BestResults.end(); }
2821 void erase(iterator I) { BestResults.erase(I); }
2822 unsigned size() const { return BestResults.size(); }
2823 bool empty() const { return BestResults.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002824
Douglas Gregor7b824e82010-10-15 13:35:25 +00002825 bool &operator[](llvm::StringRef Name) {
2826 return BestResults[Name];
2827 }
2828
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002829 unsigned getBestEditDistance() const { return BestEditDistance; }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002830};
2831
2832}
2833
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002834void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002835 bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002836 // Don't consider hidden names for typo correction.
2837 if (Hiding)
2838 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002839
Douglas Gregor546be3c2009-12-30 17:04:44 +00002840 // Only consider entities with identifiers for names, ignoring
2841 // special names (constructors, overloaded operators, selectors,
2842 // etc.).
2843 IdentifierInfo *Name = ND->getIdentifier();
2844 if (!Name)
2845 return;
2846
Douglas Gregor95f42922010-10-14 22:11:03 +00002847 FoundName(Name->getName());
2848}
2849
2850void TypoCorrectionConsumer::FoundName(llvm::StringRef Name) {
Douglas Gregora1194772010-10-19 22:14:33 +00002851 using namespace std;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002852
Douglas Gregor362a8f22010-10-19 19:39:10 +00002853 // Use a simple length-based heuristic to determine the minimum possible
2854 // edit distance. If the minimum isn't good enough, bail out early.
2855 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
2856 if (MinED > BestEditDistance || (MinED && Typo.size() / MinED < 3))
2857 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002858
Douglas Gregora1194772010-10-19 22:14:33 +00002859 // Compute an upper bound on the allowable edit distance, so that the
2860 // edit-distance algorithm can short-circuit.
2861 unsigned UpperBound = min(unsigned((Typo.size() + 2) / 3), BestEditDistance);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002862
Douglas Gregor546be3c2009-12-30 17:04:44 +00002863 // Compute the edit distance between the typo and the name of this
2864 // entity. If this edit distance is not worse than the best edit
2865 // distance we've seen so far, add it to the list of results.
Douglas Gregora1194772010-10-19 22:14:33 +00002866 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
Douglas Gregor95f42922010-10-14 22:11:03 +00002867 if (ED == 0)
2868 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002869
Douglas Gregore24b5752010-10-14 20:34:08 +00002870 if (ED < BestEditDistance) {
2871 // This result is better than any we've seen before; clear out
2872 // the previous results.
2873 BestResults.clear();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002874 BestEditDistance = ED;
Douglas Gregore24b5752010-10-14 20:34:08 +00002875 } else if (ED > BestEditDistance) {
2876 // This result is worse than the best results we've seen so far;
2877 // ignore it.
2878 return;
2879 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002880
Douglas Gregore24b5752010-10-14 20:34:08 +00002881 // Add this name to the list of results. By not assigning a value, we
2882 // keep the current value if we've seen this name before (either as a
2883 // keyword or as a declaration), or get the default value (not a keyword)
2884 // if we haven't seen it before.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002885 (void)BestResults[Name];
Douglas Gregor546be3c2009-12-30 17:04:44 +00002886}
2887
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002888void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
Douglas Gregoraaf87162010-04-14 20:04:41 +00002889 llvm::StringRef Keyword) {
2890 // Compute the edit distance between the typo and this keyword.
2891 // If this edit distance is not worse than the best edit
2892 // distance we've seen so far, add it to the list of results.
2893 unsigned ED = Typo.edit_distance(Keyword);
Douglas Gregore24b5752010-10-14 20:34:08 +00002894 if (ED < BestEditDistance) {
2895 BestResults.clear();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002896 BestEditDistance = ED;
Douglas Gregore24b5752010-10-14 20:34:08 +00002897 } else if (ED > BestEditDistance) {
2898 // This result is worse than the best results we've seen so far;
2899 // ignore it.
2900 return;
2901 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002902
Douglas Gregore24b5752010-10-14 20:34:08 +00002903 BestResults[Keyword] = true;
Douglas Gregoraaf87162010-04-14 20:04:41 +00002904}
2905
Douglas Gregor9a632ea2010-10-20 03:06:34 +00002906/// \brief Perform name lookup for a possible result for typo correction.
2907static void LookupPotentialTypoResult(Sema &SemaRef,
2908 LookupResult &Res,
2909 IdentifierInfo *Name,
2910 Scope *S, CXXScopeSpec *SS,
2911 DeclContext *MemberContext,
2912 bool EnteringContext,
2913 Sema::CorrectTypoContext CTC) {
2914 Res.suppressDiagnostics();
2915 Res.clear();
2916 Res.setLookupName(Name);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002917 if (MemberContext) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00002918 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
2919 if (CTC == Sema::CTC_ObjCIvarLookup) {
2920 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
2921 Res.addDecl(Ivar);
2922 Res.resolveKind();
2923 return;
2924 }
2925 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002926
Douglas Gregor9a632ea2010-10-20 03:06:34 +00002927 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
2928 Res.addDecl(Prop);
2929 Res.resolveKind();
2930 return;
2931 }
2932 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002933
Douglas Gregor9a632ea2010-10-20 03:06:34 +00002934 SemaRef.LookupQualifiedName(Res, MemberContext);
2935 return;
2936 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002937
2938 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00002939 EnteringContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002940
Douglas Gregor9a632ea2010-10-20 03:06:34 +00002941 // Fake ivar lookup; this should really be part of
2942 // LookupParsedName.
2943 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2944 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002945 (Res.empty() ||
Douglas Gregor9a632ea2010-10-20 03:06:34 +00002946 (Res.isSingleResult() &&
2947 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002948 if (ObjCIvarDecl *IV
Douglas Gregor9a632ea2010-10-20 03:06:34 +00002949 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
2950 Res.addDecl(IV);
2951 Res.resolveKind();
2952 }
2953 }
2954 }
2955}
2956
Douglas Gregor546be3c2009-12-30 17:04:44 +00002957/// \brief Try to "correct" a typo in the source code by finding
2958/// visible declarations whose names are similar to the name that was
2959/// present in the source code.
2960///
2961/// \param Res the \c LookupResult structure that contains the name
2962/// that was present in the source code along with the name-lookup
2963/// criteria used to search for the name. On success, this structure
2964/// will contain the results of name lookup.
2965///
2966/// \param S the scope in which name lookup occurs.
2967///
2968/// \param SS the nested-name-specifier that precedes the name we're
2969/// looking for, if present.
2970///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002971/// \param MemberContext if non-NULL, the context in which to look for
2972/// a member access expression.
2973///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002974/// \param EnteringContext whether we're entering the context described by
Douglas Gregorbb092ba2009-12-31 05:20:13 +00002975/// the nested-name-specifier SS.
2976///
Douglas Gregoraaf87162010-04-14 20:04:41 +00002977/// \param CTC The context in which typo correction occurs, which impacts the
2978/// set of keywords permitted.
2979///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002980/// \param OPT when non-NULL, the search for visible declarations will
2981/// also walk the protocols in the qualified interfaces of \p OPT.
2982///
Douglas Gregor931f98a2010-04-14 17:09:22 +00002983/// \returns the corrected name if the typo was corrected, otherwise returns an
2984/// empty \c DeclarationName. When a typo was corrected, the result structure
2985/// may contain the results of name lookup for the correct name or it may be
2986/// empty.
2987DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002988 DeclContext *MemberContext,
Douglas Gregoraaf87162010-04-14 20:04:41 +00002989 bool EnteringContext,
2990 CorrectTypoContext CTC,
2991 const ObjCObjectPointerType *OPT) {
Douglas Gregora0068fc2010-07-09 17:35:33 +00002992 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002993 return DeclarationName();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002994
Douglas Gregor546be3c2009-12-30 17:04:44 +00002995 // We only attempt to correct typos for identifiers.
2996 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2997 if (!Typo)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002998 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002999
3000 // If the scope specifier itself was invalid, don't try to correct
3001 // typos.
3002 if (SS && SS->isInvalid())
Douglas Gregor931f98a2010-04-14 17:09:22 +00003003 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003004
3005 // Never try to correct typos during template deduction or
3006 // instantiation.
3007 if (!ActiveTemplateInstantiations.empty())
Douglas Gregor931f98a2010-04-14 17:09:22 +00003008 return DeclarationName();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003009
Douglas Gregor546be3c2009-12-30 17:04:44 +00003010 TypoCorrectionConsumer Consumer(Typo);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003011
Douglas Gregoraaf87162010-04-14 20:04:41 +00003012 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003013 bool IsUnqualifiedLookup = false;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003014 if (MemberContext) {
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003015 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003016
3017 // Look in qualified interfaces.
3018 if (OPT) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003019 for (ObjCObjectPointerType::qual_iterator
3020 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003021 I != E; ++I)
3022 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
3023 }
3024 } else if (SS && SS->isSet()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003025 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
3026 if (!DC)
Douglas Gregor931f98a2010-04-14 17:09:22 +00003027 return DeclarationName();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003028
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003029 // Provide a stop gap for files that are just seriously broken. Trying
3030 // to correct all typos can turn into a HUGE performance penalty, causing
3031 // some files to take minutes to get rejected by the parser.
3032 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
3033 return DeclarationName();
3034 ++TyposCorrected;
3035
Douglas Gregor546be3c2009-12-30 17:04:44 +00003036 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
3037 } else {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003038 IsUnqualifiedLookup = true;
3039 UnqualifiedTyposCorrectedMap::iterator Cached
3040 = UnqualifiedTyposCorrected.find(Typo);
3041 if (Cached == UnqualifiedTyposCorrected.end()) {
3042 // Provide a stop gap for files that are just seriously broken. Trying
3043 // to correct all typos can turn into a HUGE performance penalty, causing
3044 // some files to take minutes to get rejected by the parser.
3045 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
3046 return DeclarationName();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003047
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003048 // For unqualified lookup, look through all of the names that we have
3049 // seen in this translation unit.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003050 for (IdentifierTable::iterator I = Context.Idents.begin(),
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003051 IEnd = Context.Idents.end();
3052 I != IEnd; ++I)
3053 Consumer.FoundName(I->getKey());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003054
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003055 // Walk through identifiers in external identifier sources.
3056 if (IdentifierInfoLookup *External
Douglas Gregor95f42922010-10-14 22:11:03 +00003057 = Context.Idents.getExternalIdentifierLookup()) {
Ted Kremenek7a054b12010-11-07 06:11:33 +00003058 llvm::OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003059 do {
3060 llvm::StringRef Name = Iter->Next();
3061 if (Name.empty())
3062 break;
Douglas Gregor95f42922010-10-14 22:11:03 +00003063
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003064 Consumer.FoundName(Name);
3065 } while (true);
3066 }
3067 } else {
3068 // Use the cached value, unless it's a keyword. In the keyword case, we'll
3069 // end up adding the keyword below.
3070 if (Cached->second.first.empty())
3071 return DeclarationName();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003072
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003073 if (!Cached->second.second)
3074 Consumer.FoundName(Cached->second.first);
Douglas Gregor95f42922010-10-14 22:11:03 +00003075 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003076 }
3077
Douglas Gregoraaf87162010-04-14 20:04:41 +00003078 // Add context-dependent keywords.
3079 bool WantTypeSpecifiers = false;
3080 bool WantExpressionKeywords = false;
3081 bool WantCXXNamedCasts = false;
3082 bool WantRemainingKeywords = false;
3083 switch (CTC) {
3084 case CTC_Unknown:
3085 WantTypeSpecifiers = true;
3086 WantExpressionKeywords = true;
3087 WantCXXNamedCasts = true;
3088 WantRemainingKeywords = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003089
Douglas Gregor91f7ac72010-05-18 16:14:23 +00003090 if (ObjCMethodDecl *Method = getCurMethodDecl())
3091 if (Method->getClassInterface() &&
3092 Method->getClassInterface()->getSuperClass())
3093 Consumer.addKeywordResult(Context, "super");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003094
Douglas Gregoraaf87162010-04-14 20:04:41 +00003095 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003096
Douglas Gregoraaf87162010-04-14 20:04:41 +00003097 case CTC_NoKeywords:
3098 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003099
Douglas Gregoraaf87162010-04-14 20:04:41 +00003100 case CTC_Type:
3101 WantTypeSpecifiers = true;
3102 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003103
Douglas Gregoraaf87162010-04-14 20:04:41 +00003104 case CTC_ObjCMessageReceiver:
3105 Consumer.addKeywordResult(Context, "super");
3106 // Fall through to handle message receivers like expressions.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003107
Douglas Gregoraaf87162010-04-14 20:04:41 +00003108 case CTC_Expression:
3109 if (getLangOptions().CPlusPlus)
3110 WantTypeSpecifiers = true;
3111 WantExpressionKeywords = true;
3112 // Fall through to get C++ named casts.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003113
Douglas Gregoraaf87162010-04-14 20:04:41 +00003114 case CTC_CXXCasts:
3115 WantCXXNamedCasts = true;
3116 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003117
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003118 case CTC_ObjCPropertyLookup:
3119 // FIXME: Add "isa"?
3120 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003121
Douglas Gregoraaf87162010-04-14 20:04:41 +00003122 case CTC_MemberLookup:
3123 if (getLangOptions().CPlusPlus)
3124 Consumer.addKeywordResult(Context, "template");
3125 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003126
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003127 case CTC_ObjCIvarLookup:
3128 break;
Douglas Gregoraaf87162010-04-14 20:04:41 +00003129 }
3130
3131 if (WantTypeSpecifiers) {
3132 // Add type-specifier keywords to the set of results.
3133 const char *CTypeSpecs[] = {
3134 "char", "const", "double", "enum", "float", "int", "long", "short",
3135 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
3136 "_Complex", "_Imaginary",
3137 // storage-specifiers as well
3138 "extern", "inline", "static", "typedef"
3139 };
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003140
Douglas Gregoraaf87162010-04-14 20:04:41 +00003141 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3142 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3143 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003144
Douglas Gregoraaf87162010-04-14 20:04:41 +00003145 if (getLangOptions().C99)
3146 Consumer.addKeywordResult(Context, "restrict");
3147 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
3148 Consumer.addKeywordResult(Context, "bool");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003149
Douglas Gregoraaf87162010-04-14 20:04:41 +00003150 if (getLangOptions().CPlusPlus) {
3151 Consumer.addKeywordResult(Context, "class");
3152 Consumer.addKeywordResult(Context, "typename");
3153 Consumer.addKeywordResult(Context, "wchar_t");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003154
Douglas Gregoraaf87162010-04-14 20:04:41 +00003155 if (getLangOptions().CPlusPlus0x) {
3156 Consumer.addKeywordResult(Context, "char16_t");
3157 Consumer.addKeywordResult(Context, "char32_t");
3158 Consumer.addKeywordResult(Context, "constexpr");
3159 Consumer.addKeywordResult(Context, "decltype");
3160 Consumer.addKeywordResult(Context, "thread_local");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003161 }
Douglas Gregoraaf87162010-04-14 20:04:41 +00003162 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003163
Douglas Gregoraaf87162010-04-14 20:04:41 +00003164 if (getLangOptions().GNUMode)
3165 Consumer.addKeywordResult(Context, "typeof");
3166 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003167
Douglas Gregord0785ea2010-05-18 16:30:22 +00003168 if (WantCXXNamedCasts && getLangOptions().CPlusPlus) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00003169 Consumer.addKeywordResult(Context, "const_cast");
3170 Consumer.addKeywordResult(Context, "dynamic_cast");
3171 Consumer.addKeywordResult(Context, "reinterpret_cast");
3172 Consumer.addKeywordResult(Context, "static_cast");
3173 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003174
Douglas Gregoraaf87162010-04-14 20:04:41 +00003175 if (WantExpressionKeywords) {
3176 Consumer.addKeywordResult(Context, "sizeof");
3177 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
3178 Consumer.addKeywordResult(Context, "false");
3179 Consumer.addKeywordResult(Context, "true");
3180 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003181
Douglas Gregoraaf87162010-04-14 20:04:41 +00003182 if (getLangOptions().CPlusPlus) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003183 const char *CXXExprs[] = {
3184 "delete", "new", "operator", "throw", "typeid"
Douglas Gregoraaf87162010-04-14 20:04:41 +00003185 };
3186 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3187 for (unsigned I = 0; I != NumCXXExprs; ++I)
3188 Consumer.addKeywordResult(Context, CXXExprs[I]);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003189
Douglas Gregoraaf87162010-04-14 20:04:41 +00003190 if (isa<CXXMethodDecl>(CurContext) &&
3191 cast<CXXMethodDecl>(CurContext)->isInstance())
3192 Consumer.addKeywordResult(Context, "this");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003193
Douglas Gregoraaf87162010-04-14 20:04:41 +00003194 if (getLangOptions().CPlusPlus0x) {
3195 Consumer.addKeywordResult(Context, "alignof");
3196 Consumer.addKeywordResult(Context, "nullptr");
3197 }
3198 }
3199 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003200
Douglas Gregoraaf87162010-04-14 20:04:41 +00003201 if (WantRemainingKeywords) {
3202 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
3203 // Statements.
3204 const char *CStmts[] = {
3205 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3206 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3207 for (unsigned I = 0; I != NumCStmts; ++I)
3208 Consumer.addKeywordResult(Context, CStmts[I]);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003209
Douglas Gregoraaf87162010-04-14 20:04:41 +00003210 if (getLangOptions().CPlusPlus) {
3211 Consumer.addKeywordResult(Context, "catch");
3212 Consumer.addKeywordResult(Context, "try");
3213 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003214
Douglas Gregoraaf87162010-04-14 20:04:41 +00003215 if (S && S->getBreakParent())
3216 Consumer.addKeywordResult(Context, "break");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003217
Douglas Gregoraaf87162010-04-14 20:04:41 +00003218 if (S && S->getContinueParent())
3219 Consumer.addKeywordResult(Context, "continue");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003220
John McCall781472f2010-08-25 08:40:02 +00003221 if (!getCurFunction()->SwitchStack.empty()) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00003222 Consumer.addKeywordResult(Context, "case");
3223 Consumer.addKeywordResult(Context, "default");
3224 }
3225 } else {
3226 if (getLangOptions().CPlusPlus) {
3227 Consumer.addKeywordResult(Context, "namespace");
3228 Consumer.addKeywordResult(Context, "template");
3229 }
3230
3231 if (S && S->isClassScope()) {
3232 Consumer.addKeywordResult(Context, "explicit");
3233 Consumer.addKeywordResult(Context, "friend");
3234 Consumer.addKeywordResult(Context, "mutable");
3235 Consumer.addKeywordResult(Context, "private");
3236 Consumer.addKeywordResult(Context, "protected");
3237 Consumer.addKeywordResult(Context, "public");
3238 Consumer.addKeywordResult(Context, "virtual");
3239 }
3240 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003241
Douglas Gregoraaf87162010-04-14 20:04:41 +00003242 if (getLangOptions().CPlusPlus) {
3243 Consumer.addKeywordResult(Context, "using");
3244
3245 if (getLangOptions().CPlusPlus0x)
3246 Consumer.addKeywordResult(Context, "static_assert");
3247 }
3248 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003249
Douglas Gregoraaf87162010-04-14 20:04:41 +00003250 // If we haven't found anything, we're done.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003251 if (Consumer.empty()) {
3252 // If this was an unqualified lookup, note that no correction was found.
3253 if (IsUnqualifiedLookup)
3254 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003255
Douglas Gregor931f98a2010-04-14 17:09:22 +00003256 return DeclarationName();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003257 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003258
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003259 // Make sure that the user typed at least 3 characters for each correction
Douglas Gregore24b5752010-10-14 20:34:08 +00003260 // made. Otherwise, we don't even both looking at the results.
Douglas Gregor53e4b552010-10-26 17:18:00 +00003261
3262 // We also suppress exact matches; those should be handled by a
3263 // different mechanism (e.g., one that introduces qualification in
3264 // C++).
Douglas Gregore24b5752010-10-14 20:34:08 +00003265 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003266 if (ED > 0 && Typo->getName().size() / ED < 3) {
3267 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregor157a3ff2010-10-27 14:20:34 +00003268 if (IsUnqualifiedLookup)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003269 (void)UnqualifiedTyposCorrected[Typo];
3270
Douglas Gregore24b5752010-10-14 20:34:08 +00003271 return DeclarationName();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003272 }
Douglas Gregore24b5752010-10-14 20:34:08 +00003273
3274 // Weed out any names that could not be found by name lookup.
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003275 bool LastLookupWasAccepted = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003276 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
Douglas Gregoraaf87162010-04-14 20:04:41 +00003277 IEnd = Consumer.end();
Douglas Gregore24b5752010-10-14 20:34:08 +00003278 I != IEnd; /* Increment in loop. */) {
3279 // Keywords are always found.
3280 if (I->second) {
3281 ++I;
3282 continue;
Douglas Gregoraaf87162010-04-14 20:04:41 +00003283 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003284
Douglas Gregore24b5752010-10-14 20:34:08 +00003285 // Perform name lookup on this name.
3286 IdentifierInfo *Name = &Context.Idents.get(I->getKey());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003287 LookupPotentialTypoResult(*this, Res, Name, S, SS, MemberContext,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003288 EnteringContext, CTC);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003289
Douglas Gregore24b5752010-10-14 20:34:08 +00003290 switch (Res.getResultKind()) {
3291 case LookupResult::NotFound:
3292 case LookupResult::NotFoundInCurrentInstantiation:
3293 case LookupResult::Ambiguous:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003294 // We didn't find this name in our scope, or didn't like what we found;
Douglas Gregore24b5752010-10-14 20:34:08 +00003295 // ignore it.
3296 Res.suppressDiagnostics();
3297 {
3298 TypoCorrectionConsumer::iterator Next = I;
3299 ++Next;
3300 Consumer.erase(I);
3301 I = Next;
3302 }
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003303 LastLookupWasAccepted = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003304 break;
3305
Douglas Gregore24b5752010-10-14 20:34:08 +00003306 case LookupResult::Found:
3307 case LookupResult::FoundOverloaded:
3308 case LookupResult::FoundUnresolvedValue:
3309 ++I;
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003310 LastLookupWasAccepted = true;
Douglas Gregoraaf87162010-04-14 20:04:41 +00003311 break;
Douglas Gregore24b5752010-10-14 20:34:08 +00003312 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003313
Douglas Gregore24b5752010-10-14 20:34:08 +00003314 if (Res.isAmbiguous()) {
3315 // We don't deal with ambiguities.
3316 Res.suppressDiagnostics();
3317 Res.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003318 return DeclarationName();
3319 }
Douglas Gregoraaf87162010-04-14 20:04:41 +00003320 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003321
Douglas Gregore24b5752010-10-14 20:34:08 +00003322 // If only a single name remains, return that result.
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003323 if (Consumer.size() == 1) {
3324 IdentifierInfo *Name = &Context.Idents.get(Consumer.begin()->getKey());
Douglas Gregorf98402d2010-10-20 01:01:57 +00003325 if (Consumer.begin()->second) {
3326 Res.suppressDiagnostics();
3327 Res.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003328
Douglas Gregor53e4b552010-10-26 17:18:00 +00003329 // Don't correct to a keyword that's the same as the typo; the keyword
3330 // wasn't actually in scope.
3331 if (ED == 0) {
3332 Res.setLookupName(Typo);
3333 return DeclarationName();
3334 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003335
Douglas Gregorf98402d2010-10-20 01:01:57 +00003336 } else if (!LastLookupWasAccepted) {
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003337 // Perform name lookup on this name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003338 LookupPotentialTypoResult(*this, Res, Name, S, SS, MemberContext,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003339 EnteringContext, CTC);
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003340 }
3341
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003342 // Record the correction for unqualified lookup.
3343 if (IsUnqualifiedLookup)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003344 UnqualifiedTyposCorrected[Typo]
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003345 = std::make_pair(Name->getName(), Consumer.begin()->second);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003346
3347 return &Context.Idents.get(Consumer.begin()->getKey());
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003348 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003349 else if (Consumer.size() > 1 && CTC == CTC_ObjCMessageReceiver
Douglas Gregor7b824e82010-10-15 13:35:25 +00003350 && Consumer["super"]) {
3351 // Prefix 'super' when we're completing in a message-receiver
3352 // context.
3353 Res.suppressDiagnostics();
3354 Res.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003355
Douglas Gregor53e4b552010-10-26 17:18:00 +00003356 // Don't correct to a keyword that's the same as the typo; the keyword
3357 // wasn't actually in scope.
3358 if (ED == 0) {
3359 Res.setLookupName(Typo);
3360 return DeclarationName();
3361 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003362
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003363 // Record the correction for unqualified lookup.
3364 if (IsUnqualifiedLookup)
3365 UnqualifiedTyposCorrected[Typo]
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003366 = std::make_pair("super", Consumer.begin()->second);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003367
Douglas Gregor7b824e82010-10-15 13:35:25 +00003368 return &Context.Idents.get("super");
3369 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003370
Douglas Gregore24b5752010-10-14 20:34:08 +00003371 Res.suppressDiagnostics();
3372 Res.setLookupName(Typo);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003373 Res.clear();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003374 // Record the correction for unqualified lookup.
3375 if (IsUnqualifiedLookup)
3376 (void)UnqualifiedTyposCorrected[Typo];
3377
Douglas Gregor931f98a2010-04-14 17:09:22 +00003378 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003379}