blob: ec633d177c44f960fcbdfc1fdc190f34c417b833 [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;
John McCall1d7c5282009-12-18 10:40:03 +0000213 if (Redeclaration) IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
214 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000215 break;
216
John McCall76d32642010-04-24 01:30:58 +0000217 case Sema::LookupOperatorName:
218 // Operator lookup is its own crazy thing; it is not the same
219 // as (e.g.) looking up an operator name for redeclaration.
220 assert(!Redeclaration && "cannot do redeclaration operator lookup");
221 IDNS = Decl::IDNS_NonMemberOperator;
222 break;
223
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000224 case Sema::LookupTagName:
John McCall0d6b1642010-04-23 18:46:30 +0000225 if (CPlusPlus) {
226 IDNS = Decl::IDNS_Type;
227
228 // When looking for a redeclaration of a tag name, we add:
229 // 1) TagFriend to find undeclared friend decls
230 // 2) Namespace because they can't "overload" with tag decls.
231 // 3) Tag because it includes class templates, which can't
232 // "overload" with tag decls.
233 if (Redeclaration)
234 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
235 } else {
236 IDNS = Decl::IDNS_Tag;
237 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000238 break;
239
240 case Sema::LookupMemberName:
241 IDNS = Decl::IDNS_Member;
242 if (CPlusPlus)
Mike Stump1eb44332009-09-09 15:08:12 +0000243 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000244 break;
245
246 case Sema::LookupNestedNameSpecifierName:
John McCall0d6b1642010-04-23 18:46:30 +0000247 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
248 break;
249
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000250 case Sema::LookupNamespaceName:
John McCall0d6b1642010-04-23 18:46:30 +0000251 IDNS = Decl::IDNS_Namespace;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000252 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000253
John McCall9f54ad42009-12-10 09:41:52 +0000254 case Sema::LookupUsingDeclName:
255 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
256 | Decl::IDNS_Member | Decl::IDNS_Using;
257 break;
258
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000259 case Sema::LookupObjCProtocolName:
260 IDNS = Decl::IDNS_ObjCProtocol;
261 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000262
Douglas Gregor8071e422010-08-15 06:18:01 +0000263 case Sema::LookupAnyName:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000264 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor8071e422010-08-15 06:18:01 +0000265 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
266 | Decl::IDNS_Type;
267 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000268 }
269 return IDNS;
270}
271
John McCall1d7c5282009-12-18 10:40:03 +0000272void LookupResult::configure() {
273 IDNS = getIDNS(LookupKind,
274 SemaRef.getLangOptions().CPlusPlus,
275 isForRedeclaration());
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000276
277 // If we're looking for one of the allocation or deallocation
278 // operators, make sure that the implicitly-declared new and delete
279 // operators can be found.
280 if (!isForRedeclaration()) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000281 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000282 case OO_New:
283 case OO_Delete:
284 case OO_Array_New:
285 case OO_Array_Delete:
286 SemaRef.DeclareGlobalNewDelete();
287 break;
288
289 default:
290 break;
291 }
292 }
John McCall1d7c5282009-12-18 10:40:03 +0000293}
294
John McCall2a7fb272010-08-25 05:32:35 +0000295void LookupResult::sanity() const {
296 assert(ResultKind != NotFound || Decls.size() == 0);
297 assert(ResultKind != Found || Decls.size() == 1);
298 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
299 (Decls.size() == 1 &&
300 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
301 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
302 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorf17b58c2010-10-22 22:08:47 +0000303 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
304 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall2a7fb272010-08-25 05:32:35 +0000305 assert((Paths != NULL) == (ResultKind == Ambiguous &&
306 (Ambiguity == AmbiguousBaseSubobjectTypes ||
307 Ambiguity == AmbiguousBaseSubobjects)));
308}
John McCall2a7fb272010-08-25 05:32:35 +0000309
John McCallf36e02d2009-10-09 21:13:30 +0000310// Necessary because CXXBasePaths is not complete in Sema.h
John McCall7d384dd2009-11-18 07:57:50 +0000311void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCallf36e02d2009-10-09 21:13:30 +0000312 delete Paths;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000313}
314
John McCall7453ed42009-11-22 00:44:51 +0000315/// Resolves the result kind of this lookup.
John McCall7d384dd2009-11-18 07:57:50 +0000316void LookupResult::resolveKind() {
John McCallf36e02d2009-10-09 21:13:30 +0000317 unsigned N = Decls.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000318
John McCallf36e02d2009-10-09 21:13:30 +0000319 // Fast case: no possible ambiguity.
John McCall68263142009-11-18 22:49:29 +0000320 if (N == 0) {
John McCalldc5c7862010-01-15 21:27:01 +0000321 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall68263142009-11-18 22:49:29 +0000322 return;
323 }
324
John McCall7453ed42009-11-22 00:44:51 +0000325 // If there's a single decl, we need to examine it to decide what
326 // kind of lookup this is.
John McCall7ba107a2009-11-18 02:36:19 +0000327 if (N == 1) {
Douglas Gregor2b147f02010-04-25 21:15:30 +0000328 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
329 if (isa<FunctionTemplateDecl>(D))
John McCall7453ed42009-11-22 00:44:51 +0000330 ResultKind = FoundOverloaded;
Douglas Gregor2b147f02010-04-25 21:15:30 +0000331 else if (isa<UnresolvedUsingValueDecl>(D))
John McCall7ba107a2009-11-18 02:36:19 +0000332 ResultKind = FoundUnresolvedValue;
333 return;
334 }
John McCallf36e02d2009-10-09 21:13:30 +0000335
John McCall6e247262009-10-10 05:48:19 +0000336 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000337 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000338
John McCallf36e02d2009-10-09 21:13:30 +0000339 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000340 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000341
John McCallf36e02d2009-10-09 21:13:30 +0000342 bool Ambiguous = false;
343 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000344 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000345
346 unsigned UniqueTagIndex = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000347
John McCallf36e02d2009-10-09 21:13:30 +0000348 unsigned I = 0;
349 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000350 NamedDecl *D = Decls[I]->getUnderlyingDecl();
351 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000352
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000353 // Redeclarations of types via typedef can occur both within a scope
354 // and, through using declarations and directives, across scopes. There is
355 // no ambiguity if they all refer to the same type, so unique based on the
356 // canonical type.
357 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
358 if (!TD->getDeclContext()->isRecord()) {
359 QualType T = SemaRef.Context.getTypeDeclType(TD);
360 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
361 // The type is not unique; pull something off the back and continue
362 // at this index.
363 Decls[I] = Decls[--N];
364 continue;
365 }
366 }
367 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000368
John McCall314be4e2009-11-17 07:50:12 +0000369 if (!Unique.insert(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000370 // If it's not unique, pull something off the back (and
371 // continue at this index).
372 Decls[I] = Decls[--N];
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000373 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000374 }
375
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000376 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000377
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000378 if (isa<UnresolvedUsingValueDecl>(D)) {
379 HasUnresolved = true;
380 } else if (isa<TagDecl>(D)) {
381 if (HasTag)
382 Ambiguous = true;
383 UniqueTagIndex = I;
384 HasTag = true;
385 } else if (isa<FunctionTemplateDecl>(D)) {
386 HasFunction = true;
387 HasFunctionTemplate = true;
388 } else if (isa<FunctionDecl>(D)) {
389 HasFunction = true;
390 } else {
391 if (HasNonFunction)
392 Ambiguous = true;
393 HasNonFunction = true;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000394 }
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000395 I++;
Mike Stump1eb44332009-09-09 15:08:12 +0000396 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000397
John McCallf36e02d2009-10-09 21:13:30 +0000398 // C++ [basic.scope.hiding]p2:
399 // A class name or enumeration name can be hidden by the name of
400 // an object, function, or enumerator declared in the same
401 // scope. If a class or enumeration name and an object, function,
402 // or enumerator are declared in the same scope (in any order)
403 // with the same name, the class or enumeration name is hidden
404 // wherever the object, function, or enumerator name is visible.
405 // But it's still an error if there are distinct tag types found,
406 // even if they're not visible. (ref?)
John McCallfda8e122009-12-03 00:58:24 +0000407 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregor77a1a882010-10-23 16:06:17 +0000408 (HasFunction || HasNonFunction || HasUnresolved)) {
409 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
410 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
411 Decls[UniqueTagIndex] = Decls[--N];
412 else
413 Ambiguous = true;
414 }
Anders Carlsson8b50d012009-06-26 03:37:05 +0000415
John McCallf36e02d2009-10-09 21:13:30 +0000416 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000417
John McCallfda8e122009-12-03 00:58:24 +0000418 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000419 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000420
John McCallf36e02d2009-10-09 21:13:30 +0000421 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000422 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000423 else if (HasUnresolved)
424 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000425 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000426 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000427 else
John McCalla24dc2e2009-11-17 02:14:36 +0000428 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000429}
430
John McCall7d384dd2009-11-18 07:57:50 +0000431void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall6b2accb2010-02-10 09:31:12 +0000432 CXXBasePaths::const_paths_iterator I, E;
John McCallf36e02d2009-10-09 21:13:30 +0000433 DeclContext::lookup_iterator DI, DE;
434 for (I = P.begin(), E = P.end(); I != E; ++I)
435 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
436 addDecl(*DI);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000437}
438
John McCall7d384dd2009-11-18 07:57:50 +0000439void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000440 Paths = new CXXBasePaths;
441 Paths->swap(P);
442 addDeclsFromBasePaths(*Paths);
443 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000444 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000445}
446
John McCall7d384dd2009-11-18 07:57:50 +0000447void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000448 Paths = new CXXBasePaths;
449 Paths->swap(P);
450 addDeclsFromBasePaths(*Paths);
451 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000452 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000453}
454
John McCall7d384dd2009-11-18 07:57:50 +0000455void LookupResult::print(llvm::raw_ostream &Out) {
John McCallf36e02d2009-10-09 21:13:30 +0000456 Out << Decls.size() << " result(s)";
457 if (isAmbiguous()) Out << ", ambiguous";
458 if (Paths) Out << ", base paths present";
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000459
John McCallf36e02d2009-10-09 21:13:30 +0000460 for (iterator I = begin(), E = end(); I != E; ++I) {
461 Out << "\n";
462 (*I)->print(Out, 2);
463 }
464}
465
Douglas Gregor85910982010-02-12 05:48:04 +0000466/// \brief Lookup a builtin function, when name lookup would otherwise
467/// fail.
468static bool LookupBuiltin(Sema &S, LookupResult &R) {
469 Sema::LookupNameKind NameKind = R.getLookupKind();
470
471 // If we didn't find a use of this identifier, and if the identifier
472 // corresponds to a compiler builtin, create the decl object for the builtin
473 // now, injecting it into translation unit scope, and return it.
474 if (NameKind == Sema::LookupOrdinaryName ||
475 NameKind == Sema::LookupRedeclarationWithLinkage) {
476 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
477 if (II) {
478 // If this is a builtin on this (or all) targets, create the decl.
479 if (unsigned BuiltinID = II->getBuiltinID()) {
480 // In C++, we don't have any predefined library functions like
481 // 'malloc'. Instead, we'll just error.
482 if (S.getLangOptions().CPlusPlus &&
483 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
484 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000485
486 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
487 BuiltinID, S.TUScope,
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000488 R.isForRedeclaration(),
489 R.getNameLoc())) {
Douglas Gregor85910982010-02-12 05:48:04 +0000490 R.addDecl(D);
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000491 return true;
492 }
493
494 if (R.isForRedeclaration()) {
495 // If we're redeclaring this function anyway, forget that
496 // this was a builtin at all.
497 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
498 }
499
500 return false;
Douglas Gregor85910982010-02-12 05:48:04 +0000501 }
502 }
503 }
504
505 return false;
506}
507
Douglas Gregor4923aa22010-07-02 20:37:36 +0000508/// \brief Determine whether we can declare a special member function within
509/// the class at this point.
510static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
511 const CXXRecordDecl *Class) {
John McCallb3b50a82010-08-11 23:52:36 +0000512 // Don't do it if the class is invalid.
513 if (Class->isInvalidDecl())
514 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000515
Douglas Gregor4923aa22010-07-02 20:37:36 +0000516 // We need to have a definition for the class.
517 if (!Class->getDefinition() || Class->isDependentContext())
518 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000519
Douglas Gregor4923aa22010-07-02 20:37:36 +0000520 // We can't be in the middle of defining the class.
521 if (const RecordType *RecordTy
522 = Context.getTypeDeclType(Class)->getAs<RecordType>())
523 return !RecordTy->isBeingDefined();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000524
Douglas Gregor4923aa22010-07-02 20:37:36 +0000525 return false;
526}
527
528void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregor22584312010-07-02 23:41:54 +0000529 if (!CanDeclareSpecialMemberFunction(Context, Class))
530 return;
Douglas Gregor18274032010-07-03 00:47:00 +0000531
532 // If the default constructor has not yet been declared, do so now.
533 if (!Class->hasDeclaredDefaultConstructor())
534 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000535
Douglas Gregor22584312010-07-02 23:41:54 +0000536 // If the copy constructor has not yet been declared, do so now.
537 if (!Class->hasDeclaredCopyConstructor())
538 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000539
Douglas Gregora376d102010-07-02 21:50:04 +0000540 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000541 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +0000542 DeclareImplicitCopyAssignment(Class);
543
Douglas Gregor4923aa22010-07-02 20:37:36 +0000544 // If the destructor has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000545 if (!Class->hasDeclaredDestructor())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000546 DeclareImplicitDestructor(Class);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000547}
548
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000549/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregora376d102010-07-02 21:50:04 +0000550/// special member function.
551static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
552 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000553 case DeclarationName::CXXConstructorName:
Douglas Gregora376d102010-07-02 21:50:04 +0000554 case DeclarationName::CXXDestructorName:
555 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000556
Douglas Gregora376d102010-07-02 21:50:04 +0000557 case DeclarationName::CXXOperatorName:
558 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000559
Douglas Gregora376d102010-07-02 21:50:04 +0000560 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000561 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000562 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000563
Douglas Gregora376d102010-07-02 21:50:04 +0000564 return false;
565}
566
567/// \brief If there are any implicit member functions with the given name
568/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000569static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregora376d102010-07-02 21:50:04 +0000570 DeclarationName Name,
571 const DeclContext *DC) {
572 if (!DC)
573 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000574
Douglas Gregora376d102010-07-02 21:50:04 +0000575 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000576 case DeclarationName::CXXConstructorName:
577 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor18274032010-07-03 00:47:00 +0000578 if (Record->getDefinition() &&
579 CanDeclareSpecialMemberFunction(S.Context, Record)) {
580 if (!Record->hasDeclaredDefaultConstructor())
581 S.DeclareImplicitDefaultConstructor(
582 const_cast<CXXRecordDecl *>(Record));
583 if (!Record->hasDeclaredCopyConstructor())
584 S.DeclareImplicitCopyConstructor(const_cast<CXXRecordDecl *>(Record));
585 }
Douglas Gregor22584312010-07-02 23:41:54 +0000586 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000587
Douglas Gregora376d102010-07-02 21:50:04 +0000588 case DeclarationName::CXXDestructorName:
589 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
590 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
591 CanDeclareSpecialMemberFunction(S.Context, Record))
592 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregora376d102010-07-02 21:50:04 +0000593 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000594
Douglas Gregora376d102010-07-02 21:50:04 +0000595 case DeclarationName::CXXOperatorName:
596 if (Name.getCXXOverloadedOperator() != OO_Equal)
597 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000598
Douglas Gregora376d102010-07-02 21:50:04 +0000599 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
600 if (Record->getDefinition() && !Record->hasDeclaredCopyAssignment() &&
601 CanDeclareSpecialMemberFunction(S.Context, Record))
602 S.DeclareImplicitCopyAssignment(const_cast<CXXRecordDecl *>(Record));
603 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000604
Douglas Gregora376d102010-07-02 21:50:04 +0000605 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000606 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000607 }
608}
Douglas Gregor4923aa22010-07-02 20:37:36 +0000609
John McCallf36e02d2009-10-09 21:13:30 +0000610// Adds all qualifying matches for a name within a decl context to the
611// given lookup result. Returns true if any matches were found.
Douglas Gregor85910982010-02-12 05:48:04 +0000612static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000613 bool Found = false;
614
Douglas Gregor4923aa22010-07-02 20:37:36 +0000615 // Lazily declare C++ special member functions.
Douglas Gregora376d102010-07-02 21:50:04 +0000616 if (S.getLangOptions().CPlusPlus)
617 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000618
Douglas Gregor4923aa22010-07-02 20:37:36 +0000619 // Perform lookup into this declaration context.
John McCalld7be78a2009-11-10 07:01:13 +0000620 DeclContext::lookup_const_iterator I, E;
Douglas Gregor48026d22010-01-11 18:40:55 +0000621 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall46460a62010-01-20 21:53:11 +0000622 NamedDecl *D = *I;
623 if (R.isAcceptableDecl(D)) {
624 R.addDecl(D);
Douglas Gregor48026d22010-01-11 18:40:55 +0000625 Found = true;
626 }
627 }
John McCallf36e02d2009-10-09 21:13:30 +0000628
Douglas Gregor85910982010-02-12 05:48:04 +0000629 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
630 return true;
631
Douglas Gregor48026d22010-01-11 18:40:55 +0000632 if (R.getLookupName().getNameKind()
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000633 != DeclarationName::CXXConversionFunctionName ||
634 R.getLookupName().getCXXNameType()->isDependentType() ||
635 !isa<CXXRecordDecl>(DC))
636 return Found;
637
638 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000639 // A specialization of a conversion function template is not found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000640 // name lookup. Instead, any conversion function templates visible in the
641 // context of the use are considered. [...]
642 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
643 if (!Record->isDefinition())
644 return Found;
645
646 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000647 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000648 UEnd = Unresolved->end(); U != UEnd; ++U) {
649 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
650 if (!ConvTemplate)
651 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000652
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000653 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000654 // add the conversion function template. When we deduce template
655 // arguments for specializations, we'll end up unifying the return
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000656 // type of the new declaration with the type of the function template.
657 if (R.isForRedeclaration()) {
658 R.addDecl(ConvTemplate);
659 Found = true;
660 continue;
661 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000662
Douglas Gregor48026d22010-01-11 18:40:55 +0000663 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000664 // [...] For each such operator, if argument deduction succeeds
665 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000666 // name lookup.
667 //
668 // When referencing a conversion function for any purpose other than
669 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000670 // result), perform template argument deduction and place the
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000671 // specialization into the result set. We do this to avoid forcing all
672 // callers to perform special deduction for conversion functions.
John McCall2a7fb272010-08-25 05:32:35 +0000673 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000674 FunctionDecl *Specialization = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000675
676 const FunctionProtoType *ConvProto
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000677 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
678 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3f477a12010-01-12 01:17:50 +0000679
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000680 // Compute the type of the function that we would expect the conversion
681 // function to have, if it were to match the name given.
682 // FIXME: Calling convention!
John McCalle23cf432010-12-14 08:05:40 +0000683 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
684 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
685 EPI.HasExceptionSpec = false;
686 EPI.HasAnyExceptionSpec = false;
687 EPI.NumExceptions = 0;
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000688 QualType ExpectedType
689 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
John McCalle23cf432010-12-14 08:05:40 +0000690 0, 0, EPI);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000691
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000692 // Perform template argument deduction against the type that we would
693 // expect the function to have.
694 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
695 Specialization, Info)
696 == Sema::TDK_Success) {
697 R.addDecl(Specialization);
698 Found = true;
Douglas Gregor48026d22010-01-11 18:40:55 +0000699 }
700 }
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000701
John McCallf36e02d2009-10-09 21:13:30 +0000702 return Found;
703}
704
John McCalld7be78a2009-11-10 07:01:13 +0000705// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000706static bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000707CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregor85910982010-02-12 05:48:04 +0000708 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000709
710 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
711
John McCalld7be78a2009-11-10 07:01:13 +0000712 // Perform direct name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +0000713 bool Found = LookupDirect(S, R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000714
John McCalld7be78a2009-11-10 07:01:13 +0000715 // Perform direct name lookup into the namespaces nominated by the
716 // using directives whose common ancestor is this namespace.
717 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
718 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000719
John McCalld7be78a2009-11-10 07:01:13 +0000720 for (; UI != UEnd; ++UI)
Douglas Gregor85910982010-02-12 05:48:04 +0000721 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000722 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000723
724 R.resolveKind();
725
726 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000727}
728
729static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000730 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000731 return Ctx->isFileContext();
732 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000733}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000734
Douglas Gregor711be1e2010-03-15 14:33:29 +0000735// Find the next outer declaration context from this scope. This
736// routine actually returns the semantic outer context, which may
737// differ from the lexical context (encoded directly in the Scope
738// stack) when we are parsing a member of a class template. In this
739// case, the second element of the pair will be true, to indicate that
740// name lookup should continue searching in this semantic context when
741// it leaves the current template parameter scope.
742static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
743 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
744 DeclContext *Lexical = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000745 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor711be1e2010-03-15 14:33:29 +0000746 OuterS = OuterS->getParent()) {
747 if (OuterS->getEntity()) {
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000748 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor711be1e2010-03-15 14:33:29 +0000749 break;
750 }
751 }
752
753 // C++ [temp.local]p8:
754 // In the definition of a member of a class template that appears
755 // outside of the namespace containing the class template
756 // definition, the name of a template-parameter hides the name of
757 // a member of this namespace.
758 //
759 // Example:
760 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000761 // namespace N {
762 // class C { };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000763 //
764 // template<class T> class B {
765 // void f(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000766 // };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000767 // }
768 //
769 // template<class C> void N::B<C>::f(C) {
770 // C b; // C is the template parameter, not N::C
771 // }
772 //
773 // In this example, the lexical context we return is the
774 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000775 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor711be1e2010-03-15 14:33:29 +0000776 !S->getParent()->isTemplateParamScope())
777 return std::make_pair(Lexical, false);
778
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000779 // Find the outermost template parameter scope.
Douglas Gregor711be1e2010-03-15 14:33:29 +0000780 // For the example, this is the scope for the template parameters of
781 // template<class C>.
782 Scope *OutermostTemplateScope = S->getParent();
783 while (OutermostTemplateScope->getParent() &&
784 OutermostTemplateScope->getParent()->isTemplateParamScope())
785 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000786
Douglas Gregor711be1e2010-03-15 14:33:29 +0000787 // Find the namespace context in which the original scope occurs. In
788 // the example, this is namespace N.
789 DeclContext *Semantic = DC;
790 while (!Semantic->isFileContext())
791 Semantic = Semantic->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000792
Douglas Gregor711be1e2010-03-15 14:33:29 +0000793 // Find the declaration context just outside of the template
794 // parameter scope. This is the context in which the template is
795 // being lexically declaration (a namespace context). In the
796 // example, this is the global scope.
797 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
798 Lexical->Encloses(Semantic))
799 return std::make_pair(Semantic, true);
800
801 return std::make_pair(Lexical, false);
Douglas Gregore942bbe2009-09-10 16:57:35 +0000802}
803
John McCalla24dc2e2009-11-17 02:14:36 +0000804bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCall1d7c5282009-12-18 10:40:03 +0000805 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000806
807 DeclarationName Name = R.getLookupName();
808
Douglas Gregora376d102010-07-02 21:50:04 +0000809 // If this is the name of an implicitly-declared special member function,
810 // go through the scope stack to implicitly declare
811 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
812 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
813 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
814 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
815 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000816
Douglas Gregora376d102010-07-02 21:50:04 +0000817 // Implicitly declare member functions with the name we're looking for, if in
818 // fact we are in a scope where it matters.
819
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000820 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000821 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000822 I = IdResolver.begin(Name),
823 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000824
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000825 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000826 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000827 // ...During unqualified name lookup (3.4.1), the names appear as if
828 // they were declared in the nearest enclosing namespace which contains
829 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000830 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000831 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000832 //
833 // For example:
834 // namespace A { int i; }
835 // void foo() {
836 // int i;
837 // {
838 // using namespace A;
839 // ++i; // finds local 'i', A::i appears at global scope
840 // }
841 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000842 //
Douglas Gregor711be1e2010-03-15 14:33:29 +0000843 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000844 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregord2235f62010-05-20 20:58:56 +0000845 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
846
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000847 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000848 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000849 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000850 if (R.isAcceptableDecl(*I)) {
John McCallf36e02d2009-10-09 21:13:30 +0000851 Found = true;
852 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000853 }
854 }
John McCallf36e02d2009-10-09 21:13:30 +0000855 if (Found) {
856 R.resolveKind();
Douglas Gregord2235f62010-05-20 20:58:56 +0000857 if (S->isClassScope())
858 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
859 R.setNamingClass(Record);
John McCallf36e02d2009-10-09 21:13:30 +0000860 return true;
861 }
862
Douglas Gregor711be1e2010-03-15 14:33:29 +0000863 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
864 S->getParent() && !S->getParent()->isTemplateParamScope()) {
865 // We've just searched the last template parameter scope and
866 // found nothing, so look into the the contexts between the
867 // lexical and semantic declaration contexts returned by
868 // findOuterContext(). This implements the name lookup behavior
869 // of C++ [temp.local]p8.
870 Ctx = OutsideOfTemplateParamDC;
871 OutsideOfTemplateParamDC = 0;
872 }
873
874 if (Ctx) {
875 DeclContext *OuterCtx;
876 bool SearchAfterTemplateScope;
877 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
878 if (SearchAfterTemplateScope)
879 OutsideOfTemplateParamDC = OuterCtx;
880
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000881 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-02-19 16:08:35 +0000882 // We do not directly look into transparent contexts, since
883 // those entities will be found in the nearest enclosing
884 // non-transparent context.
885 if (Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000886 continue;
Douglas Gregor36262b82010-02-19 16:08:35 +0000887
888 // We do not look directly into function or method contexts,
889 // since all of the local variables and parameters of the
890 // function/method are present within the Scope.
891 if (Ctx->isFunctionOrMethod()) {
892 // If we have an Objective-C instance method, look for ivars
893 // in the corresponding interface.
894 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
895 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
896 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
897 ObjCInterfaceDecl *ClassDeclared;
898 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000899 Name.getAsIdentifierInfo(),
Douglas Gregor36262b82010-02-19 16:08:35 +0000900 ClassDeclared)) {
901 if (R.isAcceptableDecl(Ivar)) {
902 R.addDecl(Ivar);
903 R.resolveKind();
904 return true;
905 }
906 }
907 }
908 }
909
910 continue;
911 }
912
Douglas Gregore942bbe2009-09-10 16:57:35 +0000913 // Perform qualified name lookup into this context.
914 // FIXME: In some cases, we know that every name that could be found by
915 // this qualified name lookup will also be on the identifier chain. For
916 // example, inside a class without any base classes, we never need to
917 // perform qualified lookup because all of the members are on top of the
918 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000919 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +0000920 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +0000921 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000922 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000923 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000924
John McCalld7be78a2009-11-10 07:01:13 +0000925 // Stop if we ran out of scopes.
926 // FIXME: This really, really shouldn't be happening.
927 if (!S) return false;
928
Argyrios Kyrtzidis78f59112010-10-29 16:12:50 +0000929 // If we are looking for members, no need to look into global/namespace scope.
930 if (R.getLookupKind() == LookupMemberName)
931 return false;
932
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000933 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000934 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +0000935 //
Mike Stump390b4cc2009-05-16 07:39:55 +0000936 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
937 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000938
John McCalld7be78a2009-11-10 07:01:13 +0000939 UnqualUsingDirectiveSet UDirs;
940 UDirs.visitScopeChain(Initial, S);
941 UDirs.done();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000942
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000943 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000944 // Unqualified name lookup in C++ requires looking into scopes
945 // that aren't strictly lexical, and therefore we walk through the
946 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000947
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000948 for (; S; S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000949 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000950 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000951 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000952 if (R.isAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000953 // We found something. Look for anything else in our scope
954 // with this same name and in an acceptable identifier
955 // namespace, so that we can construct an overload set if we
956 // need to.
John McCallf36e02d2009-10-09 21:13:30 +0000957 Found = true;
958 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000959 }
960 }
961
Douglas Gregor00b4b032010-05-14 04:53:42 +0000962 if (Found && S->isTemplateParamScope()) {
John McCallf36e02d2009-10-09 21:13:30 +0000963 R.resolveKind();
964 return true;
965 }
966
Douglas Gregor00b4b032010-05-14 04:53:42 +0000967 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
968 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
969 S->getParent() && !S->getParent()->isTemplateParamScope()) {
970 // We've just searched the last template parameter scope and
971 // found nothing, so look into the the contexts between the
972 // lexical and semantic declaration contexts returned by
973 // findOuterContext(). This implements the name lookup behavior
974 // of C++ [temp.local]p8.
975 Ctx = OutsideOfTemplateParamDC;
976 OutsideOfTemplateParamDC = 0;
977 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000978
Douglas Gregor00b4b032010-05-14 04:53:42 +0000979 if (Ctx) {
980 DeclContext *OuterCtx;
981 bool SearchAfterTemplateScope;
982 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
983 if (SearchAfterTemplateScope)
984 OutsideOfTemplateParamDC = OuterCtx;
985
986 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
987 // We do not directly look into transparent contexts, since
988 // those entities will be found in the nearest enclosing
989 // non-transparent context.
990 if (Ctx->isTransparentContext())
991 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000992
Douglas Gregor00b4b032010-05-14 04:53:42 +0000993 // If we have a context, and it's not a context stashed in the
994 // template parameter scope for an out-of-line definition, also
995 // look into that context.
996 if (!(Found && S && S->isTemplateParamScope())) {
997 assert(Ctx->isFileContext() &&
998 "We should have been looking only at file context here already.");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000999
Douglas Gregor00b4b032010-05-14 04:53:42 +00001000 // Look into context considering using-directives.
1001 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1002 Found = true;
1003 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001004
Douglas Gregor00b4b032010-05-14 04:53:42 +00001005 if (Found) {
1006 R.resolveKind();
1007 return true;
1008 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001009
Douglas Gregor00b4b032010-05-14 04:53:42 +00001010 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1011 return false;
1012 }
1013 }
1014
Douglas Gregor1df0ee92010-02-05 07:07:10 +00001015 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +00001016 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001017 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001018
John McCallf36e02d2009-10-09 21:13:30 +00001019 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001020}
1021
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001022/// @brief Perform unqualified name lookup starting from a given
1023/// scope.
1024///
1025/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1026/// used to find names within the current scope. For example, 'x' in
1027/// @code
1028/// int x;
1029/// int f() {
1030/// return x; // unqualified name look finds 'x' in the global scope
1031/// }
1032/// @endcode
1033///
1034/// Different lookup criteria can find different names. For example, a
1035/// particular scope can have both a struct and a function of the same
1036/// name, and each can be found by certain lookup criteria. For more
1037/// information about lookup criteria, see the documentation for the
1038/// class LookupCriteria.
1039///
1040/// @param S The scope from which unqualified name lookup will
1041/// begin. If the lookup criteria permits, name lookup may also search
1042/// in the parent scopes.
1043///
1044/// @param Name The name of the entity that we are searching for.
1045///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001046/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001047/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001048/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001049///
1050/// @returns The result of name lookup, which includes zero or more
1051/// declarations and possibly additional information used to diagnose
1052/// ambiguities.
John McCalla24dc2e2009-11-17 02:14:36 +00001053bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1054 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +00001055 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001056
John McCalla24dc2e2009-11-17 02:14:36 +00001057 LookupNameKind NameKind = R.getLookupKind();
1058
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001059 if (!getLangOptions().CPlusPlus) {
1060 // Unqualified name lookup in C/Objective-C is purely lexical, so
1061 // search in the declarations attached to the name.
1062
John McCall1d7c5282009-12-18 10:40:03 +00001063 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001064 // Find the nearest non-transparent declaration scope.
1065 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001066 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001067 static_cast<DeclContext *>(S->getEntity())
1068 ->isTransparentContext()))
1069 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001070 }
1071
John McCall1d7c5282009-12-18 10:40:03 +00001072 unsigned IDNS = R.getIdentifierNamespace();
1073
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001074 // Scan up the scope chain looking for a decl that matches this
1075 // identifier that is in the appropriate namespace. This search
1076 // should not take long, as shadowing of names is uncommon, and
1077 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001078 bool LeftStartingScope = false;
1079
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001080 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +00001081 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001082 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001083 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001084 if (NameKind == LookupRedeclarationWithLinkage) {
1085 // Determine whether this (or a previous) declaration is
1086 // out-of-scope.
John McCalld226f652010-08-21 09:40:31 +00001087 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001088 LeftStartingScope = true;
1089
1090 // If we found something outside of our starting scope that
1091 // does not have linkage, skip it.
1092 if (LeftStartingScope && !((*I)->hasLinkage()))
1093 continue;
1094 }
1095
John McCallf36e02d2009-10-09 21:13:30 +00001096 R.addDecl(*I);
1097
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001098 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00001099 // If this declaration has the "overloadable" attribute, we
1100 // might have a set of overloaded functions.
1101
1102 // Figure out what scope the identifier is in.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001103 while (!(S->getFlags() & Scope::DeclScope) ||
John McCalld226f652010-08-21 09:40:31 +00001104 !S->isDeclScope(*I))
Douglas Gregorf9201e02009-02-11 23:02:49 +00001105 S = S->getParent();
1106
1107 // Find the last declaration in this scope (with the same
1108 // name, naturally).
1109 IdentifierResolver::iterator LastI = I;
1110 for (++LastI; LastI != IEnd; ++LastI) {
John McCalld226f652010-08-21 09:40:31 +00001111 if (!S->isDeclScope(*LastI))
Douglas Gregorf9201e02009-02-11 23:02:49 +00001112 break;
John McCallf36e02d2009-10-09 21:13:30 +00001113 R.addDecl(*LastI);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001114 }
Douglas Gregorf9201e02009-02-11 23:02:49 +00001115 }
1116
John McCallf36e02d2009-10-09 21:13:30 +00001117 R.resolveKind();
1118
1119 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +00001120 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001121 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001122 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +00001123 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +00001124 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001125 }
1126
1127 // If we didn't find a use of this identifier, and if the identifier
1128 // corresponds to a compiler builtin, create the decl object for the builtin
1129 // now, injecting it into translation unit scope, and return it.
Douglas Gregor85910982010-02-12 05:48:04 +00001130 if (AllowBuiltinCreation)
1131 return LookupBuiltin(*this, R);
Douglas Gregor3e41d602009-02-13 23:20:09 +00001132
John McCallf36e02d2009-10-09 21:13:30 +00001133 return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001134}
1135
John McCall6e247262009-10-10 05:48:19 +00001136/// @brief Perform qualified name lookup in the namespaces nominated by
1137/// using directives by the given context.
1138///
1139/// C++98 [namespace.qual]p2:
1140/// Given X::m (where X is a user-declared namespace), or given ::m
1141/// (where X is the global namespace), let S be the set of all
1142/// declarations of m in X and in the transitive closure of all
1143/// namespaces nominated by using-directives in X and its used
1144/// namespaces, except that using-directives are ignored in any
1145/// namespace, including X, directly containing one or more
1146/// declarations of m. No namespace is searched more than once in
1147/// the lookup of a name. If S is the empty set, the program is
1148/// ill-formed. Otherwise, if S has exactly one member, or if the
1149/// context of the reference is a using-declaration
1150/// (namespace.udecl), S is the required set of declarations of
1151/// m. Otherwise if the use of m is not one that allows a unique
1152/// declaration to be chosen from S, the program is ill-formed.
1153/// C++98 [namespace.qual]p5:
1154/// During the lookup of a qualified namespace member name, if the
1155/// lookup finds more than one declaration of the member, and if one
1156/// declaration introduces a class name or enumeration name and the
1157/// other declarations either introduce the same object, the same
1158/// enumerator or a set of functions, the non-type name hides the
1159/// class or enumeration name if and only if the declarations are
1160/// from the same namespace; otherwise (the declarations are from
1161/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +00001162static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +00001163 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +00001164 assert(StartDC->isFileContext() && "start context is not a file context");
1165
1166 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1167 DeclContext::udir_iterator E = StartDC->using_directives_end();
1168
1169 if (I == E) return false;
1170
1171 // We have at least added all these contexts to the queue.
1172 llvm::DenseSet<DeclContext*> Visited;
1173 Visited.insert(StartDC);
1174
1175 // We have not yet looked into these namespaces, much less added
1176 // their "using-children" to the queue.
1177 llvm::SmallVector<NamespaceDecl*, 8> Queue;
1178
1179 // We have already looked into the initial namespace; seed the queue
1180 // with its using-children.
1181 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001182 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6e247262009-10-10 05:48:19 +00001183 if (Visited.insert(ND).second)
1184 Queue.push_back(ND);
1185 }
1186
1187 // The easiest way to implement the restriction in [namespace.qual]p5
1188 // is to check whether any of the individual results found a tag
1189 // and, if so, to declare an ambiguity if the final result is not
1190 // a tag.
1191 bool FoundTag = false;
1192 bool FoundNonTag = false;
1193
John McCall7d384dd2009-11-18 07:57:50 +00001194 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001195
1196 bool Found = false;
1197 while (!Queue.empty()) {
1198 NamespaceDecl *ND = Queue.back();
1199 Queue.pop_back();
1200
1201 // We go through some convolutions here to avoid copying results
1202 // between LookupResults.
1203 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001204 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001205 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001206
1207 if (FoundDirect) {
1208 // First do any local hiding.
1209 DirectR.resolveKind();
1210
1211 // If the local result is a tag, remember that.
1212 if (DirectR.isSingleTagDecl())
1213 FoundTag = true;
1214 else
1215 FoundNonTag = true;
1216
1217 // Append the local results to the total results if necessary.
1218 if (UseLocal) {
1219 R.addAllDecls(LocalR);
1220 LocalR.clear();
1221 }
1222 }
1223
1224 // If we find names in this namespace, ignore its using directives.
1225 if (FoundDirect) {
1226 Found = true;
1227 continue;
1228 }
1229
1230 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1231 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1232 if (Visited.insert(Nom).second)
1233 Queue.push_back(Nom);
1234 }
1235 }
1236
1237 if (Found) {
1238 if (FoundTag && FoundNonTag)
1239 R.setAmbiguousQualifiedTagHiding();
1240 else
1241 R.resolveKind();
1242 }
1243
1244 return Found;
1245}
1246
Douglas Gregor8071e422010-08-15 06:18:01 +00001247/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001248static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor8071e422010-08-15 06:18:01 +00001249 CXXBasePath &Path,
1250 void *Name) {
1251 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001252
Douglas Gregor8071e422010-08-15 06:18:01 +00001253 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1254 Path.Decls = BaseRecord->lookup(N);
1255 return Path.Decls.first != Path.Decls.second;
1256}
1257
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001258/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001259/// static members, nested types, and enumerators.
1260template<typename InputIterator>
1261static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1262 Decl *D = (*First)->getUnderlyingDecl();
1263 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1264 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001265
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001266 if (isa<CXXMethodDecl>(D)) {
1267 // Determine whether all of the methods are static.
1268 bool AllMethodsAreStatic = true;
1269 for(; First != Last; ++First) {
1270 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001271
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001272 if (!isa<CXXMethodDecl>(D)) {
1273 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1274 break;
1275 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001276
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001277 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1278 AllMethodsAreStatic = false;
1279 break;
1280 }
1281 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001282
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001283 if (AllMethodsAreStatic)
1284 return true;
1285 }
1286
1287 return false;
1288}
1289
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001290/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001291///
1292/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1293/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001294/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001295///
1296/// Different lookup criteria can find different names. For example, a
1297/// particular scope can have both a struct and a function of the same
1298/// name, and each can be found by certain lookup criteria. For more
1299/// information about lookup criteria, see the documentation for the
1300/// class LookupCriteria.
1301///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001302/// \param R captures both the lookup criteria and any lookup results found.
1303///
1304/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001305/// search. If the lookup criteria permits, name lookup may also search
1306/// in the parent contexts or (for C++ classes) base classes.
1307///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001308/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001309/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001310///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001311/// \returns true if lookup succeeded, false if it failed.
1312bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1313 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001314 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001315
John McCalla24dc2e2009-11-17 02:14:36 +00001316 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001317 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001318
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001319 // Make sure that the declaration context is complete.
1320 assert((!isa<TagDecl>(LookupCtx) ||
1321 LookupCtx->isDependentContext() ||
1322 cast<TagDecl>(LookupCtx)->isDefinition() ||
1323 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1324 ->isBeingDefined()) &&
1325 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001326
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001327 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001328 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001329 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001330 if (isa<CXXRecordDecl>(LookupCtx))
1331 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001332 return true;
1333 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001334
John McCall6e247262009-10-10 05:48:19 +00001335 // Don't descend into implied contexts for redeclarations.
1336 // C++98 [namespace.qual]p6:
1337 // In a declaration for a namespace member in which the
1338 // declarator-id is a qualified-id, given that the qualified-id
1339 // for the namespace member has the form
1340 // nested-name-specifier unqualified-id
1341 // the unqualified-id shall name a member of the namespace
1342 // designated by the nested-name-specifier.
1343 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001344 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001345 return false;
1346
John McCalla24dc2e2009-11-17 02:14:36 +00001347 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001348 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001349 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001350
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001351 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001352 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001353 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor025291b2010-07-01 00:21:21 +00001354 if (!LookupRec || !LookupRec->getDefinition())
John McCallf36e02d2009-10-09 21:13:30 +00001355 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001356
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001357 // If we're performing qualified name lookup into a dependent class,
1358 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001359 // dependent base classes, then we either have to delay lookup until
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001360 // template instantiation time (at which point all bases will be available)
1361 // or we have to fail.
1362 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1363 LookupRec->hasAnyDependentBases()) {
1364 R.setNotFoundInCurrentInstantiation();
1365 return false;
1366 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001367
Douglas Gregor7176fff2009-01-15 00:26:24 +00001368 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001369 CXXBasePaths Paths;
1370 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001371
1372 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001373 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001374 switch (R.getLookupKind()) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001375 case LookupOrdinaryName:
1376 case LookupMemberName:
1377 case LookupRedeclarationWithLinkage:
1378 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1379 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001380
Douglas Gregora8f32e02009-10-06 17:59:45 +00001381 case LookupTagName:
1382 BaseCallback = &CXXRecordDecl::FindTagMember;
1383 break;
John McCall9f54ad42009-12-10 09:41:52 +00001384
Douglas Gregor8071e422010-08-15 06:18:01 +00001385 case LookupAnyName:
1386 BaseCallback = &LookupAnyMember;
1387 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001388
John McCall9f54ad42009-12-10 09:41:52 +00001389 case LookupUsingDeclName:
1390 // This lookup is for redeclarations only.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001391
Douglas Gregora8f32e02009-10-06 17:59:45 +00001392 case LookupOperatorName:
1393 case LookupNamespaceName:
1394 case LookupObjCProtocolName:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001395 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001396 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001397
Douglas Gregora8f32e02009-10-06 17:59:45 +00001398 case LookupNestedNameSpecifierName:
1399 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1400 break;
1401 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001402
John McCalla24dc2e2009-11-17 02:14:36 +00001403 if (!LookupRec->lookupInBases(BaseCallback,
1404 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001405 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001406
John McCall92f88312010-01-23 00:46:32 +00001407 R.setNamingClass(LookupRec);
1408
Douglas Gregor7176fff2009-01-15 00:26:24 +00001409 // C++ [class.member.lookup]p2:
1410 // [...] If the resulting set of declarations are not all from
1411 // sub-objects of the same type, or the set has a nonstatic member
1412 // and includes members from distinct sub-objects, there is an
1413 // ambiguity and the program is ill-formed. Otherwise that set is
1414 // the result of the lookup.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001415 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001416 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001417 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001418
Douglas Gregora8f32e02009-10-06 17:59:45 +00001419 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001420 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001421 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001422
John McCall46460a62010-01-20 21:53:11 +00001423 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1424 // across all paths.
1425 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001426
Douglas Gregor7176fff2009-01-15 00:26:24 +00001427 // Determine whether we're looking at a distinct sub-object or not.
1428 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001429 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001430 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1431 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001432 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001433 }
1434
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001435 if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001436 != Context.getCanonicalType(PathElement.Base->getType())) {
1437 // We found members of the given name in two subobjects of
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001438 // different types. If the declaration sets aren't the same, this
1439 // this lookup is ambiguous.
1440 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1441 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1442 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1443 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001444
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001445 while (FirstD != FirstPath->Decls.second &&
1446 CurrentD != Path->Decls.second) {
1447 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1448 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1449 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001450
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001451 ++FirstD;
1452 ++CurrentD;
1453 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001454
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001455 if (FirstD == FirstPath->Decls.second &&
1456 CurrentD == Path->Decls.second)
1457 continue;
1458 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001459
John McCallf36e02d2009-10-09 21:13:30 +00001460 R.setAmbiguousBaseSubobjectTypes(Paths);
1461 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001462 }
1463
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001464 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001465 // We have a different subobject of the same type.
1466
1467 // C++ [class.member.lookup]p5:
1468 // A static member, a nested type or an enumerator defined in
1469 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001470 // has more than one base class subobject of type T.
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001471 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
Douglas Gregor7176fff2009-01-15 00:26:24 +00001472 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001473
Douglas Gregor7176fff2009-01-15 00:26:24 +00001474 // We have found a nonstatic member name in multiple, distinct
1475 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001476 R.setAmbiguousBaseSubobjects(Paths);
1477 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001478 }
1479 }
1480
1481 // Lookup in a base class succeeded; return these results.
1482
John McCallf36e02d2009-10-09 21:13:30 +00001483 DeclContext::lookup_iterator I, E;
John McCall92f88312010-01-23 00:46:32 +00001484 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1485 NamedDecl *D = *I;
1486 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1487 D->getAccess());
1488 R.addDecl(D, AS);
1489 }
John McCallf36e02d2009-10-09 21:13:30 +00001490 R.resolveKind();
1491 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001492}
1493
1494/// @brief Performs name lookup for a name that was parsed in the
1495/// source code, and may contain a C++ scope specifier.
1496///
1497/// This routine is a convenience routine meant to be called from
1498/// contexts that receive a name and an optional C++ scope specifier
1499/// (e.g., "N::M::x"). It will then perform either qualified or
1500/// unqualified name lookup (with LookupQualifiedName or LookupName,
1501/// respectively) on the given name and return those results.
1502///
1503/// @param S The scope from which unqualified name lookup will
1504/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001505///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001506/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001507///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001508/// @param EnteringContext Indicates whether we are going to enter the
1509/// context of the scope-specifier SS (if present).
1510///
John McCallf36e02d2009-10-09 21:13:30 +00001511/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001512bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001513 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001514 if (SS && SS->isInvalid()) {
1515 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001516 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001517 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001518 }
Mike Stump1eb44332009-09-09 15:08:12 +00001519
Douglas Gregor495c35d2009-08-25 22:51:20 +00001520 if (SS && SS->isSet()) {
1521 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001522 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001523 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001524 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001525 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001526
John McCalla24dc2e2009-11-17 02:14:36 +00001527 R.setContextRange(SS->getRange());
1528
1529 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001530 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001531
Douglas Gregor495c35d2009-08-25 22:51:20 +00001532 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001533 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001534 // Name lookup can't find anything in this case.
John McCallf36e02d2009-10-09 21:13:30 +00001535 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001536 }
1537
Mike Stump1eb44332009-09-09 15:08:12 +00001538 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001539 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001540}
1541
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001542
Douglas Gregor7176fff2009-01-15 00:26:24 +00001543/// @brief Produce a diagnostic describing the ambiguity that resulted
1544/// from name lookup.
1545///
1546/// @param Result The ambiguous name lookup result.
Mike Stump1eb44332009-09-09 15:08:12 +00001547///
Douglas Gregor7176fff2009-01-15 00:26:24 +00001548/// @param Name The name of the entity that name lookup was
1549/// searching for.
1550///
1551/// @param NameLoc The location of the name within the source code.
1552///
1553/// @param LookupRange A source range that provides more
1554/// source-location information concerning the lookup itself. For
1555/// example, this range might highlight a nested-name-specifier that
1556/// precedes the name.
1557///
1558/// @returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001559bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001560 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1561
John McCalla24dc2e2009-11-17 02:14:36 +00001562 DeclarationName Name = Result.getLookupName();
1563 SourceLocation NameLoc = Result.getNameLoc();
1564 SourceRange LookupRange = Result.getContextRange();
1565
John McCall6e247262009-10-10 05:48:19 +00001566 switch (Result.getAmbiguityKind()) {
1567 case LookupResult::AmbiguousBaseSubobjects: {
1568 CXXBasePaths *Paths = Result.getBasePaths();
1569 QualType SubobjectType = Paths->front().back().Base->getType();
1570 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1571 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1572 << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001573
John McCall6e247262009-10-10 05:48:19 +00001574 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1575 while (isa<CXXMethodDecl>(*Found) &&
1576 cast<CXXMethodDecl>(*Found)->isStatic())
1577 ++Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001578
John McCall6e247262009-10-10 05:48:19 +00001579 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001580
John McCall6e247262009-10-10 05:48:19 +00001581 return true;
1582 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001583
John McCall6e247262009-10-10 05:48:19 +00001584 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001585 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1586 << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001587
John McCall6e247262009-10-10 05:48:19 +00001588 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001589 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001590 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1591 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001592 Path != PathEnd; ++Path) {
1593 Decl *D = *Path->Decls.first;
1594 if (DeclsPrinted.insert(D).second)
1595 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1596 }
1597
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001598 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001599 }
1600
John McCall6e247262009-10-10 05:48:19 +00001601 case LookupResult::AmbiguousTagHiding: {
1602 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001603
John McCall6e247262009-10-10 05:48:19 +00001604 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1605
1606 LookupResult::iterator DI, DE = Result.end();
1607 for (DI = Result.begin(); DI != DE; ++DI)
1608 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1609 TagDecls.insert(TD);
1610 Diag(TD->getLocation(), diag::note_hidden_tag);
1611 }
1612
1613 for (DI = Result.begin(); DI != DE; ++DI)
1614 if (!isa<TagDecl>(*DI))
1615 Diag((*DI)->getLocation(), diag::note_hiding_object);
1616
1617 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001618 LookupResult::Filter F = Result.makeFilter();
1619 while (F.hasNext()) {
1620 if (TagDecls.count(F.next()))
1621 F.erase();
1622 }
1623 F.done();
John McCall6e247262009-10-10 05:48:19 +00001624
1625 return true;
1626 }
1627
1628 case LookupResult::AmbiguousReference: {
1629 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001630
John McCall6e247262009-10-10 05:48:19 +00001631 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1632 for (; DI != DE; ++DI)
1633 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001634
John McCall6e247262009-10-10 05:48:19 +00001635 return true;
1636 }
1637 }
1638
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001639 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001640 return true;
1641}
Douglas Gregorfa047642009-02-04 00:32:51 +00001642
John McCallc7e04da2010-05-28 18:45:08 +00001643namespace {
1644 struct AssociatedLookup {
1645 AssociatedLookup(Sema &S,
1646 Sema::AssociatedNamespaceSet &Namespaces,
1647 Sema::AssociatedClassSet &Classes)
1648 : S(S), Namespaces(Namespaces), Classes(Classes) {
1649 }
1650
1651 Sema &S;
1652 Sema::AssociatedNamespaceSet &Namespaces;
1653 Sema::AssociatedClassSet &Classes;
1654 };
1655}
1656
Mike Stump1eb44332009-09-09 15:08:12 +00001657static void
John McCallc7e04da2010-05-28 18:45:08 +00001658addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCall6ff07852009-08-07 22:18:02 +00001659
Douglas Gregor54022952010-04-30 07:08:38 +00001660static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1661 DeclContext *Ctx) {
1662 // Add the associated namespace for this class.
1663
1664 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1665 // be a locally scoped record.
1666
Sebastian Redl410c4f22010-08-31 20:53:31 +00001667 // We skip out of inline namespaces. The innermost non-inline namespace
1668 // contains all names of all its nested inline namespaces anyway, so we can
1669 // replace the entire inline namespace tree with its root.
1670 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1671 Ctx->isInlineNamespace())
Douglas Gregor54022952010-04-30 07:08:38 +00001672 Ctx = Ctx->getParent();
1673
John McCall6ff07852009-08-07 22:18:02 +00001674 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001675 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001676}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001677
Mike Stump1eb44332009-09-09 15:08:12 +00001678// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001679// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001680static void
John McCallc7e04da2010-05-28 18:45:08 +00001681addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1682 const TemplateArgument &Arg) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001683 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001684 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001685 switch (Arg.getKind()) {
1686 case TemplateArgument::Null:
1687 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001688
Douglas Gregor69be8d62009-07-08 07:51:57 +00001689 case TemplateArgument::Type:
1690 // [...] the namespaces and classes associated with the types of the
1691 // template arguments provided for template type parameters (excluding
1692 // template template parameters)
John McCallc7e04da2010-05-28 18:45:08 +00001693 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor69be8d62009-07-08 07:51:57 +00001694 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001695
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001696 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001697 case TemplateArgument::TemplateExpansion: {
Mike Stump1eb44332009-09-09 15:08:12 +00001698 // [...] the namespaces in which any template template arguments are
1699 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001700 // template template arguments are defined.
Douglas Gregora7fc9012011-01-05 18:58:31 +00001701 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump1eb44332009-09-09 15:08:12 +00001702 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001703 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001704 DeclContext *Ctx = ClassTemplate->getDeclContext();
1705 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001706 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001707 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001708 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001709 }
1710 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001711 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001712
Douglas Gregor788cd062009-11-11 01:00:40 +00001713 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001714 case TemplateArgument::Integral:
1715 case TemplateArgument::Expression:
Mike Stump1eb44332009-09-09 15:08:12 +00001716 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001717 // associated namespaces. ]
1718 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001719
Douglas Gregor69be8d62009-07-08 07:51:57 +00001720 case TemplateArgument::Pack:
1721 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1722 PEnd = Arg.pack_end();
1723 P != PEnd; ++P)
John McCallc7e04da2010-05-28 18:45:08 +00001724 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001725 break;
1726 }
1727}
1728
Douglas Gregorfa047642009-02-04 00:32:51 +00001729// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001730// argument-dependent lookup with an argument of class type
1731// (C++ [basic.lookup.koenig]p2).
1732static void
John McCallc7e04da2010-05-28 18:45:08 +00001733addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1734 CXXRecordDecl *Class) {
1735
1736 // Just silently ignore anything whose name is __va_list_tag.
1737 if (Class->getDeclName() == Result.S.VAListTagName)
1738 return;
1739
Douglas Gregorfa047642009-02-04 00:32:51 +00001740 // C++ [basic.lookup.koenig]p2:
1741 // [...]
1742 // -- If T is a class type (including unions), its associated
1743 // classes are: the class itself; the class of which it is a
1744 // member, if any; and its direct and indirect base
1745 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001746 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001747
1748 // Add the class of which it is a member, if any.
1749 DeclContext *Ctx = Class->getDeclContext();
1750 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001751 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001752 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001753 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001754
Douglas Gregorfa047642009-02-04 00:32:51 +00001755 // Add the class itself. If we've already seen this class, we don't
1756 // need to visit base classes.
John McCallc7e04da2010-05-28 18:45:08 +00001757 if (!Result.Classes.insert(Class))
Douglas Gregorfa047642009-02-04 00:32:51 +00001758 return;
1759
Mike Stump1eb44332009-09-09 15:08:12 +00001760 // -- If T is a template-id, its associated namespaces and classes are
1761 // the namespace in which the template is defined; for member
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001762 // templates, the member template's class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001763 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001764 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001765 // namespaces in which any template template arguments are defined; and
1766 // the classes in which any member templates used as template template
1767 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001768 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001769 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001770 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1771 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1772 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001773 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001774 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001775 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001776
Douglas Gregor69be8d62009-07-08 07:51:57 +00001777 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1778 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallc7e04da2010-05-28 18:45:08 +00001779 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001780 }
Mike Stump1eb44332009-09-09 15:08:12 +00001781
John McCall86ff3082010-02-04 22:26:26 +00001782 // Only recurse into base classes for complete types.
1783 if (!Class->hasDefinition()) {
1784 // FIXME: we might need to instantiate templates here
1785 return;
1786 }
1787
Douglas Gregorfa047642009-02-04 00:32:51 +00001788 // Add direct and indirect base classes along with their associated
1789 // namespaces.
1790 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1791 Bases.push_back(Class);
1792 while (!Bases.empty()) {
1793 // Pop this class off the stack.
1794 Class = Bases.back();
1795 Bases.pop_back();
1796
1797 // Visit the base classes.
1798 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1799 BaseEnd = Class->bases_end();
1800 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001801 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001802 // In dependent contexts, we do ADL twice, and the first time around,
1803 // the base type might be a dependent TemplateSpecializationType, or a
1804 // TemplateTypeParmType. If that happens, simply ignore it.
1805 // FIXME: If we want to support export, we probably need to add the
1806 // namespace of the template in a TemplateSpecializationType, or even
1807 // the classes and namespaces of known non-dependent arguments.
1808 if (!BaseType)
1809 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001810 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001811 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001812 // Find the associated namespace for this base class.
1813 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallc7e04da2010-05-28 18:45:08 +00001814 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001815
1816 // Make sure we visit the bases of this base class.
1817 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1818 Bases.push_back(BaseDecl);
1819 }
1820 }
1821 }
1822}
1823
1824// \brief Add the associated classes and namespaces for
1825// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001826// (C++ [basic.lookup.koenig]p2).
1827static void
John McCallc7e04da2010-05-28 18:45:08 +00001828addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001829 // C++ [basic.lookup.koenig]p2:
1830 //
1831 // For each argument type T in the function call, there is a set
1832 // of zero or more associated namespaces and a set of zero or more
1833 // associated classes to be considered. The sets of namespaces and
1834 // classes is determined entirely by the types of the function
1835 // arguments (and the namespace of any template template
1836 // argument). Typedef names and using-declarations used to specify
1837 // the types do not contribute to this set. The sets of namespaces
1838 // and classes are determined in the following way:
Douglas Gregorfa047642009-02-04 00:32:51 +00001839
John McCallfa4edcf2010-05-28 06:08:54 +00001840 llvm::SmallVector<const Type *, 16> Queue;
1841 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1842
Douglas Gregorfa047642009-02-04 00:32:51 +00001843 while (true) {
John McCallfa4edcf2010-05-28 06:08:54 +00001844 switch (T->getTypeClass()) {
1845
1846#define TYPE(Class, Base)
1847#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1848#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1849#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1850#define ABSTRACT_TYPE(Class, Base)
1851#include "clang/AST/TypeNodes.def"
1852 // T is canonical. We can also ignore dependent types because
1853 // we don't need to do ADL at the definition point, but if we
1854 // wanted to implement template export (or if we find some other
1855 // use for associated classes and namespaces...) this would be
1856 // wrong.
Douglas Gregorfa047642009-02-04 00:32:51 +00001857 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00001858
John McCallfa4edcf2010-05-28 06:08:54 +00001859 // -- If T is a pointer to U or an array of U, its associated
1860 // namespaces and classes are those associated with U.
1861 case Type::Pointer:
1862 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1863 continue;
1864 case Type::ConstantArray:
1865 case Type::IncompleteArray:
1866 case Type::VariableArray:
1867 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1868 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001869
John McCallfa4edcf2010-05-28 06:08:54 +00001870 // -- If T is a fundamental type, its associated sets of
1871 // namespaces and classes are both empty.
1872 case Type::Builtin:
1873 break;
1874
1875 // -- If T is a class type (including unions), its associated
1876 // classes are: the class itself; the class of which it is a
1877 // member, if any; and its direct and indirect base
1878 // classes. Its associated namespaces are the namespaces in
1879 // which its associated classes are defined.
1880 case Type::Record: {
1881 CXXRecordDecl *Class
1882 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001883 addAssociatedClassesAndNamespaces(Result, Class);
John McCallfa4edcf2010-05-28 06:08:54 +00001884 break;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001885 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00001886
John McCallfa4edcf2010-05-28 06:08:54 +00001887 // -- If T is an enumeration type, its associated namespace is
1888 // the namespace in which it is defined. If it is class
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001889 // member, its associated class is the member's class; else
John McCallfa4edcf2010-05-28 06:08:54 +00001890 // it has no associated class.
1891 case Type::Enum: {
1892 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001893
John McCallfa4edcf2010-05-28 06:08:54 +00001894 DeclContext *Ctx = Enum->getDeclContext();
1895 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001896 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001897
John McCallfa4edcf2010-05-28 06:08:54 +00001898 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001899 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001900
John McCallfa4edcf2010-05-28 06:08:54 +00001901 break;
1902 }
1903
1904 // -- If T is a function type, its associated namespaces and
1905 // classes are those associated with the function parameter
1906 // types and those associated with the return type.
1907 case Type::FunctionProto: {
1908 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1909 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1910 ArgEnd = Proto->arg_type_end();
1911 Arg != ArgEnd; ++Arg)
1912 Queue.push_back(Arg->getTypePtr());
1913 // fallthrough
1914 }
1915 case Type::FunctionNoProto: {
1916 const FunctionType *FnType = cast<FunctionType>(T);
1917 T = FnType->getResultType().getTypePtr();
1918 continue;
1919 }
1920
1921 // -- If T is a pointer to a member function of a class X, its
1922 // associated namespaces and classes are those associated
1923 // with the function parameter types and return type,
1924 // together with those associated with X.
1925 //
1926 // -- If T is a pointer to a data member of class X, its
1927 // associated namespaces and classes are those associated
1928 // with the member type together with those associated with
1929 // X.
1930 case Type::MemberPointer: {
1931 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1932
1933 // Queue up the class type into which this points.
1934 Queue.push_back(MemberPtr->getClass());
1935
1936 // And directly continue with the pointee type.
1937 T = MemberPtr->getPointeeType().getTypePtr();
1938 continue;
1939 }
1940
1941 // As an extension, treat this like a normal pointer.
1942 case Type::BlockPointer:
1943 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1944 continue;
1945
1946 // References aren't covered by the standard, but that's such an
1947 // obvious defect that we cover them anyway.
1948 case Type::LValueReference:
1949 case Type::RValueReference:
1950 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1951 continue;
1952
1953 // These are fundamental types.
1954 case Type::Vector:
1955 case Type::ExtVector:
1956 case Type::Complex:
1957 break;
1958
1959 // These are ignored by ADL.
1960 case Type::ObjCObject:
1961 case Type::ObjCInterface:
1962 case Type::ObjCObjectPointer:
1963 break;
1964 }
1965
1966 if (Queue.empty()) break;
1967 T = Queue.back();
1968 Queue.pop_back();
Douglas Gregorfa047642009-02-04 00:32:51 +00001969 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001970}
1971
1972/// \brief Find the associated classes and namespaces for
1973/// argument-dependent lookup for a call with the given set of
1974/// arguments.
1975///
1976/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00001977/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00001978/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001979void
Douglas Gregorfa047642009-02-04 00:32:51 +00001980Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1981 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001982 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001983 AssociatedNamespaces.clear();
1984 AssociatedClasses.clear();
1985
John McCallc7e04da2010-05-28 18:45:08 +00001986 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
1987
Douglas Gregorfa047642009-02-04 00:32:51 +00001988 // C++ [basic.lookup.koenig]p2:
1989 // For each argument type T in the function call, there is a set
1990 // of zero or more associated namespaces and a set of zero or more
1991 // associated classes to be considered. The sets of namespaces and
1992 // classes is determined entirely by the types of the function
1993 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00001994 // argument).
Douglas Gregorfa047642009-02-04 00:32:51 +00001995 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1996 Expr *Arg = Args[ArgIdx];
1997
1998 if (Arg->getType() != Context.OverloadTy) {
John McCallc7e04da2010-05-28 18:45:08 +00001999 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002000 continue;
2001 }
2002
2003 // [...] In addition, if the argument is the name or address of a
2004 // set of overloaded functions and/or function templates, its
2005 // associated classes and namespaces are the union of those
2006 // associated with each of the members of the set: the namespace
2007 // in which the function or function template is defined and the
2008 // classes and namespaces associated with its (non-dependent)
2009 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00002010 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00002011 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCall2de56d12010-08-25 11:45:40 +00002012 if (unaryOp->getOpcode() == UO_AddrOf)
John McCallba135432009-11-21 08:51:07 +00002013 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002014
John McCallc7e04da2010-05-28 18:45:08 +00002015 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2016 if (!ULE) continue;
John McCallba135432009-11-21 08:51:07 +00002017
John McCallc7e04da2010-05-28 18:45:08 +00002018 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2019 I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00002020 // Look through any using declarations to find the underlying function.
2021 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002022
Chandler Carruthbd647292009-12-29 06:17:27 +00002023 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2024 if (!FDecl)
2025 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002026
2027 // Add the classes and namespaces associated with the parameter
2028 // types and return type of this function.
John McCallc7e04da2010-05-28 18:45:08 +00002029 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002030 }
2031 }
2032}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002033
2034/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2035/// an acceptable non-member overloaded operator for a call whose
2036/// arguments have types T1 (and, if non-empty, T2). This routine
2037/// implements the check in C++ [over.match.oper]p3b2 concerning
2038/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00002039static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002040IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2041 QualType T1, QualType T2,
2042 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00002043 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2044 return true;
2045
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002046 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2047 return true;
2048
John McCall183700f2009-09-21 23:43:11 +00002049 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002050 if (Proto->getNumArgs() < 1)
2051 return false;
2052
2053 if (T1->isEnumeralType()) {
2054 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002055 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002056 return true;
2057 }
2058
2059 if (Proto->getNumArgs() < 2)
2060 return false;
2061
2062 if (!T2.isNull() && T2->isEnumeralType()) {
2063 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002064 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002065 return true;
2066 }
2067
2068 return false;
2069}
2070
John McCall7d384dd2009-11-18 07:57:50 +00002071NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002072 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00002073 LookupNameKind NameKind,
2074 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002075 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00002076 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00002077 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00002078}
2079
Douglas Gregor6e378de2009-04-23 23:18:26 +00002080/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002081ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002082 SourceLocation IdLoc) {
2083 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2084 LookupObjCProtocolName);
Douglas Gregor6e378de2009-04-23 23:18:26 +00002085 return cast_or_null<ObjCProtocolDecl>(D);
2086}
2087
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002088void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00002089 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00002090 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002091 // C++ [over.match.oper]p3:
2092 // -- The set of non-member candidates is the result of the
2093 // unqualified lookup of operator@ in the context of the
2094 // expression according to the usual rules for name lookup in
2095 // unqualified function calls (3.4.2) except that all member
2096 // functions are ignored. However, if no operand has a class
2097 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00002098 // that have a first parameter of type T1 or "reference to
2099 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002100 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00002101 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002102 // when T2 is an enumeration type, are candidate functions.
2103 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00002104 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2105 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002106
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002107 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2108
John McCallf36e02d2009-10-09 21:13:30 +00002109 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002110 return;
2111
2112 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2113 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002114 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2115 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002116 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002117 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00002118 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002119 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00002120 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00002121 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00002122 // later?
2123 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002124 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00002125 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002126 }
2127}
2128
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002129/// \brief Look up the constructors for the given class.
2130DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Douglas Gregor22584312010-07-02 23:41:54 +00002131 // If the copy constructor has not yet been declared, do so now.
Douglas Gregor18274032010-07-03 00:47:00 +00002132 if (CanDeclareSpecialMemberFunction(Context, Class)) {
2133 if (!Class->hasDeclaredDefaultConstructor())
2134 DeclareImplicitDefaultConstructor(Class);
2135 if (!Class->hasDeclaredCopyConstructor())
2136 DeclareImplicitCopyConstructor(Class);
2137 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002138
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002139 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2140 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2141 return Class->lookup(Name);
2142}
2143
Douglas Gregordb89f282010-07-01 22:47:18 +00002144/// \brief Look for the destructor of the given class.
2145///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002146/// During semantic analysis, this routine should be used in lieu of
Douglas Gregordb89f282010-07-01 22:47:18 +00002147/// CXXRecordDecl::getDestructor().
2148///
2149/// \returns The destructor for this class.
2150CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Douglas Gregor4923aa22010-07-02 20:37:36 +00002151 // If the destructor has not yet been declared, do so now.
2152 if (CanDeclareSpecialMemberFunction(Context, Class) &&
2153 !Class->hasDeclaredDestructor())
2154 DeclareImplicitDestructor(Class);
2155
Douglas Gregordb89f282010-07-01 22:47:18 +00002156 return Class->getDestructor();
2157}
2158
John McCall7edb5fd2010-01-26 07:16:45 +00002159void ADLResult::insert(NamedDecl *New) {
2160 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2161
2162 // If we haven't yet seen a decl for this key, or the last decl
2163 // was exactly this one, we're done.
2164 if (Old == 0 || Old == New) {
2165 Old = New;
2166 return;
2167 }
2168
2169 // Otherwise, decide which is a more recent redeclaration.
2170 FunctionDecl *OldFD, *NewFD;
2171 if (isa<FunctionTemplateDecl>(New)) {
2172 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2173 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2174 } else {
2175 OldFD = cast<FunctionDecl>(Old);
2176 NewFD = cast<FunctionDecl>(New);
2177 }
2178
2179 FunctionDecl *Cursor = NewFD;
2180 while (true) {
2181 Cursor = Cursor->getPreviousDeclaration();
2182
2183 // If we got to the end without finding OldFD, OldFD is the newer
2184 // declaration; leave things as they are.
2185 if (!Cursor) return;
2186
2187 // If we do find OldFD, then NewFD is newer.
2188 if (Cursor == OldFD) break;
2189
2190 // Otherwise, keep looking.
2191 }
2192
2193 Old = New;
2194}
2195
Sebastian Redl644be852009-10-23 19:23:15 +00002196void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002197 Expr **Args, unsigned NumArgs,
John McCall7edb5fd2010-01-26 07:16:45 +00002198 ADLResult &Result) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002199 // Find all of the associated namespaces and classes based on the
2200 // arguments we have.
2201 AssociatedNamespaceSet AssociatedNamespaces;
2202 AssociatedClassSet AssociatedClasses;
Mike Stump1eb44332009-09-09 15:08:12 +00002203 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCall6ff07852009-08-07 22:18:02 +00002204 AssociatedNamespaces,
2205 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002206
Sebastian Redl644be852009-10-23 19:23:15 +00002207 QualType T1, T2;
2208 if (Operator) {
2209 T1 = Args[0]->getType();
2210 if (NumArgs >= 2)
2211 T2 = Args[1]->getType();
2212 }
2213
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002214 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002215 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2216 // and let Y be the lookup set produced by argument dependent
2217 // lookup (defined as follows). If X contains [...] then Y is
2218 // empty. Otherwise Y is the set of declarations found in the
2219 // namespaces associated with the argument types as described
2220 // below. The set of declarations found by the lookup of the name
2221 // is the union of X and Y.
2222 //
2223 // Here, we compute Y and add its members to the overloaded
2224 // candidate set.
2225 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002226 NSEnd = AssociatedNamespaces.end();
2227 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002228 // When considering an associated namespace, the lookup is the
2229 // same as the lookup performed when the associated namespace is
2230 // used as a qualifier (3.4.3.2) except that:
2231 //
2232 // -- Any using-directives in the associated namespace are
2233 // ignored.
2234 //
John McCall6ff07852009-08-07 22:18:02 +00002235 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002236 // associated classes are visible within their respective
2237 // namespaces even if they are not visible during an ordinary
2238 // lookup (11.4).
2239 DeclContext::lookup_iterator I, E;
John McCall3f9a8a62009-08-11 06:59:38 +00002240 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall6e266892010-01-26 03:27:55 +00002241 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00002242 // If the only declaration here is an ordinary friend, consider
2243 // it only if it was declared in an associated classes.
2244 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00002245 DeclContext *LexDC = D->getLexicalDeclContext();
2246 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2247 continue;
2248 }
Mike Stump1eb44332009-09-09 15:08:12 +00002249
John McCalla113e722010-01-26 06:04:06 +00002250 if (isa<UsingShadowDecl>(D))
2251 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00002252
John McCalla113e722010-01-26 06:04:06 +00002253 if (isa<FunctionDecl>(D)) {
2254 if (Operator &&
2255 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2256 T1, T2, Context))
2257 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00002258 } else if (!isa<FunctionTemplateDecl>(D))
2259 continue;
2260
2261 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00002262 }
2263 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002264}
Douglas Gregor546be3c2009-12-30 17:04:44 +00002265
2266//----------------------------------------------------------------------------
2267// Search for all visible declarations.
2268//----------------------------------------------------------------------------
2269VisibleDeclConsumer::~VisibleDeclConsumer() { }
2270
2271namespace {
2272
2273class ShadowContextRAII;
2274
2275class VisibleDeclsRecord {
2276public:
2277 /// \brief An entry in the shadow map, which is optimized to store a
2278 /// single declaration (the common case) but can also store a list
2279 /// of declarations.
2280 class ShadowMapEntry {
2281 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002282
Douglas Gregor546be3c2009-12-30 17:04:44 +00002283 /// \brief Contains either the solitary NamedDecl * or a vector
2284 /// of declarations.
2285 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2286
2287 public:
2288 ShadowMapEntry() : DeclOrVector() { }
2289
2290 void Add(NamedDecl *ND);
2291 void Destroy();
2292
2293 // Iteration.
2294 typedef NamedDecl **iterator;
2295 iterator begin();
2296 iterator end();
2297 };
2298
2299private:
2300 /// \brief A mapping from declaration names to the declarations that have
2301 /// this name within a particular scope.
2302 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2303
2304 /// \brief A list of shadow maps, which is used to model name hiding.
2305 std::list<ShadowMap> ShadowMaps;
2306
2307 /// \brief The declaration contexts we have already visited.
2308 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2309
2310 friend class ShadowContextRAII;
2311
2312public:
2313 /// \brief Determine whether we have already visited this context
2314 /// (and, if not, note that we are going to visit that context now).
2315 bool visitedContext(DeclContext *Ctx) {
2316 return !VisitedContexts.insert(Ctx);
2317 }
2318
Douglas Gregor8071e422010-08-15 06:18:01 +00002319 bool alreadyVisitedContext(DeclContext *Ctx) {
2320 return VisitedContexts.count(Ctx);
2321 }
2322
Douglas Gregor546be3c2009-12-30 17:04:44 +00002323 /// \brief Determine whether the given declaration is hidden in the
2324 /// current scope.
2325 ///
2326 /// \returns the declaration that hides the given declaration, or
2327 /// NULL if no such declaration exists.
2328 NamedDecl *checkHidden(NamedDecl *ND);
2329
2330 /// \brief Add a declaration to the current shadow map.
2331 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2332};
2333
2334/// \brief RAII object that records when we've entered a shadow context.
2335class ShadowContextRAII {
2336 VisibleDeclsRecord &Visible;
2337
2338 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2339
2340public:
2341 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2342 Visible.ShadowMaps.push_back(ShadowMap());
2343 }
2344
2345 ~ShadowContextRAII() {
2346 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2347 EEnd = Visible.ShadowMaps.back().end();
2348 E != EEnd;
2349 ++E)
2350 E->second.Destroy();
2351
2352 Visible.ShadowMaps.pop_back();
2353 }
2354};
2355
2356} // end anonymous namespace
2357
2358void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2359 if (DeclOrVector.isNull()) {
2360 // 0 - > 1 elements: just set the single element information.
2361 DeclOrVector = ND;
2362 return;
2363 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002364
Douglas Gregor546be3c2009-12-30 17:04:44 +00002365 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2366 // 1 -> 2 elements: create the vector of results and push in the
2367 // existing declaration.
2368 DeclVector *Vec = new DeclVector;
2369 Vec->push_back(PrevND);
2370 DeclOrVector = Vec;
2371 }
2372
2373 // Add the new element to the end of the vector.
2374 DeclOrVector.get<DeclVector*>()->push_back(ND);
2375}
2376
2377void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2378 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2379 delete Vec;
2380 DeclOrVector = ((NamedDecl *)0);
2381 }
2382}
2383
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002384VisibleDeclsRecord::ShadowMapEntry::iterator
Douglas Gregor546be3c2009-12-30 17:04:44 +00002385VisibleDeclsRecord::ShadowMapEntry::begin() {
2386 if (DeclOrVector.isNull())
2387 return 0;
2388
2389 if (DeclOrVector.dyn_cast<NamedDecl *>())
2390 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
2391
2392 return DeclOrVector.get<DeclVector *>()->begin();
2393}
2394
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002395VisibleDeclsRecord::ShadowMapEntry::iterator
Douglas Gregor546be3c2009-12-30 17:04:44 +00002396VisibleDeclsRecord::ShadowMapEntry::end() {
2397 if (DeclOrVector.isNull())
2398 return 0;
2399
2400 if (DeclOrVector.dyn_cast<NamedDecl *>())
2401 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2402
2403 return DeclOrVector.get<DeclVector *>()->end();
2404}
2405
2406NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002407 // Look through using declarations.
2408 ND = ND->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002409
Douglas Gregor546be3c2009-12-30 17:04:44 +00002410 unsigned IDNS = ND->getIdentifierNamespace();
2411 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2412 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2413 SM != SMEnd; ++SM) {
2414 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2415 if (Pos == SM->end())
2416 continue;
2417
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002418 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00002419 IEnd = Pos->second.end();
2420 I != IEnd; ++I) {
2421 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002422 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002423 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor546be3c2009-12-30 17:04:44 +00002424 Decl::IDNS_ObjCProtocol)))
2425 continue;
2426
2427 // Protocols are in distinct namespaces from everything else.
2428 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2429 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2430 (*I)->getIdentifierNamespace() != IDNS)
2431 continue;
2432
Douglas Gregor0cc84042010-01-14 15:47:35 +00002433 // Functions and function templates in the same scope overload
2434 // rather than hide. FIXME: Look for hiding based on function
2435 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002436 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002437 ND->isFunctionOrFunctionTemplate() &&
2438 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002439 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002440
Douglas Gregor546be3c2009-12-30 17:04:44 +00002441 // We've found a declaration that hides this one.
2442 return *I;
2443 }
2444 }
2445
2446 return 0;
2447}
2448
2449static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2450 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002451 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002452 VisibleDeclConsumer &Consumer,
2453 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00002454 if (!Ctx)
2455 return;
2456
Douglas Gregor546be3c2009-12-30 17:04:44 +00002457 // Make sure we don't visit the same context twice.
2458 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2459 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002460
Douglas Gregor4923aa22010-07-02 20:37:36 +00002461 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2462 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2463
Douglas Gregor546be3c2009-12-30 17:04:44 +00002464 // Enumerate all of the results in this context.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002465 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002466 CurCtx = CurCtx->getNextContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002467 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00002468 DEnd = CurCtx->decls_end();
2469 D != DEnd; ++D) {
Douglas Gregor70c23352010-12-09 21:44:02 +00002470 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002471 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002472 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002473 Visited.add(ND);
2474 }
Douglas Gregor70c23352010-12-09 21:44:02 +00002475 } else if (ObjCForwardProtocolDecl *ForwardProto
2476 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
2477 for (ObjCForwardProtocolDecl::protocol_iterator
2478 P = ForwardProto->protocol_begin(),
2479 PEnd = ForwardProto->protocol_end();
2480 P != PEnd;
2481 ++P) {
2482 if (Result.isAcceptableDecl(*P)) {
2483 Consumer.FoundDecl(*P, Visited.checkHidden(*P), InBaseClass);
2484 Visited.add(*P);
2485 }
2486 }
2487 }
Sebastian Redl410c4f22010-08-31 20:53:31 +00002488 // Visit transparent contexts and inline namespaces inside this context.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002489 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
Sebastian Redl410c4f22010-08-31 20:53:31 +00002490 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Douglas Gregor0cc84042010-01-14 15:47:35 +00002491 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002492 Consumer, Visited);
2493 }
2494 }
2495 }
2496
2497 // Traverse using directives for qualified name lookup.
2498 if (QualifiedNameLookup) {
2499 ShadowContextRAII Shadow(Visited);
2500 DeclContext::udir_iterator I, E;
2501 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002502 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002503 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002504 }
2505 }
2506
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002507 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002508 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00002509 if (!Record->hasDefinition())
2510 return;
2511
Douglas Gregor546be3c2009-12-30 17:04:44 +00002512 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2513 BEnd = Record->bases_end();
2514 B != BEnd; ++B) {
2515 QualType BaseType = B->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002516
Douglas Gregor546be3c2009-12-30 17:04:44 +00002517 // Don't look into dependent bases, because name lookup can't look
2518 // there anyway.
2519 if (BaseType->isDependentType())
2520 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002521
Douglas Gregor546be3c2009-12-30 17:04:44 +00002522 const RecordType *Record = BaseType->getAs<RecordType>();
2523 if (!Record)
2524 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002525
Douglas Gregor546be3c2009-12-30 17:04:44 +00002526 // FIXME: It would be nice to be able to determine whether referencing
2527 // a particular member would be ambiguous. For example, given
2528 //
2529 // struct A { int member; };
2530 // struct B { int member; };
2531 // struct C : A, B { };
2532 //
2533 // void f(C *c) { c->### }
2534 //
2535 // accessing 'member' would result in an ambiguity. However, we
2536 // could be smart enough to qualify the member with the base
2537 // class, e.g.,
2538 //
2539 // c->B::member
2540 //
2541 // or
2542 //
2543 // c->A::member
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002544
Douglas Gregor546be3c2009-12-30 17:04:44 +00002545 // Find results in this base class (and its bases).
2546 ShadowContextRAII Shadow(Visited);
2547 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002548 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002549 }
2550 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002551
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002552 // Traverse the contexts of Objective-C classes.
2553 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2554 // Traverse categories.
2555 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2556 Category; Category = Category->getNextClassCategory()) {
2557 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002558 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002559 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002560 }
2561
2562 // Traverse protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00002563 for (ObjCInterfaceDecl::all_protocol_iterator
2564 I = IFace->all_referenced_protocol_begin(),
2565 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002566 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002567 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002568 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002569 }
2570
2571 // Traverse the superclass.
2572 if (IFace->getSuperClass()) {
2573 ShadowContextRAII Shadow(Visited);
2574 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002575 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002576 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002577
Douglas Gregorc220a182010-04-19 18:02:19 +00002578 // If there is an implementation, traverse it. We do this to find
2579 // synthesized ivars.
2580 if (IFace->getImplementation()) {
2581 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002582 LookupVisibleDecls(IFace->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00002583 QualifiedNameLookup, true, Consumer, Visited);
2584 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002585 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2586 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2587 E = Protocol->protocol_end(); I != E; ++I) {
2588 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002589 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002590 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002591 }
2592 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2593 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2594 E = Category->protocol_end(); I != E; ++I) {
2595 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002596 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002597 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002598 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002599
Douglas Gregorc220a182010-04-19 18:02:19 +00002600 // If there is an implementation, traverse it.
2601 if (Category->getImplementation()) {
2602 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002603 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00002604 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002605 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002606 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002607}
2608
2609static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2610 UnqualUsingDirectiveSet &UDirs,
2611 VisibleDeclConsumer &Consumer,
2612 VisibleDeclsRecord &Visited) {
2613 if (!S)
2614 return;
2615
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002616 if (!S->getEntity() ||
2617 (!S->getParent() &&
Douglas Gregor8071e422010-08-15 06:18:01 +00002618 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor539c5c32010-01-07 00:31:29 +00002619 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2620 // Walk through the declarations in this Scope.
2621 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2622 D != DEnd; ++D) {
John McCalld226f652010-08-21 09:40:31 +00002623 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor539c5c32010-01-07 00:31:29 +00002624 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002625 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002626 Visited.add(ND);
2627 }
2628 }
2629 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002630
Douglas Gregor711be1e2010-03-15 14:33:29 +00002631 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00002632 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00002633 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002634 // Look into this scope's declaration context, along with any of its
2635 // parent lookup contexts (e.g., enclosing classes), up to the point
2636 // where we hit the context stored in the next outer scope.
2637 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00002638 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002639
Douglas Gregordbdf5e72010-03-15 15:26:48 +00002640 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002641 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002642 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2643 if (Method->isInstanceMethod()) {
2644 // For instance methods, look for ivars in the method's interface.
2645 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2646 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregorca45da02010-11-02 20:36:02 +00002647 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002648 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Douglas Gregor62021192010-02-04 23:42:48 +00002649 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002650
Douglas Gregorca45da02010-11-02 20:36:02 +00002651 // Look for properties from which we can synthesize ivars, if
2652 // permitted.
2653 if (Result.getSema().getLangOptions().ObjCNonFragileABI2 &&
2654 IFace->getImplementation() &&
2655 Result.getLookupKind() == Sema::LookupOrdinaryName) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002656 for (ObjCInterfaceDecl::prop_iterator
Douglas Gregorca45da02010-11-02 20:36:02 +00002657 P = IFace->prop_begin(),
2658 PEnd = IFace->prop_end();
2659 P != PEnd; ++P) {
2660 if (Result.getSema().canSynthesizeProvisionalIvar(*P) &&
2661 !IFace->lookupInstanceVariable((*P)->getIdentifier())) {
2662 Consumer.FoundDecl(*P, Visited.checkHidden(*P), false);
2663 Visited.add(*P);
2664 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002665 }
2666 }
Douglas Gregorca45da02010-11-02 20:36:02 +00002667 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002668 }
2669
2670 // We've already performed all of the name lookup that we need
2671 // to for Objective-C methods; the next context will be the
2672 // outer scope.
2673 break;
2674 }
2675
Douglas Gregor546be3c2009-12-30 17:04:44 +00002676 if (Ctx->isFunctionOrMethod())
2677 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002678
2679 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002680 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002681 }
2682 } else if (!S->getParent()) {
2683 // Look into the translation unit scope. We walk through the translation
2684 // unit's declaration context, because the Scope itself won't have all of
2685 // the declarations if we loaded a precompiled header.
2686 // FIXME: We would like the translation unit's Scope object to point to the
2687 // translation unit, so we don't need this special "if" branch. However,
2688 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002689 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002690 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00002691 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002692 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002693 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002694 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002695 }
2696
Douglas Gregor546be3c2009-12-30 17:04:44 +00002697 if (Entity) {
2698 // Lookup visible declarations in any namespaces found by using
2699 // directives.
2700 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2701 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2702 for (; UI != UEnd; ++UI)
2703 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002704 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002705 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002706 }
2707
2708 // Lookup names in the parent scope.
2709 ShadowContextRAII Shadow(Visited);
2710 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2711}
2712
2713void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00002714 VisibleDeclConsumer &Consumer,
2715 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002716 // Determine the set of using directives available during
2717 // unqualified name lookup.
2718 Scope *Initial = S;
2719 UnqualUsingDirectiveSet UDirs;
2720 if (getLangOptions().CPlusPlus) {
2721 // Find the first namespace or translation-unit scope.
2722 while (S && !isNamespaceOrTranslationUnitScope(S))
2723 S = S->getParent();
2724
2725 UDirs.visitScopeChain(Initial, S);
2726 }
2727 UDirs.done();
2728
2729 // Look for visible declarations.
2730 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2731 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00002732 if (!IncludeGlobalScope)
2733 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00002734 ShadowContextRAII Shadow(Visited);
2735 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2736}
2737
2738void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00002739 VisibleDeclConsumer &Consumer,
2740 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002741 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2742 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00002743 if (!IncludeGlobalScope)
2744 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00002745 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002746 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002747 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002748}
2749
2750//----------------------------------------------------------------------------
2751// Typo correction
2752//----------------------------------------------------------------------------
2753
2754namespace {
2755class TypoCorrectionConsumer : public VisibleDeclConsumer {
2756 /// \brief The name written that is a typo in the source.
2757 llvm::StringRef Typo;
2758
2759 /// \brief The results found that have the smallest edit distance
2760 /// found (so far) with the typo name.
Douglas Gregore24b5752010-10-14 20:34:08 +00002761 ///
2762 /// The boolean value indicates whether there is a keyword with this name.
2763 llvm::StringMap<bool, llvm::BumpPtrAllocator> BestResults;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002764
2765 /// \brief The best edit distance found so far.
2766 unsigned BestEditDistance;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002767
Douglas Gregor546be3c2009-12-30 17:04:44 +00002768public:
2769 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002770 : Typo(Typo->getName()),
Douglas Gregore24b5752010-10-14 20:34:08 +00002771 BestEditDistance((std::numeric_limits<unsigned>::max)()) { }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002772
Douglas Gregor0cc84042010-01-14 15:47:35 +00002773 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregor95f42922010-10-14 22:11:03 +00002774 void FoundName(llvm::StringRef Name);
Douglas Gregoraaf87162010-04-14 20:04:41 +00002775 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002776
Douglas Gregore24b5752010-10-14 20:34:08 +00002777 typedef llvm::StringMap<bool, llvm::BumpPtrAllocator>::iterator iterator;
2778 iterator begin() { return BestResults.begin(); }
2779 iterator end() { return BestResults.end(); }
2780 void erase(iterator I) { BestResults.erase(I); }
2781 unsigned size() const { return BestResults.size(); }
2782 bool empty() const { return BestResults.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002783
Douglas Gregor7b824e82010-10-15 13:35:25 +00002784 bool &operator[](llvm::StringRef Name) {
2785 return BestResults[Name];
2786 }
2787
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002788 unsigned getBestEditDistance() const { return BestEditDistance; }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002789};
2790
2791}
2792
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002793void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002794 bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002795 // Don't consider hidden names for typo correction.
2796 if (Hiding)
2797 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002798
Douglas Gregor546be3c2009-12-30 17:04:44 +00002799 // Only consider entities with identifiers for names, ignoring
2800 // special names (constructors, overloaded operators, selectors,
2801 // etc.).
2802 IdentifierInfo *Name = ND->getIdentifier();
2803 if (!Name)
2804 return;
2805
Douglas Gregor95f42922010-10-14 22:11:03 +00002806 FoundName(Name->getName());
2807}
2808
2809void TypoCorrectionConsumer::FoundName(llvm::StringRef Name) {
Douglas Gregora1194772010-10-19 22:14:33 +00002810 using namespace std;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002811
Douglas Gregor362a8f22010-10-19 19:39:10 +00002812 // Use a simple length-based heuristic to determine the minimum possible
2813 // edit distance. If the minimum isn't good enough, bail out early.
2814 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
2815 if (MinED > BestEditDistance || (MinED && Typo.size() / MinED < 3))
2816 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002817
Douglas Gregora1194772010-10-19 22:14:33 +00002818 // Compute an upper bound on the allowable edit distance, so that the
2819 // edit-distance algorithm can short-circuit.
2820 unsigned UpperBound = min(unsigned((Typo.size() + 2) / 3), BestEditDistance);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002821
Douglas Gregor546be3c2009-12-30 17:04:44 +00002822 // Compute the edit distance between the typo and the name of this
2823 // entity. If this edit distance is not worse than the best edit
2824 // distance we've seen so far, add it to the list of results.
Douglas Gregora1194772010-10-19 22:14:33 +00002825 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
Douglas Gregor95f42922010-10-14 22:11:03 +00002826 if (ED == 0)
2827 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002828
Douglas Gregore24b5752010-10-14 20:34:08 +00002829 if (ED < BestEditDistance) {
2830 // This result is better than any we've seen before; clear out
2831 // the previous results.
2832 BestResults.clear();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002833 BestEditDistance = ED;
Douglas Gregore24b5752010-10-14 20:34:08 +00002834 } else if (ED > BestEditDistance) {
2835 // This result is worse than the best results we've seen so far;
2836 // ignore it.
2837 return;
2838 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002839
Douglas Gregore24b5752010-10-14 20:34:08 +00002840 // Add this name to the list of results. By not assigning a value, we
2841 // keep the current value if we've seen this name before (either as a
2842 // keyword or as a declaration), or get the default value (not a keyword)
2843 // if we haven't seen it before.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002844 (void)BestResults[Name];
Douglas Gregor546be3c2009-12-30 17:04:44 +00002845}
2846
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002847void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
Douglas Gregoraaf87162010-04-14 20:04:41 +00002848 llvm::StringRef Keyword) {
2849 // Compute the edit distance between the typo and this keyword.
2850 // If this edit distance is not worse than the best edit
2851 // distance we've seen so far, add it to the list of results.
2852 unsigned ED = Typo.edit_distance(Keyword);
Douglas Gregore24b5752010-10-14 20:34:08 +00002853 if (ED < BestEditDistance) {
2854 BestResults.clear();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002855 BestEditDistance = ED;
Douglas Gregore24b5752010-10-14 20:34:08 +00002856 } else if (ED > BestEditDistance) {
2857 // This result is worse than the best results we've seen so far;
2858 // ignore it.
2859 return;
2860 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002861
Douglas Gregore24b5752010-10-14 20:34:08 +00002862 BestResults[Keyword] = true;
Douglas Gregoraaf87162010-04-14 20:04:41 +00002863}
2864
Douglas Gregor9a632ea2010-10-20 03:06:34 +00002865/// \brief Perform name lookup for a possible result for typo correction.
2866static void LookupPotentialTypoResult(Sema &SemaRef,
2867 LookupResult &Res,
2868 IdentifierInfo *Name,
2869 Scope *S, CXXScopeSpec *SS,
2870 DeclContext *MemberContext,
2871 bool EnteringContext,
2872 Sema::CorrectTypoContext CTC) {
2873 Res.suppressDiagnostics();
2874 Res.clear();
2875 Res.setLookupName(Name);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002876 if (MemberContext) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00002877 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
2878 if (CTC == Sema::CTC_ObjCIvarLookup) {
2879 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
2880 Res.addDecl(Ivar);
2881 Res.resolveKind();
2882 return;
2883 }
2884 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002885
Douglas Gregor9a632ea2010-10-20 03:06:34 +00002886 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
2887 Res.addDecl(Prop);
2888 Res.resolveKind();
2889 return;
2890 }
2891 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002892
Douglas Gregor9a632ea2010-10-20 03:06:34 +00002893 SemaRef.LookupQualifiedName(Res, MemberContext);
2894 return;
2895 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002896
2897 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00002898 EnteringContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002899
Douglas Gregor9a632ea2010-10-20 03:06:34 +00002900 // Fake ivar lookup; this should really be part of
2901 // LookupParsedName.
2902 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2903 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002904 (Res.empty() ||
Douglas Gregor9a632ea2010-10-20 03:06:34 +00002905 (Res.isSingleResult() &&
2906 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002907 if (ObjCIvarDecl *IV
Douglas Gregor9a632ea2010-10-20 03:06:34 +00002908 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
2909 Res.addDecl(IV);
2910 Res.resolveKind();
2911 }
2912 }
2913 }
2914}
2915
Douglas Gregor546be3c2009-12-30 17:04:44 +00002916/// \brief Try to "correct" a typo in the source code by finding
2917/// visible declarations whose names are similar to the name that was
2918/// present in the source code.
2919///
2920/// \param Res the \c LookupResult structure that contains the name
2921/// that was present in the source code along with the name-lookup
2922/// criteria used to search for the name. On success, this structure
2923/// will contain the results of name lookup.
2924///
2925/// \param S the scope in which name lookup occurs.
2926///
2927/// \param SS the nested-name-specifier that precedes the name we're
2928/// looking for, if present.
2929///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002930/// \param MemberContext if non-NULL, the context in which to look for
2931/// a member access expression.
2932///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002933/// \param EnteringContext whether we're entering the context described by
Douglas Gregorbb092ba2009-12-31 05:20:13 +00002934/// the nested-name-specifier SS.
2935///
Douglas Gregoraaf87162010-04-14 20:04:41 +00002936/// \param CTC The context in which typo correction occurs, which impacts the
2937/// set of keywords permitted.
2938///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002939/// \param OPT when non-NULL, the search for visible declarations will
2940/// also walk the protocols in the qualified interfaces of \p OPT.
2941///
Douglas Gregor931f98a2010-04-14 17:09:22 +00002942/// \returns the corrected name if the typo was corrected, otherwise returns an
2943/// empty \c DeclarationName. When a typo was corrected, the result structure
2944/// may contain the results of name lookup for the correct name or it may be
2945/// empty.
2946DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002947 DeclContext *MemberContext,
Douglas Gregoraaf87162010-04-14 20:04:41 +00002948 bool EnteringContext,
2949 CorrectTypoContext CTC,
2950 const ObjCObjectPointerType *OPT) {
Douglas Gregora0068fc2010-07-09 17:35:33 +00002951 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002952 return DeclarationName();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002953
Douglas Gregor546be3c2009-12-30 17:04:44 +00002954 // We only attempt to correct typos for identifiers.
2955 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2956 if (!Typo)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002957 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002958
2959 // If the scope specifier itself was invalid, don't try to correct
2960 // typos.
2961 if (SS && SS->isInvalid())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002962 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002963
2964 // Never try to correct typos during template deduction or
2965 // instantiation.
2966 if (!ActiveTemplateInstantiations.empty())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002967 return DeclarationName();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002968
Douglas Gregor546be3c2009-12-30 17:04:44 +00002969 TypoCorrectionConsumer Consumer(Typo);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002970
Douglas Gregoraaf87162010-04-14 20:04:41 +00002971 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00002972 bool IsUnqualifiedLookup = false;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002973 if (MemberContext) {
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002974 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002975
2976 // Look in qualified interfaces.
2977 if (OPT) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002978 for (ObjCObjectPointerType::qual_iterator
2979 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002980 I != E; ++I)
2981 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2982 }
2983 } else if (SS && SS->isSet()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002984 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2985 if (!DC)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002986 return DeclarationName();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002987
Douglas Gregor3eedbb02010-10-20 01:32:02 +00002988 // Provide a stop gap for files that are just seriously broken. Trying
2989 // to correct all typos can turn into a HUGE performance penalty, causing
2990 // some files to take minutes to get rejected by the parser.
2991 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
2992 return DeclarationName();
2993 ++TyposCorrected;
2994
Douglas Gregor546be3c2009-12-30 17:04:44 +00002995 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2996 } else {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00002997 IsUnqualifiedLookup = true;
2998 UnqualifiedTyposCorrectedMap::iterator Cached
2999 = UnqualifiedTyposCorrected.find(Typo);
3000 if (Cached == UnqualifiedTyposCorrected.end()) {
3001 // Provide a stop gap for files that are just seriously broken. Trying
3002 // to correct all typos can turn into a HUGE performance penalty, causing
3003 // some files to take minutes to get rejected by the parser.
3004 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
3005 return DeclarationName();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003006
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003007 // For unqualified lookup, look through all of the names that we have
3008 // seen in this translation unit.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003009 for (IdentifierTable::iterator I = Context.Idents.begin(),
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003010 IEnd = Context.Idents.end();
3011 I != IEnd; ++I)
3012 Consumer.FoundName(I->getKey());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003013
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003014 // Walk through identifiers in external identifier sources.
3015 if (IdentifierInfoLookup *External
Douglas Gregor95f42922010-10-14 22:11:03 +00003016 = Context.Idents.getExternalIdentifierLookup()) {
Ted Kremenek7a054b12010-11-07 06:11:33 +00003017 llvm::OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003018 do {
3019 llvm::StringRef Name = Iter->Next();
3020 if (Name.empty())
3021 break;
Douglas Gregor95f42922010-10-14 22:11:03 +00003022
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003023 Consumer.FoundName(Name);
3024 } while (true);
3025 }
3026 } else {
3027 // Use the cached value, unless it's a keyword. In the keyword case, we'll
3028 // end up adding the keyword below.
3029 if (Cached->second.first.empty())
3030 return DeclarationName();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003031
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003032 if (!Cached->second.second)
3033 Consumer.FoundName(Cached->second.first);
Douglas Gregor95f42922010-10-14 22:11:03 +00003034 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003035 }
3036
Douglas Gregoraaf87162010-04-14 20:04:41 +00003037 // Add context-dependent keywords.
3038 bool WantTypeSpecifiers = false;
3039 bool WantExpressionKeywords = false;
3040 bool WantCXXNamedCasts = false;
3041 bool WantRemainingKeywords = false;
3042 switch (CTC) {
3043 case CTC_Unknown:
3044 WantTypeSpecifiers = true;
3045 WantExpressionKeywords = true;
3046 WantCXXNamedCasts = true;
3047 WantRemainingKeywords = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003048
Douglas Gregor91f7ac72010-05-18 16:14:23 +00003049 if (ObjCMethodDecl *Method = getCurMethodDecl())
3050 if (Method->getClassInterface() &&
3051 Method->getClassInterface()->getSuperClass())
3052 Consumer.addKeywordResult(Context, "super");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003053
Douglas Gregoraaf87162010-04-14 20:04:41 +00003054 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003055
Douglas Gregoraaf87162010-04-14 20:04:41 +00003056 case CTC_NoKeywords:
3057 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003058
Douglas Gregoraaf87162010-04-14 20:04:41 +00003059 case CTC_Type:
3060 WantTypeSpecifiers = true;
3061 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003062
Douglas Gregoraaf87162010-04-14 20:04:41 +00003063 case CTC_ObjCMessageReceiver:
3064 Consumer.addKeywordResult(Context, "super");
3065 // Fall through to handle message receivers like expressions.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003066
Douglas Gregoraaf87162010-04-14 20:04:41 +00003067 case CTC_Expression:
3068 if (getLangOptions().CPlusPlus)
3069 WantTypeSpecifiers = true;
3070 WantExpressionKeywords = true;
3071 // Fall through to get C++ named casts.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003072
Douglas Gregoraaf87162010-04-14 20:04:41 +00003073 case CTC_CXXCasts:
3074 WantCXXNamedCasts = true;
3075 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003076
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003077 case CTC_ObjCPropertyLookup:
3078 // FIXME: Add "isa"?
3079 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003080
Douglas Gregoraaf87162010-04-14 20:04:41 +00003081 case CTC_MemberLookup:
3082 if (getLangOptions().CPlusPlus)
3083 Consumer.addKeywordResult(Context, "template");
3084 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003085
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003086 case CTC_ObjCIvarLookup:
3087 break;
Douglas Gregoraaf87162010-04-14 20:04:41 +00003088 }
3089
3090 if (WantTypeSpecifiers) {
3091 // Add type-specifier keywords to the set of results.
3092 const char *CTypeSpecs[] = {
3093 "char", "const", "double", "enum", "float", "int", "long", "short",
3094 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
3095 "_Complex", "_Imaginary",
3096 // storage-specifiers as well
3097 "extern", "inline", "static", "typedef"
3098 };
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003099
Douglas Gregoraaf87162010-04-14 20:04:41 +00003100 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3101 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3102 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003103
Douglas Gregoraaf87162010-04-14 20:04:41 +00003104 if (getLangOptions().C99)
3105 Consumer.addKeywordResult(Context, "restrict");
3106 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
3107 Consumer.addKeywordResult(Context, "bool");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003108
Douglas Gregoraaf87162010-04-14 20:04:41 +00003109 if (getLangOptions().CPlusPlus) {
3110 Consumer.addKeywordResult(Context, "class");
3111 Consumer.addKeywordResult(Context, "typename");
3112 Consumer.addKeywordResult(Context, "wchar_t");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003113
Douglas Gregoraaf87162010-04-14 20:04:41 +00003114 if (getLangOptions().CPlusPlus0x) {
3115 Consumer.addKeywordResult(Context, "char16_t");
3116 Consumer.addKeywordResult(Context, "char32_t");
3117 Consumer.addKeywordResult(Context, "constexpr");
3118 Consumer.addKeywordResult(Context, "decltype");
3119 Consumer.addKeywordResult(Context, "thread_local");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003120 }
Douglas Gregoraaf87162010-04-14 20:04:41 +00003121 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003122
Douglas Gregoraaf87162010-04-14 20:04:41 +00003123 if (getLangOptions().GNUMode)
3124 Consumer.addKeywordResult(Context, "typeof");
3125 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003126
Douglas Gregord0785ea2010-05-18 16:30:22 +00003127 if (WantCXXNamedCasts && getLangOptions().CPlusPlus) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00003128 Consumer.addKeywordResult(Context, "const_cast");
3129 Consumer.addKeywordResult(Context, "dynamic_cast");
3130 Consumer.addKeywordResult(Context, "reinterpret_cast");
3131 Consumer.addKeywordResult(Context, "static_cast");
3132 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003133
Douglas Gregoraaf87162010-04-14 20:04:41 +00003134 if (WantExpressionKeywords) {
3135 Consumer.addKeywordResult(Context, "sizeof");
3136 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
3137 Consumer.addKeywordResult(Context, "false");
3138 Consumer.addKeywordResult(Context, "true");
3139 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003140
Douglas Gregoraaf87162010-04-14 20:04:41 +00003141 if (getLangOptions().CPlusPlus) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003142 const char *CXXExprs[] = {
3143 "delete", "new", "operator", "throw", "typeid"
Douglas Gregoraaf87162010-04-14 20:04:41 +00003144 };
3145 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3146 for (unsigned I = 0; I != NumCXXExprs; ++I)
3147 Consumer.addKeywordResult(Context, CXXExprs[I]);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003148
Douglas Gregoraaf87162010-04-14 20:04:41 +00003149 if (isa<CXXMethodDecl>(CurContext) &&
3150 cast<CXXMethodDecl>(CurContext)->isInstance())
3151 Consumer.addKeywordResult(Context, "this");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003152
Douglas Gregoraaf87162010-04-14 20:04:41 +00003153 if (getLangOptions().CPlusPlus0x) {
3154 Consumer.addKeywordResult(Context, "alignof");
3155 Consumer.addKeywordResult(Context, "nullptr");
3156 }
3157 }
3158 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003159
Douglas Gregoraaf87162010-04-14 20:04:41 +00003160 if (WantRemainingKeywords) {
3161 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
3162 // Statements.
3163 const char *CStmts[] = {
3164 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3165 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3166 for (unsigned I = 0; I != NumCStmts; ++I)
3167 Consumer.addKeywordResult(Context, CStmts[I]);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003168
Douglas Gregoraaf87162010-04-14 20:04:41 +00003169 if (getLangOptions().CPlusPlus) {
3170 Consumer.addKeywordResult(Context, "catch");
3171 Consumer.addKeywordResult(Context, "try");
3172 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003173
Douglas Gregoraaf87162010-04-14 20:04:41 +00003174 if (S && S->getBreakParent())
3175 Consumer.addKeywordResult(Context, "break");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003176
Douglas Gregoraaf87162010-04-14 20:04:41 +00003177 if (S && S->getContinueParent())
3178 Consumer.addKeywordResult(Context, "continue");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003179
John McCall781472f2010-08-25 08:40:02 +00003180 if (!getCurFunction()->SwitchStack.empty()) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00003181 Consumer.addKeywordResult(Context, "case");
3182 Consumer.addKeywordResult(Context, "default");
3183 }
3184 } else {
3185 if (getLangOptions().CPlusPlus) {
3186 Consumer.addKeywordResult(Context, "namespace");
3187 Consumer.addKeywordResult(Context, "template");
3188 }
3189
3190 if (S && S->isClassScope()) {
3191 Consumer.addKeywordResult(Context, "explicit");
3192 Consumer.addKeywordResult(Context, "friend");
3193 Consumer.addKeywordResult(Context, "mutable");
3194 Consumer.addKeywordResult(Context, "private");
3195 Consumer.addKeywordResult(Context, "protected");
3196 Consumer.addKeywordResult(Context, "public");
3197 Consumer.addKeywordResult(Context, "virtual");
3198 }
3199 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003200
Douglas Gregoraaf87162010-04-14 20:04:41 +00003201 if (getLangOptions().CPlusPlus) {
3202 Consumer.addKeywordResult(Context, "using");
3203
3204 if (getLangOptions().CPlusPlus0x)
3205 Consumer.addKeywordResult(Context, "static_assert");
3206 }
3207 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003208
Douglas Gregoraaf87162010-04-14 20:04:41 +00003209 // If we haven't found anything, we're done.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003210 if (Consumer.empty()) {
3211 // If this was an unqualified lookup, note that no correction was found.
3212 if (IsUnqualifiedLookup)
3213 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003214
Douglas Gregor931f98a2010-04-14 17:09:22 +00003215 return DeclarationName();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003216 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003217
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003218 // Make sure that the user typed at least 3 characters for each correction
Douglas Gregore24b5752010-10-14 20:34:08 +00003219 // made. Otherwise, we don't even both looking at the results.
Douglas Gregor53e4b552010-10-26 17:18:00 +00003220
3221 // We also suppress exact matches; those should be handled by a
3222 // different mechanism (e.g., one that introduces qualification in
3223 // C++).
Douglas Gregore24b5752010-10-14 20:34:08 +00003224 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003225 if (ED > 0 && Typo->getName().size() / ED < 3) {
3226 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregor157a3ff2010-10-27 14:20:34 +00003227 if (IsUnqualifiedLookup)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003228 (void)UnqualifiedTyposCorrected[Typo];
3229
Douglas Gregore24b5752010-10-14 20:34:08 +00003230 return DeclarationName();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003231 }
Douglas Gregore24b5752010-10-14 20:34:08 +00003232
3233 // Weed out any names that could not be found by name lookup.
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003234 bool LastLookupWasAccepted = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003235 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
Douglas Gregoraaf87162010-04-14 20:04:41 +00003236 IEnd = Consumer.end();
Douglas Gregore24b5752010-10-14 20:34:08 +00003237 I != IEnd; /* Increment in loop. */) {
3238 // Keywords are always found.
3239 if (I->second) {
3240 ++I;
3241 continue;
Douglas Gregoraaf87162010-04-14 20:04:41 +00003242 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003243
Douglas Gregore24b5752010-10-14 20:34:08 +00003244 // Perform name lookup on this name.
3245 IdentifierInfo *Name = &Context.Idents.get(I->getKey());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003246 LookupPotentialTypoResult(*this, Res, Name, S, SS, MemberContext,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003247 EnteringContext, CTC);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003248
Douglas Gregore24b5752010-10-14 20:34:08 +00003249 switch (Res.getResultKind()) {
3250 case LookupResult::NotFound:
3251 case LookupResult::NotFoundInCurrentInstantiation:
3252 case LookupResult::Ambiguous:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003253 // We didn't find this name in our scope, or didn't like what we found;
Douglas Gregore24b5752010-10-14 20:34:08 +00003254 // ignore it.
3255 Res.suppressDiagnostics();
3256 {
3257 TypoCorrectionConsumer::iterator Next = I;
3258 ++Next;
3259 Consumer.erase(I);
3260 I = Next;
3261 }
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003262 LastLookupWasAccepted = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003263 break;
3264
Douglas Gregore24b5752010-10-14 20:34:08 +00003265 case LookupResult::Found:
3266 case LookupResult::FoundOverloaded:
3267 case LookupResult::FoundUnresolvedValue:
3268 ++I;
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003269 LastLookupWasAccepted = true;
Douglas Gregoraaf87162010-04-14 20:04:41 +00003270 break;
Douglas Gregore24b5752010-10-14 20:34:08 +00003271 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003272
Douglas Gregore24b5752010-10-14 20:34:08 +00003273 if (Res.isAmbiguous()) {
3274 // We don't deal with ambiguities.
3275 Res.suppressDiagnostics();
3276 Res.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003277 return DeclarationName();
3278 }
Douglas Gregoraaf87162010-04-14 20:04:41 +00003279 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003280
Douglas Gregore24b5752010-10-14 20:34:08 +00003281 // If only a single name remains, return that result.
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003282 if (Consumer.size() == 1) {
3283 IdentifierInfo *Name = &Context.Idents.get(Consumer.begin()->getKey());
Douglas Gregorf98402d2010-10-20 01:01:57 +00003284 if (Consumer.begin()->second) {
3285 Res.suppressDiagnostics();
3286 Res.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003287
Douglas Gregor53e4b552010-10-26 17:18:00 +00003288 // Don't correct to a keyword that's the same as the typo; the keyword
3289 // wasn't actually in scope.
3290 if (ED == 0) {
3291 Res.setLookupName(Typo);
3292 return DeclarationName();
3293 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003294
Douglas Gregorf98402d2010-10-20 01:01:57 +00003295 } else if (!LastLookupWasAccepted) {
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003296 // Perform name lookup on this name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003297 LookupPotentialTypoResult(*this, Res, Name, S, SS, MemberContext,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003298 EnteringContext, CTC);
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003299 }
3300
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003301 // Record the correction for unqualified lookup.
3302 if (IsUnqualifiedLookup)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003303 UnqualifiedTyposCorrected[Typo]
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003304 = std::make_pair(Name->getName(), Consumer.begin()->second);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003305
3306 return &Context.Idents.get(Consumer.begin()->getKey());
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003307 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003308 else if (Consumer.size() > 1 && CTC == CTC_ObjCMessageReceiver
Douglas Gregor7b824e82010-10-15 13:35:25 +00003309 && Consumer["super"]) {
3310 // Prefix 'super' when we're completing in a message-receiver
3311 // context.
3312 Res.suppressDiagnostics();
3313 Res.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003314
Douglas Gregor53e4b552010-10-26 17:18:00 +00003315 // Don't correct to a keyword that's the same as the typo; the keyword
3316 // wasn't actually in scope.
3317 if (ED == 0) {
3318 Res.setLookupName(Typo);
3319 return DeclarationName();
3320 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003321
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003322 // Record the correction for unqualified lookup.
3323 if (IsUnqualifiedLookup)
3324 UnqualifiedTyposCorrected[Typo]
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003325 = std::make_pair("super", Consumer.begin()->second);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003326
Douglas Gregor7b824e82010-10-15 13:35:25 +00003327 return &Context.Idents.get("super");
3328 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003329
Douglas Gregore24b5752010-10-14 20:34:08 +00003330 Res.suppressDiagnostics();
3331 Res.setLookupName(Typo);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003332 Res.clear();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003333 // Record the correction for unqualified lookup.
3334 if (IsUnqualifiedLookup)
3335 (void)UnqualifiedTyposCorrected[Typo];
3336
Douglas Gregor931f98a2010-04-14 17:09:22 +00003337 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003338}