blob: b7740bf5c0828f97404509d27ef863adf09a8bb1 [file] [log] [blame]
Douglas Gregor34074322009-01-14 22:20:51 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000016#include "clang/Sema/Lookup.h"
John McCall8b0666c2010-08-20 18:27:03 +000017#include "clang/Sema/DeclSpec.h"
John McCallcc14d1f2010-08-24 08:50:51 +000018#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
John McCall19c1bfd2010-08-25 05:32:35 +000020#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor960b5bc2009-01-15 00:26:24 +000021#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000023#include "clang/AST/Decl.h"
24#include "clang/AST/DeclCXX.h"
25#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000026#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000027#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000028#include "clang/AST/ExprCXX.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000029#include "clang/Basic/Builtins.h"
Douglas Gregor34074322009-01-14 22:20:51 +000030#include "clang/Basic/LangOptions.h"
John McCalla1e130b2010-08-25 07:03:20 +000031#include "llvm/ADT/DenseSet.h"
Douglas Gregor34074322009-01-14 22:20:51 +000032#include "llvm/ADT/STLExtras.h"
Douglas Gregore254f902009-02-04 00:32:51 +000033#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0afa7f62010-10-14 20:34:08 +000034#include "llvm/ADT/StringMap.h"
John McCall6538c932009-10-10 05:48:19 +000035#include "llvm/Support/ErrorHandling.h"
Douglas Gregor0afa7f62010-10-14 20:34:08 +000036#include <limits>
Douglas Gregor2d435302009-12-30 17:04:44 +000037#include <list>
Douglas Gregor1c846b02009-01-16 00:38:09 +000038#include <set>
Douglas Gregor889ceb72009-02-03 19:21:40 +000039#include <vector>
40#include <iterator>
41#include <utility>
42#include <algorithm>
Douglas Gregor34074322009-01-14 22:20:51 +000043
44using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000045using namespace sema;
Douglas Gregor34074322009-01-14 22:20:51 +000046
John McCallf6c8a4e2009-11-10 07:01:13 +000047namespace {
48 class UnqualUsingEntry {
49 const DeclContext *Nominated;
50 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000051
John McCallf6c8a4e2009-11-10 07:01:13 +000052 public:
53 UnqualUsingEntry(const DeclContext *Nominated,
54 const DeclContext *CommonAncestor)
55 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
56 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000057
John McCallf6c8a4e2009-11-10 07:01:13 +000058 const DeclContext *getCommonAncestor() const {
59 return CommonAncestor;
60 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000061
John McCallf6c8a4e2009-11-10 07:01:13 +000062 const DeclContext *getNominatedNamespace() const {
63 return Nominated;
64 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000065
John McCallf6c8a4e2009-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 Gregor889ceb72009-02-03 19:21:40 +000071
John McCallf6c8a4e2009-11-10 07:01:13 +000072 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
73 return E.getCommonAncestor() < DC;
74 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000075
John McCallf6c8a4e2009-11-10 07:01:13 +000076 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
77 return DC < E.getCommonAncestor();
78 }
79 };
80 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000081
John McCallf6c8a4e2009-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 Gregor889ceb72009-02-03 19:21:40 +000086
John McCallf6c8a4e2009-11-10 07:01:13 +000087 ListTy list;
88 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000089
John McCallf6c8a4e2009-11-10 07:01:13 +000090 public:
91 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +000092
John McCallf6c8a4e2009-11-10 07:01:13 +000093 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000094 // C++ [namespace.udir]p1:
John McCallf6c8a4e2009-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 Gregor889ceb72009-02-03 19:21:40 +0000101
John McCallf6c8a4e2009-11-10 07:01:13 +0000102 for (; S; S = S->getParent()) {
John McCallf6c8a4e2009-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 Takumif9cbcc42011-01-27 07:10:08 +0000109
John McCallf6c8a4e2009-11-10 07:01:13 +0000110 for (; I != End; ++I)
John McCall48871652010-08-21 09:40:31 +0000111 visit(*I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000112 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000113 }
114 }
John McCallf6c8a4e2009-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 McCall9757d032009-11-10 09:20:04 +0000179 Common = Common->getPrimaryContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000180
John McCallf6c8a4e2009-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 McCallf6c8a4e2009-11-10 07:01:13 +0000188 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000189
John McCallf6c8a4e2009-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 McCall9757d032009-11-10 09:20:04 +0000195 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCallf6c8a4e2009-11-10 07:01:13 +0000196 UnqualUsingEntry::Comparator());
197 }
198 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000199}
200
Douglas Gregor889ceb72009-02-03 19:21:40 +0000201// Retrieve the set of identifier namespaces that correspond to a
202// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000203static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
204 bool CPlusPlus,
205 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000206 unsigned IDNS = 0;
207 switch (NameKind) {
208 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000209 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000210 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000211 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000212 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000213 if (Redeclaration)
214 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCallea305ed2009-12-18 10:40:03 +0000215 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000216 break;
217
John McCallb9467b62010-04-24 01:30:58 +0000218 case Sema::LookupOperatorName:
219 // Operator lookup is its own crazy thing; it is not the same
220 // as (e.g.) looking up an operator name for redeclaration.
221 assert(!Redeclaration && "cannot do redeclaration operator lookup");
222 IDNS = Decl::IDNS_NonMemberOperator;
223 break;
224
Douglas Gregor889ceb72009-02-03 19:21:40 +0000225 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000226 if (CPlusPlus) {
227 IDNS = Decl::IDNS_Type;
228
229 // When looking for a redeclaration of a tag name, we add:
230 // 1) TagFriend to find undeclared friend decls
231 // 2) Namespace because they can't "overload" with tag decls.
232 // 3) Tag because it includes class templates, which can't
233 // "overload" with tag decls.
234 if (Redeclaration)
235 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
236 } else {
237 IDNS = Decl::IDNS_Tag;
238 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000239 break;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000240 case Sema::LookupLabel:
241 IDNS = Decl::IDNS_Label;
242 break;
243
Douglas Gregor889ceb72009-02-03 19:21:40 +0000244 case Sema::LookupMemberName:
245 IDNS = Decl::IDNS_Member;
246 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000247 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000248 break;
249
250 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000251 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
252 break;
253
Douglas Gregor889ceb72009-02-03 19:21:40 +0000254 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000255 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000256 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000257
John McCall84d87672009-12-10 09:41:52 +0000258 case Sema::LookupUsingDeclName:
259 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
260 | Decl::IDNS_Member | Decl::IDNS_Using;
261 break;
262
Douglas Gregor79947a22009-04-24 00:11:27 +0000263 case Sema::LookupObjCProtocolName:
264 IDNS = Decl::IDNS_ObjCProtocol;
265 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000266
Douglas Gregor39982192010-08-15 06:18:01 +0000267 case Sema::LookupAnyName:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000268 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor39982192010-08-15 06:18:01 +0000269 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
270 | Decl::IDNS_Type;
271 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000272 }
273 return IDNS;
274}
275
John McCallea305ed2009-12-18 10:40:03 +0000276void LookupResult::configure() {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000277 IDNS = getIDNS(LookupKind, SemaRef.getLangOptions().CPlusPlus,
John McCallea305ed2009-12-18 10:40:03 +0000278 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000279
280 // If we're looking for one of the allocation or deallocation
281 // operators, make sure that the implicitly-declared new and delete
282 // operators can be found.
283 if (!isForRedeclaration()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000284 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000285 case OO_New:
286 case OO_Delete:
287 case OO_Array_New:
288 case OO_Array_Delete:
289 SemaRef.DeclareGlobalNewDelete();
290 break;
291
292 default:
293 break;
294 }
295 }
John McCallea305ed2009-12-18 10:40:03 +0000296}
297
John McCall19c1bfd2010-08-25 05:32:35 +0000298void LookupResult::sanity() const {
299 assert(ResultKind != NotFound || Decls.size() == 0);
300 assert(ResultKind != Found || Decls.size() == 1);
301 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
302 (Decls.size() == 1 &&
303 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
304 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
305 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000306 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
307 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall19c1bfd2010-08-25 05:32:35 +0000308 assert((Paths != NULL) == (ResultKind == Ambiguous &&
309 (Ambiguity == AmbiguousBaseSubobjectTypes ||
310 Ambiguity == AmbiguousBaseSubobjects)));
311}
John McCall19c1bfd2010-08-25 05:32:35 +0000312
John McCall9f3059a2009-10-09 21:13:30 +0000313// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000314void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000315 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000316}
317
John McCall283b9012009-11-22 00:44:51 +0000318/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000319void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000320 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000321
John McCall9f3059a2009-10-09 21:13:30 +0000322 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000323 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000324 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000325 return;
326 }
327
John McCall283b9012009-11-22 00:44:51 +0000328 // If there's a single decl, we need to examine it to decide what
329 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000330 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000331 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
332 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000333 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000334 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000335 ResultKind = FoundUnresolvedValue;
336 return;
337 }
John McCall9f3059a2009-10-09 21:13:30 +0000338
John McCall6538c932009-10-10 05:48:19 +0000339 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000340 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000341
John McCall9f3059a2009-10-09 21:13:30 +0000342 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor13e65872010-08-11 14:45:53 +0000343 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000344
John McCall9f3059a2009-10-09 21:13:30 +0000345 bool Ambiguous = false;
346 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000347 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000348
349 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000350
John McCall9f3059a2009-10-09 21:13:30 +0000351 unsigned I = 0;
352 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000353 NamedDecl *D = Decls[I]->getUnderlyingDecl();
354 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000355
Douglas Gregor13e65872010-08-11 14:45:53 +0000356 // Redeclarations of types via typedef can occur both within a scope
357 // and, through using declarations and directives, across scopes. There is
358 // no ambiguity if they all refer to the same type, so unique based on the
359 // canonical type.
360 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
361 if (!TD->getDeclContext()->isRecord()) {
362 QualType T = SemaRef.Context.getTypeDeclType(TD);
363 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
364 // The type is not unique; pull something off the back and continue
365 // at this index.
366 Decls[I] = Decls[--N];
367 continue;
368 }
369 }
370 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000371
John McCallf0f1cf02009-11-17 07:50:12 +0000372 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000373 // If it's not unique, pull something off the back (and
374 // continue at this index).
375 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000376 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000377 }
378
Douglas Gregor13e65872010-08-11 14:45:53 +0000379 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000380
Douglas Gregor13e65872010-08-11 14:45:53 +0000381 if (isa<UnresolvedUsingValueDecl>(D)) {
382 HasUnresolved = true;
383 } else if (isa<TagDecl>(D)) {
384 if (HasTag)
385 Ambiguous = true;
386 UniqueTagIndex = I;
387 HasTag = true;
388 } else if (isa<FunctionTemplateDecl>(D)) {
389 HasFunction = true;
390 HasFunctionTemplate = true;
391 } else if (isa<FunctionDecl>(D)) {
392 HasFunction = true;
393 } else {
394 if (HasNonFunction)
395 Ambiguous = true;
396 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000397 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000398 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000399 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000400
John McCall9f3059a2009-10-09 21:13:30 +0000401 // C++ [basic.scope.hiding]p2:
402 // A class name or enumeration name can be hidden by the name of
403 // an object, function, or enumerator declared in the same
404 // scope. If a class or enumeration name and an object, function,
405 // or enumerator are declared in the same scope (in any order)
406 // with the same name, the class or enumeration name is hidden
407 // wherever the object, function, or enumerator name is visible.
408 // But it's still an error if there are distinct tag types found,
409 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000410 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000411 (HasFunction || HasNonFunction || HasUnresolved)) {
412 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
413 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
414 Decls[UniqueTagIndex] = Decls[--N];
415 else
416 Ambiguous = true;
417 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000418
John McCall9f3059a2009-10-09 21:13:30 +0000419 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000420
John McCall80053822009-12-03 00:58:24 +0000421 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000422 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000423
John McCall9f3059a2009-10-09 21:13:30 +0000424 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000425 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000426 else if (HasUnresolved)
427 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000428 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000429 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000430 else
John McCall27b18f82009-11-17 02:14:36 +0000431 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000432}
433
John McCall5cebab12009-11-18 07:57:50 +0000434void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000435 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000436 DeclContext::lookup_iterator DI, DE;
437 for (I = P.begin(), E = P.end(); I != E; ++I)
438 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
439 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000440}
441
John McCall5cebab12009-11-18 07:57:50 +0000442void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000443 Paths = new CXXBasePaths;
444 Paths->swap(P);
445 addDeclsFromBasePaths(*Paths);
446 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000447 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000448}
449
John McCall5cebab12009-11-18 07:57:50 +0000450void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000451 Paths = new CXXBasePaths;
452 Paths->swap(P);
453 addDeclsFromBasePaths(*Paths);
454 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000455 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000456}
457
John McCall5cebab12009-11-18 07:57:50 +0000458void LookupResult::print(llvm::raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000459 Out << Decls.size() << " result(s)";
460 if (isAmbiguous()) Out << ", ambiguous";
461 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000462
John McCall9f3059a2009-10-09 21:13:30 +0000463 for (iterator I = begin(), E = end(); I != E; ++I) {
464 Out << "\n";
465 (*I)->print(Out, 2);
466 }
467}
468
Douglas Gregord3a59182010-02-12 05:48:04 +0000469/// \brief Lookup a builtin function, when name lookup would otherwise
470/// fail.
471static bool LookupBuiltin(Sema &S, LookupResult &R) {
472 Sema::LookupNameKind NameKind = R.getLookupKind();
473
474 // If we didn't find a use of this identifier, and if the identifier
475 // corresponds to a compiler builtin, create the decl object for the builtin
476 // now, injecting it into translation unit scope, and return it.
477 if (NameKind == Sema::LookupOrdinaryName ||
478 NameKind == Sema::LookupRedeclarationWithLinkage) {
479 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
480 if (II) {
481 // If this is a builtin on this (or all) targets, create the decl.
482 if (unsigned BuiltinID = II->getBuiltinID()) {
483 // In C++, we don't have any predefined library functions like
484 // 'malloc'. Instead, we'll just error.
485 if (S.getLangOptions().CPlusPlus &&
486 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
487 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000488
489 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
490 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000491 R.isForRedeclaration(),
492 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000493 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000494 return true;
495 }
496
497 if (R.isForRedeclaration()) {
498 // If we're redeclaring this function anyway, forget that
499 // this was a builtin at all.
500 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
501 }
502
503 return false;
Douglas Gregord3a59182010-02-12 05:48:04 +0000504 }
505 }
506 }
507
508 return false;
509}
510
Douglas Gregor7454c562010-07-02 20:37:36 +0000511/// \brief Determine whether we can declare a special member function within
512/// the class at this point.
513static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
514 const CXXRecordDecl *Class) {
John McCall2ded5d22010-08-11 23:52:36 +0000515 // Don't do it if the class is invalid.
516 if (Class->isInvalidDecl())
517 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000518
Douglas Gregor7454c562010-07-02 20:37:36 +0000519 // We need to have a definition for the class.
520 if (!Class->getDefinition() || Class->isDependentContext())
521 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000522
Douglas Gregor7454c562010-07-02 20:37:36 +0000523 // We can't be in the middle of defining the class.
524 if (const RecordType *RecordTy
525 = Context.getTypeDeclType(Class)->getAs<RecordType>())
526 return !RecordTy->isBeingDefined();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000527
Douglas Gregor7454c562010-07-02 20:37:36 +0000528 return false;
529}
530
531void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000532 if (!CanDeclareSpecialMemberFunction(Context, Class))
533 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000534
535 // If the default constructor has not yet been declared, do so now.
536 if (!Class->hasDeclaredDefaultConstructor())
537 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000538
Douglas Gregora6d69502010-07-02 23:41:54 +0000539 // If the copy constructor has not yet been declared, do so now.
540 if (!Class->hasDeclaredCopyConstructor())
541 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000542
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000543 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000544 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000545 DeclareImplicitCopyAssignment(Class);
546
Douglas Gregor7454c562010-07-02 20:37:36 +0000547 // If the destructor has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000548 if (!Class->hasDeclaredDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000549 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000550}
551
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000552/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000553/// special member function.
554static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
555 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000556 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000557 case DeclarationName::CXXDestructorName:
558 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000559
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000560 case DeclarationName::CXXOperatorName:
561 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000562
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000563 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000564 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000565 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000566
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000567 return false;
568}
569
570/// \brief If there are any implicit member functions with the given name
571/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000572static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000573 DeclarationName Name,
574 const DeclContext *DC) {
575 if (!DC)
576 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000577
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000578 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000579 case DeclarationName::CXXConstructorName:
580 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor9672f922010-07-03 00:47:00 +0000581 if (Record->getDefinition() &&
582 CanDeclareSpecialMemberFunction(S.Context, Record)) {
583 if (!Record->hasDeclaredDefaultConstructor())
584 S.DeclareImplicitDefaultConstructor(
585 const_cast<CXXRecordDecl *>(Record));
586 if (!Record->hasDeclaredCopyConstructor())
587 S.DeclareImplicitCopyConstructor(const_cast<CXXRecordDecl *>(Record));
588 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000589 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000590
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000591 case DeclarationName::CXXDestructorName:
592 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
593 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
594 CanDeclareSpecialMemberFunction(S.Context, Record))
595 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000596 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000597
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000598 case DeclarationName::CXXOperatorName:
599 if (Name.getCXXOverloadedOperator() != OO_Equal)
600 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000601
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000602 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
603 if (Record->getDefinition() && !Record->hasDeclaredCopyAssignment() &&
604 CanDeclareSpecialMemberFunction(S.Context, Record))
605 S.DeclareImplicitCopyAssignment(const_cast<CXXRecordDecl *>(Record));
606 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000607
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000608 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000609 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000610 }
611}
Douglas Gregor7454c562010-07-02 20:37:36 +0000612
John McCall9f3059a2009-10-09 21:13:30 +0000613// Adds all qualifying matches for a name within a decl context to the
614// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000615static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000616 bool Found = false;
617
Douglas Gregor7454c562010-07-02 20:37:36 +0000618 // Lazily declare C++ special member functions.
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000619 if (S.getLangOptions().CPlusPlus)
620 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000621
Douglas Gregor7454c562010-07-02 20:37:36 +0000622 // Perform lookup into this declaration context.
John McCallf6c8a4e2009-11-10 07:01:13 +0000623 DeclContext::lookup_const_iterator I, E;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000624 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall401982f2010-01-20 21:53:11 +0000625 NamedDecl *D = *I;
626 if (R.isAcceptableDecl(D)) {
627 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000628 Found = true;
629 }
630 }
John McCall9f3059a2009-10-09 21:13:30 +0000631
Douglas Gregord3a59182010-02-12 05:48:04 +0000632 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
633 return true;
634
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000635 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000636 != DeclarationName::CXXConversionFunctionName ||
637 R.getLookupName().getCXXNameType()->isDependentType() ||
638 !isa<CXXRecordDecl>(DC))
639 return Found;
640
641 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000642 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000643 // name lookup. Instead, any conversion function templates visible in the
644 // context of the use are considered. [...]
645 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
646 if (!Record->isDefinition())
647 return Found;
648
649 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000650 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
Chandler Carruth3a693b72010-01-31 11:44:02 +0000651 UEnd = Unresolved->end(); U != UEnd; ++U) {
652 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
653 if (!ConvTemplate)
654 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000655
Chandler Carruth3a693b72010-01-31 11:44:02 +0000656 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000657 // add the conversion function template. When we deduce template
658 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000659 // type of the new declaration with the type of the function template.
660 if (R.isForRedeclaration()) {
661 R.addDecl(ConvTemplate);
662 Found = true;
663 continue;
664 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000665
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000666 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000667 // [...] For each such operator, if argument deduction succeeds
668 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000669 // name lookup.
670 //
671 // When referencing a conversion function for any purpose other than
672 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000673 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000674 // specialization into the result set. We do this to avoid forcing all
675 // callers to perform special deduction for conversion functions.
John McCall19c1bfd2010-08-25 05:32:35 +0000676 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruth3a693b72010-01-31 11:44:02 +0000677 FunctionDecl *Specialization = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000678
679 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000680 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
681 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000682
Chandler Carruth3a693b72010-01-31 11:44:02 +0000683 // Compute the type of the function that we would expect the conversion
684 // function to have, if it were to match the name given.
685 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000686 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
687 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
688 EPI.HasExceptionSpec = false;
689 EPI.HasAnyExceptionSpec = false;
690 EPI.NumExceptions = 0;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000691 QualType ExpectedType
692 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
John McCalldb40c7f2010-12-14 08:05:40 +0000693 0, 0, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000694
Chandler Carruth3a693b72010-01-31 11:44:02 +0000695 // Perform template argument deduction against the type that we would
696 // expect the function to have.
697 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
698 Specialization, Info)
699 == Sema::TDK_Success) {
700 R.addDecl(Specialization);
701 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000702 }
703 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000704
John McCall9f3059a2009-10-09 21:13:30 +0000705 return Found;
706}
707
John McCallf6c8a4e2009-11-10 07:01:13 +0000708// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000709static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000710CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000711 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000712
713 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
714
John McCallf6c8a4e2009-11-10 07:01:13 +0000715 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000716 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000717
John McCallf6c8a4e2009-11-10 07:01:13 +0000718 // Perform direct name lookup into the namespaces nominated by the
719 // using directives whose common ancestor is this namespace.
720 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
721 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000722
John McCallf6c8a4e2009-11-10 07:01:13 +0000723 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000724 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000725 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000726
727 R.resolveKind();
728
729 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000730}
731
732static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000733 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000734 return Ctx->isFileContext();
735 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000736}
Douglas Gregored8f2882009-01-30 01:04:22 +0000737
Douglas Gregor66230062010-03-15 14:33:29 +0000738// Find the next outer declaration context from this scope. This
739// routine actually returns the semantic outer context, which may
740// differ from the lexical context (encoded directly in the Scope
741// stack) when we are parsing a member of a class template. In this
742// case, the second element of the pair will be true, to indicate that
743// name lookup should continue searching in this semantic context when
744// it leaves the current template parameter scope.
745static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
746 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
747 DeclContext *Lexical = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000748 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000749 OuterS = OuterS->getParent()) {
750 if (OuterS->getEntity()) {
Douglas Gregorea166062010-03-15 15:26:48 +0000751 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor66230062010-03-15 14:33:29 +0000752 break;
753 }
754 }
755
756 // C++ [temp.local]p8:
757 // In the definition of a member of a class template that appears
758 // outside of the namespace containing the class template
759 // definition, the name of a template-parameter hides the name of
760 // a member of this namespace.
761 //
762 // Example:
763 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000764 // namespace N {
765 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000766 //
767 // template<class T> class B {
768 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000769 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000770 // }
771 //
772 // template<class C> void N::B<C>::f(C) {
773 // C b; // C is the template parameter, not N::C
774 // }
775 //
776 // In this example, the lexical context we return is the
777 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000778 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000779 !S->getParent()->isTemplateParamScope())
780 return std::make_pair(Lexical, false);
781
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000782 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000783 // For the example, this is the scope for the template parameters of
784 // template<class C>.
785 Scope *OutermostTemplateScope = S->getParent();
786 while (OutermostTemplateScope->getParent() &&
787 OutermostTemplateScope->getParent()->isTemplateParamScope())
788 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000789
Douglas Gregor66230062010-03-15 14:33:29 +0000790 // Find the namespace context in which the original scope occurs. In
791 // the example, this is namespace N.
792 DeclContext *Semantic = DC;
793 while (!Semantic->isFileContext())
794 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000795
Douglas Gregor66230062010-03-15 14:33:29 +0000796 // Find the declaration context just outside of the template
797 // parameter scope. This is the context in which the template is
798 // being lexically declaration (a namespace context). In the
799 // example, this is the global scope.
800 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
801 Lexical->Encloses(Semantic))
802 return std::make_pair(Semantic, true);
803
804 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000805}
806
John McCall27b18f82009-11-17 02:14:36 +0000807bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCallea305ed2009-12-18 10:40:03 +0000808 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000809
810 DeclarationName Name = R.getLookupName();
811
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000812 // If this is the name of an implicitly-declared special member function,
813 // go through the scope stack to implicitly declare
814 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
815 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
816 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
817 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
818 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000819
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000820 // Implicitly declare member functions with the name we're looking for, if in
821 // fact we are in a scope where it matters.
822
Douglas Gregor889ceb72009-02-03 19:21:40 +0000823 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000824 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000825 I = IdResolver.begin(Name),
826 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000827
Douglas Gregor889ceb72009-02-03 19:21:40 +0000828 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000829 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000830 // ...During unqualified name lookup (3.4.1), the names appear as if
831 // they were declared in the nearest enclosing namespace which contains
832 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000833 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000834 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000835 //
836 // For example:
837 // namespace A { int i; }
838 // void foo() {
839 // int i;
840 // {
841 // using namespace A;
842 // ++i; // finds local 'i', A::i appears at global scope
843 // }
844 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000845 //
Douglas Gregor66230062010-03-15 14:33:29 +0000846 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor700792c2009-02-05 19:25:20 +0000847 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor3e51e172010-05-20 20:58:56 +0000848 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
849
Douglas Gregor889ceb72009-02-03 19:21:40 +0000850 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000851 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000852 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000853 if (R.isAcceptableDecl(*I)) {
John McCall9f3059a2009-10-09 21:13:30 +0000854 Found = true;
855 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000856 }
857 }
John McCall9f3059a2009-10-09 21:13:30 +0000858 if (Found) {
859 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000860 if (S->isClassScope())
861 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
862 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000863 return true;
864 }
865
Douglas Gregor66230062010-03-15 14:33:29 +0000866 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
867 S->getParent() && !S->getParent()->isTemplateParamScope()) {
868 // We've just searched the last template parameter scope and
869 // found nothing, so look into the the contexts between the
870 // lexical and semantic declaration contexts returned by
871 // findOuterContext(). This implements the name lookup behavior
872 // of C++ [temp.local]p8.
873 Ctx = OutsideOfTemplateParamDC;
874 OutsideOfTemplateParamDC = 0;
875 }
876
877 if (Ctx) {
878 DeclContext *OuterCtx;
879 bool SearchAfterTemplateScope;
880 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
881 if (SearchAfterTemplateScope)
882 OutsideOfTemplateParamDC = OuterCtx;
883
Douglas Gregorea166062010-03-15 15:26:48 +0000884 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000885 // We do not directly look into transparent contexts, since
886 // those entities will be found in the nearest enclosing
887 // non-transparent context.
888 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000889 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000890
891 // We do not look directly into function or method contexts,
892 // since all of the local variables and parameters of the
893 // function/method are present within the Scope.
894 if (Ctx->isFunctionOrMethod()) {
895 // If we have an Objective-C instance method, look for ivars
896 // in the corresponding interface.
897 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
898 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
899 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
900 ObjCInterfaceDecl *ClassDeclared;
901 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000902 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +0000903 ClassDeclared)) {
904 if (R.isAcceptableDecl(Ivar)) {
905 R.addDecl(Ivar);
906 R.resolveKind();
907 return true;
908 }
909 }
910 }
911 }
912
913 continue;
914 }
915
Douglas Gregor7f737c02009-09-10 16:57:35 +0000916 // Perform qualified name lookup into this context.
917 // FIXME: In some cases, we know that every name that could be found by
918 // this qualified name lookup will also be on the identifier chain. For
919 // example, inside a class without any base classes, we never need to
920 // perform qualified lookup because all of the members are on top of the
921 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000922 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +0000923 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000924 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000925 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000926 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000927
John McCallf6c8a4e2009-11-10 07:01:13 +0000928 // Stop if we ran out of scopes.
929 // FIXME: This really, really shouldn't be happening.
930 if (!S) return false;
931
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +0000932 // If we are looking for members, no need to look into global/namespace scope.
933 if (R.getLookupKind() == LookupMemberName)
934 return false;
935
Douglas Gregor700792c2009-02-05 19:25:20 +0000936 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000937 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000938 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000939 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
940 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000941
John McCallf6c8a4e2009-11-10 07:01:13 +0000942 UnqualUsingDirectiveSet UDirs;
943 UDirs.visitScopeChain(Initial, S);
944 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000945
Douglas Gregor700792c2009-02-05 19:25:20 +0000946 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000947 // Unqualified name lookup in C++ requires looking into scopes
948 // that aren't strictly lexical, and therefore we walk through the
949 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000950
Douglas Gregor889ceb72009-02-03 19:21:40 +0000951 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000952 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000953 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000954 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000955 if (R.isAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000956 // We found something. Look for anything else in our scope
957 // with this same name and in an acceptable identifier
958 // namespace, so that we can construct an overload set if we
959 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000960 Found = true;
961 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000962 }
963 }
964
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000965 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +0000966 R.resolveKind();
967 return true;
968 }
969
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000970 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
971 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
972 S->getParent() && !S->getParent()->isTemplateParamScope()) {
973 // We've just searched the last template parameter scope and
974 // found nothing, so look into the the contexts between the
975 // lexical and semantic declaration contexts returned by
976 // findOuterContext(). This implements the name lookup behavior
977 // of C++ [temp.local]p8.
978 Ctx = OutsideOfTemplateParamDC;
979 OutsideOfTemplateParamDC = 0;
980 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000981
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000982 if (Ctx) {
983 DeclContext *OuterCtx;
984 bool SearchAfterTemplateScope;
985 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
986 if (SearchAfterTemplateScope)
987 OutsideOfTemplateParamDC = OuterCtx;
988
989 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
990 // We do not directly look into transparent contexts, since
991 // those entities will be found in the nearest enclosing
992 // non-transparent context.
993 if (Ctx->isTransparentContext())
994 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000995
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000996 // If we have a context, and it's not a context stashed in the
997 // template parameter scope for an out-of-line definition, also
998 // look into that context.
999 if (!(Found && S && S->isTemplateParamScope())) {
1000 assert(Ctx->isFileContext() &&
1001 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001002
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001003 // Look into context considering using-directives.
1004 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1005 Found = true;
1006 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001007
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001008 if (Found) {
1009 R.resolveKind();
1010 return true;
1011 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001012
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001013 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1014 return false;
1015 }
1016 }
1017
Douglas Gregor3ce74932010-02-05 07:07:10 +00001018 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001019 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001020 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001021
John McCall9f3059a2009-10-09 21:13:30 +00001022 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001023}
1024
Douglas Gregor34074322009-01-14 22:20:51 +00001025/// @brief Perform unqualified name lookup starting from a given
1026/// scope.
1027///
1028/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1029/// used to find names within the current scope. For example, 'x' in
1030/// @code
1031/// int x;
1032/// int f() {
1033/// return x; // unqualified name look finds 'x' in the global scope
1034/// }
1035/// @endcode
1036///
1037/// Different lookup criteria can find different names. For example, a
1038/// particular scope can have both a struct and a function of the same
1039/// name, and each can be found by certain lookup criteria. For more
1040/// information about lookup criteria, see the documentation for the
1041/// class LookupCriteria.
1042///
1043/// @param S The scope from which unqualified name lookup will
1044/// begin. If the lookup criteria permits, name lookup may also search
1045/// in the parent scopes.
1046///
1047/// @param Name The name of the entity that we are searching for.
1048///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001049/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001050/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001051/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +00001052///
1053/// @returns The result of name lookup, which includes zero or more
1054/// declarations and possibly additional information used to diagnose
1055/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +00001056bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1057 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001058 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001059
John McCall27b18f82009-11-17 02:14:36 +00001060 LookupNameKind NameKind = R.getLookupKind();
1061
Douglas Gregor34074322009-01-14 22:20:51 +00001062 if (!getLangOptions().CPlusPlus) {
1063 // Unqualified name lookup in C/Objective-C is purely lexical, so
1064 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001065 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001066 // Find the nearest non-transparent declaration scope.
1067 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +00001068 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +00001069 static_cast<DeclContext *>(S->getEntity())
1070 ->isTransparentContext()))
1071 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001072 }
1073
John McCallea305ed2009-12-18 10:40:03 +00001074 unsigned IDNS = R.getIdentifierNamespace();
1075
Douglas Gregor34074322009-01-14 22:20:51 +00001076 // Scan up the scope chain looking for a decl that matches this
1077 // identifier that is in the appropriate namespace. This search
1078 // should not take long, as shadowing of names is uncommon, and
1079 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001080 bool LeftStartingScope = false;
1081
Douglas Gregored8f2882009-01-30 01:04:22 +00001082 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001083 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001084 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001085 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001086 if (NameKind == LookupRedeclarationWithLinkage) {
1087 // Determine whether this (or a previous) declaration is
1088 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001089 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001090 LeftStartingScope = true;
1091
1092 // If we found something outside of our starting scope that
1093 // does not have linkage, skip it.
1094 if (LeftStartingScope && !((*I)->hasLinkage()))
1095 continue;
1096 }
1097
John McCall9f3059a2009-10-09 21:13:30 +00001098 R.addDecl(*I);
1099
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001100 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001101 // If this declaration has the "overloadable" attribute, we
1102 // might have a set of overloaded functions.
1103
1104 // Figure out what scope the identifier is in.
Chris Lattner83f095c2009-03-28 19:18:32 +00001105 while (!(S->getFlags() & Scope::DeclScope) ||
John McCall48871652010-08-21 09:40:31 +00001106 !S->isDeclScope(*I))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001107 S = S->getParent();
1108
1109 // Find the last declaration in this scope (with the same
1110 // name, naturally).
1111 IdentifierResolver::iterator LastI = I;
1112 for (++LastI; LastI != IEnd; ++LastI) {
John McCall48871652010-08-21 09:40:31 +00001113 if (!S->isDeclScope(*LastI))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001114 break;
John McCall9f3059a2009-10-09 21:13:30 +00001115 R.addDecl(*LastI);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001116 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001117 }
1118
John McCall9f3059a2009-10-09 21:13:30 +00001119 R.resolveKind();
1120
1121 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001122 }
Douglas Gregor34074322009-01-14 22:20:51 +00001123 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001124 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001125 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001126 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001127 }
1128
1129 // If we didn't find a use of this identifier, and if the identifier
1130 // corresponds to a compiler builtin, create the decl object for the builtin
1131 // now, injecting it into translation unit scope, and return it.
Douglas Gregord3a59182010-02-12 05:48:04 +00001132 if (AllowBuiltinCreation)
1133 return LookupBuiltin(*this, R);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001134
John McCall9f3059a2009-10-09 21:13:30 +00001135 return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001136}
1137
John McCall6538c932009-10-10 05:48:19 +00001138/// @brief Perform qualified name lookup in the namespaces nominated by
1139/// using directives by the given context.
1140///
1141/// C++98 [namespace.qual]p2:
1142/// Given X::m (where X is a user-declared namespace), or given ::m
1143/// (where X is the global namespace), let S be the set of all
1144/// declarations of m in X and in the transitive closure of all
1145/// namespaces nominated by using-directives in X and its used
1146/// namespaces, except that using-directives are ignored in any
1147/// namespace, including X, directly containing one or more
1148/// declarations of m. No namespace is searched more than once in
1149/// the lookup of a name. If S is the empty set, the program is
1150/// ill-formed. Otherwise, if S has exactly one member, or if the
1151/// context of the reference is a using-declaration
1152/// (namespace.udecl), S is the required set of declarations of
1153/// m. Otherwise if the use of m is not one that allows a unique
1154/// declaration to be chosen from S, the program is ill-formed.
1155/// C++98 [namespace.qual]p5:
1156/// During the lookup of a qualified namespace member name, if the
1157/// lookup finds more than one declaration of the member, and if one
1158/// declaration introduces a class name or enumeration name and the
1159/// other declarations either introduce the same object, the same
1160/// enumerator or a set of functions, the non-type name hides the
1161/// class or enumeration name if and only if the declarations are
1162/// from the same namespace; otherwise (the declarations are from
1163/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001164static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001165 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001166 assert(StartDC->isFileContext() && "start context is not a file context");
1167
1168 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1169 DeclContext::udir_iterator E = StartDC->using_directives_end();
1170
1171 if (I == E) return false;
1172
1173 // We have at least added all these contexts to the queue.
1174 llvm::DenseSet<DeclContext*> Visited;
1175 Visited.insert(StartDC);
1176
1177 // We have not yet looked into these namespaces, much less added
1178 // their "using-children" to the queue.
1179 llvm::SmallVector<NamespaceDecl*, 8> Queue;
1180
1181 // We have already looked into the initial namespace; seed the queue
1182 // with its using-children.
1183 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +00001184 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6538c932009-10-10 05:48:19 +00001185 if (Visited.insert(ND).second)
1186 Queue.push_back(ND);
1187 }
1188
1189 // The easiest way to implement the restriction in [namespace.qual]p5
1190 // is to check whether any of the individual results found a tag
1191 // and, if so, to declare an ambiguity if the final result is not
1192 // a tag.
1193 bool FoundTag = false;
1194 bool FoundNonTag = false;
1195
John McCall5cebab12009-11-18 07:57:50 +00001196 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001197
1198 bool Found = false;
1199 while (!Queue.empty()) {
1200 NamespaceDecl *ND = Queue.back();
1201 Queue.pop_back();
1202
1203 // We go through some convolutions here to avoid copying results
1204 // between LookupResults.
1205 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001206 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001207 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001208
1209 if (FoundDirect) {
1210 // First do any local hiding.
1211 DirectR.resolveKind();
1212
1213 // If the local result is a tag, remember that.
1214 if (DirectR.isSingleTagDecl())
1215 FoundTag = true;
1216 else
1217 FoundNonTag = true;
1218
1219 // Append the local results to the total results if necessary.
1220 if (UseLocal) {
1221 R.addAllDecls(LocalR);
1222 LocalR.clear();
1223 }
1224 }
1225
1226 // If we find names in this namespace, ignore its using directives.
1227 if (FoundDirect) {
1228 Found = true;
1229 continue;
1230 }
1231
1232 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1233 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1234 if (Visited.insert(Nom).second)
1235 Queue.push_back(Nom);
1236 }
1237 }
1238
1239 if (Found) {
1240 if (FoundTag && FoundNonTag)
1241 R.setAmbiguousQualifiedTagHiding();
1242 else
1243 R.resolveKind();
1244 }
1245
1246 return Found;
1247}
1248
Douglas Gregor39982192010-08-15 06:18:01 +00001249/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001250static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor39982192010-08-15 06:18:01 +00001251 CXXBasePath &Path,
1252 void *Name) {
1253 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001254
Douglas Gregor39982192010-08-15 06:18:01 +00001255 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1256 Path.Decls = BaseRecord->lookup(N);
1257 return Path.Decls.first != Path.Decls.second;
1258}
1259
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001260/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001261/// static members, nested types, and enumerators.
1262template<typename InputIterator>
1263static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1264 Decl *D = (*First)->getUnderlyingDecl();
1265 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1266 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001267
Douglas Gregorc0d24902010-10-22 22:08:47 +00001268 if (isa<CXXMethodDecl>(D)) {
1269 // Determine whether all of the methods are static.
1270 bool AllMethodsAreStatic = true;
1271 for(; First != Last; ++First) {
1272 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001273
Douglas Gregorc0d24902010-10-22 22:08:47 +00001274 if (!isa<CXXMethodDecl>(D)) {
1275 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1276 break;
1277 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001278
Douglas Gregorc0d24902010-10-22 22:08:47 +00001279 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1280 AllMethodsAreStatic = false;
1281 break;
1282 }
1283 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001284
Douglas Gregorc0d24902010-10-22 22:08:47 +00001285 if (AllMethodsAreStatic)
1286 return true;
1287 }
1288
1289 return false;
1290}
1291
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001292/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001293///
1294/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1295/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001296/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001297///
1298/// Different lookup criteria can find different names. For example, a
1299/// particular scope can have both a struct and a function of the same
1300/// name, and each can be found by certain lookup criteria. For more
1301/// information about lookup criteria, see the documentation for the
1302/// class LookupCriteria.
1303///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001304/// \param R captures both the lookup criteria and any lookup results found.
1305///
1306/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001307/// search. If the lookup criteria permits, name lookup may also search
1308/// in the parent contexts or (for C++ classes) base classes.
1309///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001310/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001311/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001312///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001313/// \returns true if lookup succeeded, false if it failed.
1314bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1315 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001316 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001317
John McCall27b18f82009-11-17 02:14:36 +00001318 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001319 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001320
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001321 // Make sure that the declaration context is complete.
1322 assert((!isa<TagDecl>(LookupCtx) ||
1323 LookupCtx->isDependentContext() ||
1324 cast<TagDecl>(LookupCtx)->isDefinition() ||
1325 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1326 ->isBeingDefined()) &&
1327 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001328
Douglas Gregor34074322009-01-14 22:20:51 +00001329 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001330 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001331 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001332 if (isa<CXXRecordDecl>(LookupCtx))
1333 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001334 return true;
1335 }
Douglas Gregor34074322009-01-14 22:20:51 +00001336
John McCall6538c932009-10-10 05:48:19 +00001337 // Don't descend into implied contexts for redeclarations.
1338 // C++98 [namespace.qual]p6:
1339 // In a declaration for a namespace member in which the
1340 // declarator-id is a qualified-id, given that the qualified-id
1341 // for the namespace member has the form
1342 // nested-name-specifier unqualified-id
1343 // the unqualified-id shall name a member of the namespace
1344 // designated by the nested-name-specifier.
1345 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001346 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001347 return false;
1348
John McCall27b18f82009-11-17 02:14:36 +00001349 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001350 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001351 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001352
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001353 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001354 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001355 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001356 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001357 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001358
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001359 // If we're performing qualified name lookup into a dependent class,
1360 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001361 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001362 // template instantiation time (at which point all bases will be available)
1363 // or we have to fail.
1364 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1365 LookupRec->hasAnyDependentBases()) {
1366 R.setNotFoundInCurrentInstantiation();
1367 return false;
1368 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001369
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001370 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001371 CXXBasePaths Paths;
1372 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001373
1374 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001375 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001376 switch (R.getLookupKind()) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001377 case LookupOrdinaryName:
1378 case LookupMemberName:
1379 case LookupRedeclarationWithLinkage:
1380 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1381 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001382
Douglas Gregor36d1b142009-10-06 17:59:45 +00001383 case LookupTagName:
1384 BaseCallback = &CXXRecordDecl::FindTagMember;
1385 break;
John McCall84d87672009-12-10 09:41:52 +00001386
Douglas Gregor39982192010-08-15 06:18:01 +00001387 case LookupAnyName:
1388 BaseCallback = &LookupAnyMember;
1389 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001390
John McCall84d87672009-12-10 09:41:52 +00001391 case LookupUsingDeclName:
1392 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001393
Douglas Gregor36d1b142009-10-06 17:59:45 +00001394 case LookupOperatorName:
1395 case LookupNamespaceName:
1396 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001397 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001398 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001399 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001400
Douglas Gregor36d1b142009-10-06 17:59:45 +00001401 case LookupNestedNameSpecifierName:
1402 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1403 break;
1404 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001405
John McCall27b18f82009-11-17 02:14:36 +00001406 if (!LookupRec->lookupInBases(BaseCallback,
1407 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001408 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001409
John McCall553c0792010-01-23 00:46:32 +00001410 R.setNamingClass(LookupRec);
1411
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001412 // C++ [class.member.lookup]p2:
1413 // [...] If the resulting set of declarations are not all from
1414 // sub-objects of the same type, or the set has a nonstatic member
1415 // and includes members from distinct sub-objects, there is an
1416 // ambiguity and the program is ill-formed. Otherwise that set is
1417 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001418 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001419 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001420 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001421
Douglas Gregor36d1b142009-10-06 17:59:45 +00001422 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001423 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001424 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001425
John McCall401982f2010-01-20 21:53:11 +00001426 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1427 // across all paths.
1428 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001429
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001430 // Determine whether we're looking at a distinct sub-object or not.
1431 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001432 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001433 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1434 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001435 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001436 }
1437
Douglas Gregorc0d24902010-10-22 22:08:47 +00001438 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001439 != Context.getCanonicalType(PathElement.Base->getType())) {
1440 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001441 // different types. If the declaration sets aren't the same, this
1442 // this lookup is ambiguous.
1443 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1444 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1445 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1446 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001447
Douglas Gregorc0d24902010-10-22 22:08:47 +00001448 while (FirstD != FirstPath->Decls.second &&
1449 CurrentD != Path->Decls.second) {
1450 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1451 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1452 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001453
Douglas Gregorc0d24902010-10-22 22:08:47 +00001454 ++FirstD;
1455 ++CurrentD;
1456 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001457
Douglas Gregorc0d24902010-10-22 22:08:47 +00001458 if (FirstD == FirstPath->Decls.second &&
1459 CurrentD == Path->Decls.second)
1460 continue;
1461 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001462
John McCall9f3059a2009-10-09 21:13:30 +00001463 R.setAmbiguousBaseSubobjectTypes(Paths);
1464 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001465 }
1466
Douglas Gregorc0d24902010-10-22 22:08:47 +00001467 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001468 // We have a different subobject of the same type.
1469
1470 // C++ [class.member.lookup]p5:
1471 // A static member, a nested type or an enumerator defined in
1472 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001473 // has more than one base class subobject of type T.
Douglas Gregorc0d24902010-10-22 22:08:47 +00001474 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001475 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001476
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001477 // We have found a nonstatic member name in multiple, distinct
1478 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001479 R.setAmbiguousBaseSubobjects(Paths);
1480 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001481 }
1482 }
1483
1484 // Lookup in a base class succeeded; return these results.
1485
John McCall9f3059a2009-10-09 21:13:30 +00001486 DeclContext::lookup_iterator I, E;
John McCall553c0792010-01-23 00:46:32 +00001487 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1488 NamedDecl *D = *I;
1489 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1490 D->getAccess());
1491 R.addDecl(D, AS);
1492 }
John McCall9f3059a2009-10-09 21:13:30 +00001493 R.resolveKind();
1494 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001495}
1496
1497/// @brief Performs name lookup for a name that was parsed in the
1498/// source code, and may contain a C++ scope specifier.
1499///
1500/// This routine is a convenience routine meant to be called from
1501/// contexts that receive a name and an optional C++ scope specifier
1502/// (e.g., "N::M::x"). It will then perform either qualified or
1503/// unqualified name lookup (with LookupQualifiedName or LookupName,
1504/// respectively) on the given name and return those results.
1505///
1506/// @param S The scope from which unqualified name lookup will
1507/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001508///
Douglas Gregore861bac2009-08-25 22:51:20 +00001509/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001510///
Douglas Gregore861bac2009-08-25 22:51:20 +00001511/// @param EnteringContext Indicates whether we are going to enter the
1512/// context of the scope-specifier SS (if present).
1513///
John McCall9f3059a2009-10-09 21:13:30 +00001514/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001515bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001516 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001517 if (SS && SS->isInvalid()) {
1518 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001519 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001520 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001521 }
Mike Stump11289f42009-09-09 15:08:12 +00001522
Douglas Gregore861bac2009-08-25 22:51:20 +00001523 if (SS && SS->isSet()) {
1524 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001525 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001526 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001527 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001528 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001529
John McCall27b18f82009-11-17 02:14:36 +00001530 R.setContextRange(SS->getRange());
1531
1532 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001533 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001534
Douglas Gregore861bac2009-08-25 22:51:20 +00001535 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001536 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001537 // Name lookup can't find anything in this case.
John McCall9f3059a2009-10-09 21:13:30 +00001538 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001539 }
1540
Mike Stump11289f42009-09-09 15:08:12 +00001541 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001542 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001543}
1544
Douglas Gregor889ceb72009-02-03 19:21:40 +00001545
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001546/// @brief Produce a diagnostic describing the ambiguity that resulted
1547/// from name lookup.
1548///
1549/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001550///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001551/// @param Name The name of the entity that name lookup was
1552/// searching for.
1553///
1554/// @param NameLoc The location of the name within the source code.
1555///
1556/// @param LookupRange A source range that provides more
1557/// source-location information concerning the lookup itself. For
1558/// example, this range might highlight a nested-name-specifier that
1559/// precedes the name.
1560///
1561/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001562bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001563 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1564
John McCall27b18f82009-11-17 02:14:36 +00001565 DeclarationName Name = Result.getLookupName();
1566 SourceLocation NameLoc = Result.getNameLoc();
1567 SourceRange LookupRange = Result.getContextRange();
1568
John McCall6538c932009-10-10 05:48:19 +00001569 switch (Result.getAmbiguityKind()) {
1570 case LookupResult::AmbiguousBaseSubobjects: {
1571 CXXBasePaths *Paths = Result.getBasePaths();
1572 QualType SubobjectType = Paths->front().back().Base->getType();
1573 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1574 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1575 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001576
John McCall6538c932009-10-10 05:48:19 +00001577 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1578 while (isa<CXXMethodDecl>(*Found) &&
1579 cast<CXXMethodDecl>(*Found)->isStatic())
1580 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001581
John McCall6538c932009-10-10 05:48:19 +00001582 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001583
John McCall6538c932009-10-10 05:48:19 +00001584 return true;
1585 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001586
John McCall6538c932009-10-10 05:48:19 +00001587 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001588 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1589 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001590
John McCall6538c932009-10-10 05:48:19 +00001591 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001592 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001593 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1594 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001595 Path != PathEnd; ++Path) {
1596 Decl *D = *Path->Decls.first;
1597 if (DeclsPrinted.insert(D).second)
1598 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1599 }
1600
Douglas Gregor1c846b02009-01-16 00:38:09 +00001601 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001602 }
1603
John McCall6538c932009-10-10 05:48:19 +00001604 case LookupResult::AmbiguousTagHiding: {
1605 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001606
John McCall6538c932009-10-10 05:48:19 +00001607 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1608
1609 LookupResult::iterator DI, DE = Result.end();
1610 for (DI = Result.begin(); DI != DE; ++DI)
1611 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1612 TagDecls.insert(TD);
1613 Diag(TD->getLocation(), diag::note_hidden_tag);
1614 }
1615
1616 for (DI = Result.begin(); DI != DE; ++DI)
1617 if (!isa<TagDecl>(*DI))
1618 Diag((*DI)->getLocation(), diag::note_hiding_object);
1619
1620 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001621 LookupResult::Filter F = Result.makeFilter();
1622 while (F.hasNext()) {
1623 if (TagDecls.count(F.next()))
1624 F.erase();
1625 }
1626 F.done();
John McCall6538c932009-10-10 05:48:19 +00001627
1628 return true;
1629 }
1630
1631 case LookupResult::AmbiguousReference: {
1632 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001633
John McCall6538c932009-10-10 05:48:19 +00001634 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1635 for (; DI != DE; ++DI)
1636 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001637
John McCall6538c932009-10-10 05:48:19 +00001638 return true;
1639 }
1640 }
1641
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001642 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001643 return true;
1644}
Douglas Gregore254f902009-02-04 00:32:51 +00001645
John McCallf24d7bb2010-05-28 18:45:08 +00001646namespace {
1647 struct AssociatedLookup {
1648 AssociatedLookup(Sema &S,
1649 Sema::AssociatedNamespaceSet &Namespaces,
1650 Sema::AssociatedClassSet &Classes)
1651 : S(S), Namespaces(Namespaces), Classes(Classes) {
1652 }
1653
1654 Sema &S;
1655 Sema::AssociatedNamespaceSet &Namespaces;
1656 Sema::AssociatedClassSet &Classes;
1657 };
1658}
1659
Mike Stump11289f42009-09-09 15:08:12 +00001660static void
John McCallf24d7bb2010-05-28 18:45:08 +00001661addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001662
Douglas Gregor8b895222010-04-30 07:08:38 +00001663static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1664 DeclContext *Ctx) {
1665 // Add the associated namespace for this class.
1666
1667 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1668 // be a locally scoped record.
1669
Sebastian Redlbd595762010-08-31 20:53:31 +00001670 // We skip out of inline namespaces. The innermost non-inline namespace
1671 // contains all names of all its nested inline namespaces anyway, so we can
1672 // replace the entire inline namespace tree with its root.
1673 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1674 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00001675 Ctx = Ctx->getParent();
1676
John McCallc7e8e792009-08-07 22:18:02 +00001677 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001678 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001679}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001680
Mike Stump11289f42009-09-09 15:08:12 +00001681// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001682// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001683static void
John McCallf24d7bb2010-05-28 18:45:08 +00001684addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1685 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001686 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001687 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001688 switch (Arg.getKind()) {
1689 case TemplateArgument::Null:
1690 break;
Mike Stump11289f42009-09-09 15:08:12 +00001691
Douglas Gregor197e5f72009-07-08 07:51:57 +00001692 case TemplateArgument::Type:
1693 // [...] the namespaces and classes associated with the types of the
1694 // template arguments provided for template type parameters (excluding
1695 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001696 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001697 break;
Mike Stump11289f42009-09-09 15:08:12 +00001698
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001699 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001700 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00001701 // [...] the namespaces in which any template template arguments are
1702 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001703 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001704 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00001705 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001706 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001707 DeclContext *Ctx = ClassTemplate->getDeclContext();
1708 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001709 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001710 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001711 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001712 }
1713 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001714 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001715
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001716 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001717 case TemplateArgument::Integral:
1718 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001719 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001720 // associated namespaces. ]
1721 break;
Mike Stump11289f42009-09-09 15:08:12 +00001722
Douglas Gregor197e5f72009-07-08 07:51:57 +00001723 case TemplateArgument::Pack:
1724 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1725 PEnd = Arg.pack_end();
1726 P != PEnd; ++P)
John McCallf24d7bb2010-05-28 18:45:08 +00001727 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001728 break;
1729 }
1730}
1731
Douglas Gregore254f902009-02-04 00:32:51 +00001732// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001733// argument-dependent lookup with an argument of class type
1734// (C++ [basic.lookup.koenig]p2).
1735static void
John McCallf24d7bb2010-05-28 18:45:08 +00001736addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1737 CXXRecordDecl *Class) {
1738
1739 // Just silently ignore anything whose name is __va_list_tag.
1740 if (Class->getDeclName() == Result.S.VAListTagName)
1741 return;
1742
Douglas Gregore254f902009-02-04 00:32:51 +00001743 // C++ [basic.lookup.koenig]p2:
1744 // [...]
1745 // -- If T is a class type (including unions), its associated
1746 // classes are: the class itself; the class of which it is a
1747 // member, if any; and its direct and indirect base
1748 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001749 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001750
1751 // Add the class of which it is a member, if any.
1752 DeclContext *Ctx = Class->getDeclContext();
1753 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001754 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001755 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001756 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001757
Douglas Gregore254f902009-02-04 00:32:51 +00001758 // Add the class itself. If we've already seen this class, we don't
1759 // need to visit base classes.
John McCallf24d7bb2010-05-28 18:45:08 +00001760 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00001761 return;
1762
Mike Stump11289f42009-09-09 15:08:12 +00001763 // -- If T is a template-id, its associated namespaces and classes are
1764 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001765 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001766 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001767 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001768 // namespaces in which any template template arguments are defined; and
1769 // the classes in which any member templates used as template template
1770 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001771 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001772 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001773 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1774 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1775 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001776 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001777 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001778 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001779
Douglas Gregor197e5f72009-07-08 07:51:57 +00001780 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1781 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00001782 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001783 }
Mike Stump11289f42009-09-09 15:08:12 +00001784
John McCall67da35c2010-02-04 22:26:26 +00001785 // Only recurse into base classes for complete types.
1786 if (!Class->hasDefinition()) {
1787 // FIXME: we might need to instantiate templates here
1788 return;
1789 }
1790
Douglas Gregore254f902009-02-04 00:32:51 +00001791 // Add direct and indirect base classes along with their associated
1792 // namespaces.
1793 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1794 Bases.push_back(Class);
1795 while (!Bases.empty()) {
1796 // Pop this class off the stack.
1797 Class = Bases.back();
1798 Bases.pop_back();
1799
1800 // Visit the base classes.
1801 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1802 BaseEnd = Class->bases_end();
1803 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001804 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001805 // In dependent contexts, we do ADL twice, and the first time around,
1806 // the base type might be a dependent TemplateSpecializationType, or a
1807 // TemplateTypeParmType. If that happens, simply ignore it.
1808 // FIXME: If we want to support export, we probably need to add the
1809 // namespace of the template in a TemplateSpecializationType, or even
1810 // the classes and namespaces of known non-dependent arguments.
1811 if (!BaseType)
1812 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001813 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001814 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00001815 // Find the associated namespace for this base class.
1816 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00001817 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001818
1819 // Make sure we visit the bases of this base class.
1820 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1821 Bases.push_back(BaseDecl);
1822 }
1823 }
1824 }
1825}
1826
1827// \brief Add the associated classes and namespaces for
1828// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001829// (C++ [basic.lookup.koenig]p2).
1830static void
John McCallf24d7bb2010-05-28 18:45:08 +00001831addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00001832 // C++ [basic.lookup.koenig]p2:
1833 //
1834 // For each argument type T in the function call, there is a set
1835 // of zero or more associated namespaces and a set of zero or more
1836 // associated classes to be considered. The sets of namespaces and
1837 // classes is determined entirely by the types of the function
1838 // arguments (and the namespace of any template template
1839 // argument). Typedef names and using-declarations used to specify
1840 // the types do not contribute to this set. The sets of namespaces
1841 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00001842
John McCall0af3d3b2010-05-28 06:08:54 +00001843 llvm::SmallVector<const Type *, 16> Queue;
1844 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1845
Douglas Gregore254f902009-02-04 00:32:51 +00001846 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00001847 switch (T->getTypeClass()) {
1848
1849#define TYPE(Class, Base)
1850#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1851#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1852#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1853#define ABSTRACT_TYPE(Class, Base)
1854#include "clang/AST/TypeNodes.def"
1855 // T is canonical. We can also ignore dependent types because
1856 // we don't need to do ADL at the definition point, but if we
1857 // wanted to implement template export (or if we find some other
1858 // use for associated classes and namespaces...) this would be
1859 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00001860 break;
Douglas Gregore254f902009-02-04 00:32:51 +00001861
John McCall0af3d3b2010-05-28 06:08:54 +00001862 // -- If T is a pointer to U or an array of U, its associated
1863 // namespaces and classes are those associated with U.
1864 case Type::Pointer:
1865 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1866 continue;
1867 case Type::ConstantArray:
1868 case Type::IncompleteArray:
1869 case Type::VariableArray:
1870 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1871 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001872
John McCall0af3d3b2010-05-28 06:08:54 +00001873 // -- If T is a fundamental type, its associated sets of
1874 // namespaces and classes are both empty.
1875 case Type::Builtin:
1876 break;
1877
1878 // -- If T is a class type (including unions), its associated
1879 // classes are: the class itself; the class of which it is a
1880 // member, if any; and its direct and indirect base
1881 // classes. Its associated namespaces are the namespaces in
1882 // which its associated classes are defined.
1883 case Type::Record: {
1884 CXXRecordDecl *Class
1885 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001886 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00001887 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00001888 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00001889
John McCall0af3d3b2010-05-28 06:08:54 +00001890 // -- If T is an enumeration type, its associated namespace is
1891 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001892 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00001893 // it has no associated class.
1894 case Type::Enum: {
1895 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001896
John McCall0af3d3b2010-05-28 06:08:54 +00001897 DeclContext *Ctx = Enum->getDeclContext();
1898 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001899 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001900
John McCall0af3d3b2010-05-28 06:08:54 +00001901 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001902 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001903
John McCall0af3d3b2010-05-28 06:08:54 +00001904 break;
1905 }
1906
1907 // -- If T is a function type, its associated namespaces and
1908 // classes are those associated with the function parameter
1909 // types and those associated with the return type.
1910 case Type::FunctionProto: {
1911 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1912 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1913 ArgEnd = Proto->arg_type_end();
1914 Arg != ArgEnd; ++Arg)
1915 Queue.push_back(Arg->getTypePtr());
1916 // fallthrough
1917 }
1918 case Type::FunctionNoProto: {
1919 const FunctionType *FnType = cast<FunctionType>(T);
1920 T = FnType->getResultType().getTypePtr();
1921 continue;
1922 }
1923
1924 // -- If T is a pointer to a member function of a class X, its
1925 // associated namespaces and classes are those associated
1926 // with the function parameter types and return type,
1927 // together with those associated with X.
1928 //
1929 // -- If T is a pointer to a data member of class X, its
1930 // associated namespaces and classes are those associated
1931 // with the member type together with those associated with
1932 // X.
1933 case Type::MemberPointer: {
1934 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1935
1936 // Queue up the class type into which this points.
1937 Queue.push_back(MemberPtr->getClass());
1938
1939 // And directly continue with the pointee type.
1940 T = MemberPtr->getPointeeType().getTypePtr();
1941 continue;
1942 }
1943
1944 // As an extension, treat this like a normal pointer.
1945 case Type::BlockPointer:
1946 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1947 continue;
1948
1949 // References aren't covered by the standard, but that's such an
1950 // obvious defect that we cover them anyway.
1951 case Type::LValueReference:
1952 case Type::RValueReference:
1953 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1954 continue;
1955
1956 // These are fundamental types.
1957 case Type::Vector:
1958 case Type::ExtVector:
1959 case Type::Complex:
1960 break;
1961
1962 // These are ignored by ADL.
1963 case Type::ObjCObject:
1964 case Type::ObjCInterface:
1965 case Type::ObjCObjectPointer:
1966 break;
1967 }
1968
1969 if (Queue.empty()) break;
1970 T = Queue.back();
1971 Queue.pop_back();
Douglas Gregore254f902009-02-04 00:32:51 +00001972 }
Douglas Gregore254f902009-02-04 00:32:51 +00001973}
1974
1975/// \brief Find the associated classes and namespaces for
1976/// argument-dependent lookup for a call with the given set of
1977/// arguments.
1978///
1979/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00001980/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00001981/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00001982void
Douglas Gregore254f902009-02-04 00:32:51 +00001983Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1984 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001985 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001986 AssociatedNamespaces.clear();
1987 AssociatedClasses.clear();
1988
John McCallf24d7bb2010-05-28 18:45:08 +00001989 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
1990
Douglas Gregore254f902009-02-04 00:32:51 +00001991 // C++ [basic.lookup.koenig]p2:
1992 // For each argument type T in the function call, there is a set
1993 // of zero or more associated namespaces and a set of zero or more
1994 // associated classes to be considered. The sets of namespaces and
1995 // classes is determined entirely by the types of the function
1996 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00001997 // argument).
Douglas Gregore254f902009-02-04 00:32:51 +00001998 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1999 Expr *Arg = Args[ArgIdx];
2000
2001 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002002 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002003 continue;
2004 }
2005
2006 // [...] In addition, if the argument is the name or address of a
2007 // set of overloaded functions and/or function templates, its
2008 // associated classes and namespaces are the union of those
2009 // associated with each of the members of the set: the namespace
2010 // in which the function or function template is defined and the
2011 // classes and namespaces associated with its (non-dependent)
2012 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002013 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002014 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002015 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002016 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002017
John McCallf24d7bb2010-05-28 18:45:08 +00002018 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2019 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002020
John McCallf24d7bb2010-05-28 18:45:08 +00002021 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2022 I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002023 // Look through any using declarations to find the underlying function.
2024 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002025
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002026 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2027 if (!FDecl)
2028 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002029
2030 // Add the classes and namespaces associated with the parameter
2031 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002032 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002033 }
2034 }
2035}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002036
2037/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2038/// an acceptable non-member overloaded operator for a call whose
2039/// arguments have types T1 (and, if non-empty, T2). This routine
2040/// implements the check in C++ [over.match.oper]p3b2 concerning
2041/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00002042static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002043IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2044 QualType T1, QualType T2,
2045 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00002046 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2047 return true;
2048
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002049 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2050 return true;
2051
John McCall9dd450b2009-09-21 23:43:11 +00002052 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002053 if (Proto->getNumArgs() < 1)
2054 return false;
2055
2056 if (T1->isEnumeralType()) {
2057 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002058 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002059 return true;
2060 }
2061
2062 if (Proto->getNumArgs() < 2)
2063 return false;
2064
2065 if (!T2.isNull() && T2->isEnumeralType()) {
2066 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002067 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002068 return true;
2069 }
2070
2071 return false;
2072}
2073
John McCall5cebab12009-11-18 07:57:50 +00002074NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002075 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002076 LookupNameKind NameKind,
2077 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002078 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002079 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002080 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002081}
2082
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002083/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002084ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002085 SourceLocation IdLoc) {
2086 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2087 LookupObjCProtocolName);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002088 return cast_or_null<ObjCProtocolDecl>(D);
2089}
2090
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002091void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002092 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002093 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002094 // C++ [over.match.oper]p3:
2095 // -- The set of non-member candidates is the result of the
2096 // unqualified lookup of operator@ in the context of the
2097 // expression according to the usual rules for name lookup in
2098 // unqualified function calls (3.4.2) except that all member
2099 // functions are ignored. However, if no operand has a class
2100 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00002101 // that have a first parameter of type T1 or "reference to
2102 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002103 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00002104 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002105 // when T2 is an enumeration type, are candidate functions.
2106 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002107 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2108 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002109
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002110 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2111
John McCall9f3059a2009-10-09 21:13:30 +00002112 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002113 return;
2114
2115 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2116 Op != OpEnd; ++Op) {
Douglas Gregor645d76f2010-04-25 20:25:43 +00002117 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2118 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002119 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor645d76f2010-04-25 20:25:43 +00002120 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00002121 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor645d76f2010-04-25 20:25:43 +00002122 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor15448f82009-06-27 21:05:07 +00002123 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00002124 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00002125 // later?
2126 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor645d76f2010-04-25 20:25:43 +00002127 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor15448f82009-06-27 21:05:07 +00002128 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002129 }
2130}
2131
Douglas Gregor52b72822010-07-02 23:12:18 +00002132/// \brief Look up the constructors for the given class.
2133DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Douglas Gregora6d69502010-07-02 23:41:54 +00002134 // If the copy constructor has not yet been declared, do so now.
Douglas Gregor9672f922010-07-03 00:47:00 +00002135 if (CanDeclareSpecialMemberFunction(Context, Class)) {
2136 if (!Class->hasDeclaredDefaultConstructor())
2137 DeclareImplicitDefaultConstructor(Class);
2138 if (!Class->hasDeclaredCopyConstructor())
2139 DeclareImplicitCopyConstructor(Class);
2140 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002141
Douglas Gregor52b72822010-07-02 23:12:18 +00002142 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2143 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2144 return Class->lookup(Name);
2145}
2146
Douglas Gregore71edda2010-07-01 22:47:18 +00002147/// \brief Look for the destructor of the given class.
2148///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002149/// During semantic analysis, this routine should be used in lieu of
Douglas Gregore71edda2010-07-01 22:47:18 +00002150/// CXXRecordDecl::getDestructor().
2151///
2152/// \returns The destructor for this class.
2153CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +00002154 // If the destructor has not yet been declared, do so now.
2155 if (CanDeclareSpecialMemberFunction(Context, Class) &&
2156 !Class->hasDeclaredDestructor())
2157 DeclareImplicitDestructor(Class);
2158
Douglas Gregore71edda2010-07-01 22:47:18 +00002159 return Class->getDestructor();
2160}
2161
John McCall8fe68082010-01-26 07:16:45 +00002162void ADLResult::insert(NamedDecl *New) {
2163 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2164
2165 // If we haven't yet seen a decl for this key, or the last decl
2166 // was exactly this one, we're done.
2167 if (Old == 0 || Old == New) {
2168 Old = New;
2169 return;
2170 }
2171
2172 // Otherwise, decide which is a more recent redeclaration.
2173 FunctionDecl *OldFD, *NewFD;
2174 if (isa<FunctionTemplateDecl>(New)) {
2175 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2176 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2177 } else {
2178 OldFD = cast<FunctionDecl>(Old);
2179 NewFD = cast<FunctionDecl>(New);
2180 }
2181
2182 FunctionDecl *Cursor = NewFD;
2183 while (true) {
2184 Cursor = Cursor->getPreviousDeclaration();
2185
2186 // If we got to the end without finding OldFD, OldFD is the newer
2187 // declaration; leave things as they are.
2188 if (!Cursor) return;
2189
2190 // If we do find OldFD, then NewFD is newer.
2191 if (Cursor == OldFD) break;
2192
2193 // Otherwise, keep looking.
2194 }
2195
2196 Old = New;
2197}
2198
Sebastian Redlc057f422009-10-23 19:23:15 +00002199void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002200 Expr **Args, unsigned NumArgs,
John McCall8fe68082010-01-26 07:16:45 +00002201 ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002202 // Find all of the associated namespaces and classes based on the
2203 // arguments we have.
2204 AssociatedNamespaceSet AssociatedNamespaces;
2205 AssociatedClassSet AssociatedClasses;
Mike Stump11289f42009-09-09 15:08:12 +00002206 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCallc7e8e792009-08-07 22:18:02 +00002207 AssociatedNamespaces,
2208 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002209
Sebastian Redlc057f422009-10-23 19:23:15 +00002210 QualType T1, T2;
2211 if (Operator) {
2212 T1 = Args[0]->getType();
2213 if (NumArgs >= 2)
2214 T2 = Args[1]->getType();
2215 }
2216
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002217 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002218 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2219 // and let Y be the lookup set produced by argument dependent
2220 // lookup (defined as follows). If X contains [...] then Y is
2221 // empty. Otherwise Y is the set of declarations found in the
2222 // namespaces associated with the argument types as described
2223 // below. The set of declarations found by the lookup of the name
2224 // is the union of X and Y.
2225 //
2226 // Here, we compute Y and add its members to the overloaded
2227 // candidate set.
2228 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00002229 NSEnd = AssociatedNamespaces.end();
2230 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002231 // When considering an associated namespace, the lookup is the
2232 // same as the lookup performed when the associated namespace is
2233 // used as a qualifier (3.4.3.2) except that:
2234 //
2235 // -- Any using-directives in the associated namespace are
2236 // ignored.
2237 //
John McCallc7e8e792009-08-07 22:18:02 +00002238 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002239 // associated classes are visible within their respective
2240 // namespaces even if they are not visible during an ordinary
2241 // lookup (11.4).
2242 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00002243 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00002244 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00002245 // If the only declaration here is an ordinary friend, consider
2246 // it only if it was declared in an associated classes.
2247 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00002248 DeclContext *LexDC = D->getLexicalDeclContext();
2249 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2250 continue;
2251 }
Mike Stump11289f42009-09-09 15:08:12 +00002252
John McCall91f61fc2010-01-26 06:04:06 +00002253 if (isa<UsingShadowDecl>(D))
2254 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002255
John McCall91f61fc2010-01-26 06:04:06 +00002256 if (isa<FunctionDecl>(D)) {
2257 if (Operator &&
2258 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2259 T1, T2, Context))
2260 continue;
John McCall8fe68082010-01-26 07:16:45 +00002261 } else if (!isa<FunctionTemplateDecl>(D))
2262 continue;
2263
2264 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002265 }
2266 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002267}
Douglas Gregor2d435302009-12-30 17:04:44 +00002268
2269//----------------------------------------------------------------------------
2270// Search for all visible declarations.
2271//----------------------------------------------------------------------------
2272VisibleDeclConsumer::~VisibleDeclConsumer() { }
2273
2274namespace {
2275
2276class ShadowContextRAII;
2277
2278class VisibleDeclsRecord {
2279public:
2280 /// \brief An entry in the shadow map, which is optimized to store a
2281 /// single declaration (the common case) but can also store a list
2282 /// of declarations.
2283 class ShadowMapEntry {
2284 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002285
Douglas Gregor2d435302009-12-30 17:04:44 +00002286 /// \brief Contains either the solitary NamedDecl * or a vector
2287 /// of declarations.
2288 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2289
2290 public:
2291 ShadowMapEntry() : DeclOrVector() { }
2292
2293 void Add(NamedDecl *ND);
2294 void Destroy();
2295
2296 // Iteration.
2297 typedef NamedDecl **iterator;
2298 iterator begin();
2299 iterator end();
2300 };
2301
2302private:
2303 /// \brief A mapping from declaration names to the declarations that have
2304 /// this name within a particular scope.
2305 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2306
2307 /// \brief A list of shadow maps, which is used to model name hiding.
2308 std::list<ShadowMap> ShadowMaps;
2309
2310 /// \brief The declaration contexts we have already visited.
2311 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2312
2313 friend class ShadowContextRAII;
2314
2315public:
2316 /// \brief Determine whether we have already visited this context
2317 /// (and, if not, note that we are going to visit that context now).
2318 bool visitedContext(DeclContext *Ctx) {
2319 return !VisitedContexts.insert(Ctx);
2320 }
2321
Douglas Gregor39982192010-08-15 06:18:01 +00002322 bool alreadyVisitedContext(DeclContext *Ctx) {
2323 return VisitedContexts.count(Ctx);
2324 }
2325
Douglas Gregor2d435302009-12-30 17:04:44 +00002326 /// \brief Determine whether the given declaration is hidden in the
2327 /// current scope.
2328 ///
2329 /// \returns the declaration that hides the given declaration, or
2330 /// NULL if no such declaration exists.
2331 NamedDecl *checkHidden(NamedDecl *ND);
2332
2333 /// \brief Add a declaration to the current shadow map.
2334 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2335};
2336
2337/// \brief RAII object that records when we've entered a shadow context.
2338class ShadowContextRAII {
2339 VisibleDeclsRecord &Visible;
2340
2341 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2342
2343public:
2344 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2345 Visible.ShadowMaps.push_back(ShadowMap());
2346 }
2347
2348 ~ShadowContextRAII() {
2349 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2350 EEnd = Visible.ShadowMaps.back().end();
2351 E != EEnd;
2352 ++E)
2353 E->second.Destroy();
2354
2355 Visible.ShadowMaps.pop_back();
2356 }
2357};
2358
2359} // end anonymous namespace
2360
2361void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2362 if (DeclOrVector.isNull()) {
2363 // 0 - > 1 elements: just set the single element information.
2364 DeclOrVector = ND;
2365 return;
2366 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002367
Douglas Gregor2d435302009-12-30 17:04:44 +00002368 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2369 // 1 -> 2 elements: create the vector of results and push in the
2370 // existing declaration.
2371 DeclVector *Vec = new DeclVector;
2372 Vec->push_back(PrevND);
2373 DeclOrVector = Vec;
2374 }
2375
2376 // Add the new element to the end of the vector.
2377 DeclOrVector.get<DeclVector*>()->push_back(ND);
2378}
2379
2380void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2381 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2382 delete Vec;
2383 DeclOrVector = ((NamedDecl *)0);
2384 }
2385}
2386
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002387VisibleDeclsRecord::ShadowMapEntry::iterator
Douglas Gregor2d435302009-12-30 17:04:44 +00002388VisibleDeclsRecord::ShadowMapEntry::begin() {
2389 if (DeclOrVector.isNull())
2390 return 0;
2391
2392 if (DeclOrVector.dyn_cast<NamedDecl *>())
2393 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
2394
2395 return DeclOrVector.get<DeclVector *>()->begin();
2396}
2397
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002398VisibleDeclsRecord::ShadowMapEntry::iterator
Douglas Gregor2d435302009-12-30 17:04:44 +00002399VisibleDeclsRecord::ShadowMapEntry::end() {
2400 if (DeclOrVector.isNull())
2401 return 0;
2402
2403 if (DeclOrVector.dyn_cast<NamedDecl *>())
2404 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2405
2406 return DeclOrVector.get<DeclVector *>()->end();
2407}
2408
2409NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002410 // Look through using declarations.
2411 ND = ND->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002412
Douglas Gregor2d435302009-12-30 17:04:44 +00002413 unsigned IDNS = ND->getIdentifierNamespace();
2414 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2415 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2416 SM != SMEnd; ++SM) {
2417 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2418 if (Pos == SM->end())
2419 continue;
2420
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002421 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor2d435302009-12-30 17:04:44 +00002422 IEnd = Pos->second.end();
2423 I != IEnd; ++I) {
2424 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +00002425 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002426 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00002427 Decl::IDNS_ObjCProtocol)))
2428 continue;
2429
2430 // Protocols are in distinct namespaces from everything else.
2431 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2432 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2433 (*I)->getIdentifierNamespace() != IDNS)
2434 continue;
2435
Douglas Gregor09bbc652010-01-14 15:47:35 +00002436 // Functions and function templates in the same scope overload
2437 // rather than hide. FIXME: Look for hiding based on function
2438 // signatures!
Douglas Gregor200c99d2010-01-14 03:35:48 +00002439 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002440 ND->isFunctionOrFunctionTemplate() &&
2441 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002442 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002443
Douglas Gregor2d435302009-12-30 17:04:44 +00002444 // We've found a declaration that hides this one.
2445 return *I;
2446 }
2447 }
2448
2449 return 0;
2450}
2451
2452static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2453 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002454 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002455 VisibleDeclConsumer &Consumer,
2456 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002457 if (!Ctx)
2458 return;
2459
Douglas Gregor2d435302009-12-30 17:04:44 +00002460 // Make sure we don't visit the same context twice.
2461 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2462 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002463
Douglas Gregor7454c562010-07-02 20:37:36 +00002464 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2465 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2466
Douglas Gregor2d435302009-12-30 17:04:44 +00002467 // Enumerate all of the results in this context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002468 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
Douglas Gregor2d435302009-12-30 17:04:44 +00002469 CurCtx = CurCtx->getNextContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002470 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
Douglas Gregor2d435302009-12-30 17:04:44 +00002471 DEnd = CurCtx->decls_end();
2472 D != DEnd; ++D) {
Douglas Gregora3b23b02010-12-09 21:44:02 +00002473 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002474 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002475 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002476 Visited.add(ND);
2477 }
Douglas Gregora3b23b02010-12-09 21:44:02 +00002478 } else if (ObjCForwardProtocolDecl *ForwardProto
2479 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
2480 for (ObjCForwardProtocolDecl::protocol_iterator
2481 P = ForwardProto->protocol_begin(),
2482 PEnd = ForwardProto->protocol_end();
2483 P != PEnd;
2484 ++P) {
2485 if (Result.isAcceptableDecl(*P)) {
2486 Consumer.FoundDecl(*P, Visited.checkHidden(*P), InBaseClass);
2487 Visited.add(*P);
2488 }
2489 }
Douglas Gregor04246572011-02-16 01:39:26 +00002490 } else if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D)) {
2491 for (ObjCClassDecl::iterator I = Class->begin(), IEnd = Class->end();
2492 I != IEnd; ++I) {
2493 ObjCInterfaceDecl *IFace = I->getInterface();
2494 if (Result.isAcceptableDecl(IFace)) {
2495 Consumer.FoundDecl(IFace, Visited.checkHidden(IFace), InBaseClass);
2496 Visited.add(IFace);
2497 }
2498 }
Douglas Gregora3b23b02010-12-09 21:44:02 +00002499 }
Douglas Gregor04246572011-02-16 01:39:26 +00002500
Sebastian Redlbd595762010-08-31 20:53:31 +00002501 // Visit transparent contexts and inline namespaces inside this context.
Douglas Gregor2d435302009-12-30 17:04:44 +00002502 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
Sebastian Redlbd595762010-08-31 20:53:31 +00002503 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Douglas Gregor09bbc652010-01-14 15:47:35 +00002504 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002505 Consumer, Visited);
2506 }
2507 }
2508 }
2509
2510 // Traverse using directives for qualified name lookup.
2511 if (QualifiedNameLookup) {
2512 ShadowContextRAII Shadow(Visited);
2513 DeclContext::udir_iterator I, E;
2514 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002515 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002516 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002517 }
2518 }
2519
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002520 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00002521 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00002522 if (!Record->hasDefinition())
2523 return;
2524
Douglas Gregor2d435302009-12-30 17:04:44 +00002525 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2526 BEnd = Record->bases_end();
2527 B != BEnd; ++B) {
2528 QualType BaseType = B->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002529
Douglas Gregor2d435302009-12-30 17:04:44 +00002530 // Don't look into dependent bases, because name lookup can't look
2531 // there anyway.
2532 if (BaseType->isDependentType())
2533 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002534
Douglas Gregor2d435302009-12-30 17:04:44 +00002535 const RecordType *Record = BaseType->getAs<RecordType>();
2536 if (!Record)
2537 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002538
Douglas Gregor2d435302009-12-30 17:04:44 +00002539 // FIXME: It would be nice to be able to determine whether referencing
2540 // a particular member would be ambiguous. For example, given
2541 //
2542 // struct A { int member; };
2543 // struct B { int member; };
2544 // struct C : A, B { };
2545 //
2546 // void f(C *c) { c->### }
2547 //
2548 // accessing 'member' would result in an ambiguity. However, we
2549 // could be smart enough to qualify the member with the base
2550 // class, e.g.,
2551 //
2552 // c->B::member
2553 //
2554 // or
2555 //
2556 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002557
Douglas Gregor2d435302009-12-30 17:04:44 +00002558 // Find results in this base class (and its bases).
2559 ShadowContextRAII Shadow(Visited);
2560 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002561 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002562 }
2563 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002564
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002565 // Traverse the contexts of Objective-C classes.
2566 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2567 // Traverse categories.
2568 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2569 Category; Category = Category->getNextClassCategory()) {
2570 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002571 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002572 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002573 }
2574
2575 // Traverse protocols.
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002576 for (ObjCInterfaceDecl::all_protocol_iterator
2577 I = IFace->all_referenced_protocol_begin(),
2578 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002579 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002580 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002581 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002582 }
2583
2584 // Traverse the superclass.
2585 if (IFace->getSuperClass()) {
2586 ShadowContextRAII Shadow(Visited);
2587 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002588 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002589 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002590
Douglas Gregor0b59e802010-04-19 18:02:19 +00002591 // If there is an implementation, traverse it. We do this to find
2592 // synthesized ivars.
2593 if (IFace->getImplementation()) {
2594 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002595 LookupVisibleDecls(IFace->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00002596 QualifiedNameLookup, true, Consumer, Visited);
2597 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002598 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2599 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2600 E = Protocol->protocol_end(); I != E; ++I) {
2601 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002602 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002603 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002604 }
2605 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2606 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2607 E = Category->protocol_end(); I != E; ++I) {
2608 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002609 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002610 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002611 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002612
Douglas Gregor0b59e802010-04-19 18:02:19 +00002613 // If there is an implementation, traverse it.
2614 if (Category->getImplementation()) {
2615 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002616 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00002617 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002618 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002619 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002620}
2621
2622static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2623 UnqualUsingDirectiveSet &UDirs,
2624 VisibleDeclConsumer &Consumer,
2625 VisibleDeclsRecord &Visited) {
2626 if (!S)
2627 return;
2628
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002629 if (!S->getEntity() ||
2630 (!S->getParent() &&
Douglas Gregor39982192010-08-15 06:18:01 +00002631 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002632 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2633 // Walk through the declarations in this Scope.
2634 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2635 D != DEnd; ++D) {
John McCall48871652010-08-21 09:40:31 +00002636 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002637 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002638 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002639 Visited.add(ND);
2640 }
2641 }
2642 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002643
Douglas Gregor66230062010-03-15 14:33:29 +00002644 // FIXME: C++ [temp.local]p8
Douglas Gregor2d435302009-12-30 17:04:44 +00002645 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00002646 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002647 // Look into this scope's declaration context, along with any of its
2648 // parent lookup contexts (e.g., enclosing classes), up to the point
2649 // where we hit the context stored in the next outer scope.
2650 Entity = (DeclContext *)S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00002651 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002652
Douglas Gregorea166062010-03-15 15:26:48 +00002653 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00002654 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002655 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2656 if (Method->isInstanceMethod()) {
2657 // For instance methods, look for ivars in the method's interface.
2658 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2659 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00002660 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002661 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002662 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002663
Douglas Gregor05fcf842010-11-02 20:36:02 +00002664 // Look for properties from which we can synthesize ivars, if
2665 // permitted.
2666 if (Result.getSema().getLangOptions().ObjCNonFragileABI2 &&
2667 IFace->getImplementation() &&
2668 Result.getLookupKind() == Sema::LookupOrdinaryName) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002669 for (ObjCInterfaceDecl::prop_iterator
Douglas Gregor05fcf842010-11-02 20:36:02 +00002670 P = IFace->prop_begin(),
2671 PEnd = IFace->prop_end();
2672 P != PEnd; ++P) {
2673 if (Result.getSema().canSynthesizeProvisionalIvar(*P) &&
2674 !IFace->lookupInstanceVariable((*P)->getIdentifier())) {
2675 Consumer.FoundDecl(*P, Visited.checkHidden(*P), false);
2676 Visited.add(*P);
2677 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002678 }
2679 }
Douglas Gregor05fcf842010-11-02 20:36:02 +00002680 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002681 }
2682
2683 // We've already performed all of the name lookup that we need
2684 // to for Objective-C methods; the next context will be the
2685 // outer scope.
2686 break;
2687 }
2688
Douglas Gregor2d435302009-12-30 17:04:44 +00002689 if (Ctx->isFunctionOrMethod())
2690 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002691
2692 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002693 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002694 }
2695 } else if (!S->getParent()) {
2696 // Look into the translation unit scope. We walk through the translation
2697 // unit's declaration context, because the Scope itself won't have all of
2698 // the declarations if we loaded a precompiled header.
2699 // FIXME: We would like the translation unit's Scope object to point to the
2700 // translation unit, so we don't need this special "if" branch. However,
2701 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002702 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00002703 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002704 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00002705 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002706 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002707 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002708 }
2709
Douglas Gregor2d435302009-12-30 17:04:44 +00002710 if (Entity) {
2711 // Lookup visible declarations in any namespaces found by using
2712 // directives.
2713 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2714 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2715 for (; UI != UEnd; ++UI)
2716 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002717 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002718 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002719 }
2720
2721 // Lookup names in the parent scope.
2722 ShadowContextRAII Shadow(Visited);
2723 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2724}
2725
2726void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00002727 VisibleDeclConsumer &Consumer,
2728 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002729 // Determine the set of using directives available during
2730 // unqualified name lookup.
2731 Scope *Initial = S;
2732 UnqualUsingDirectiveSet UDirs;
2733 if (getLangOptions().CPlusPlus) {
2734 // Find the first namespace or translation-unit scope.
2735 while (S && !isNamespaceOrTranslationUnitScope(S))
2736 S = S->getParent();
2737
2738 UDirs.visitScopeChain(Initial, S);
2739 }
2740 UDirs.done();
2741
2742 // Look for visible declarations.
2743 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2744 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00002745 if (!IncludeGlobalScope)
2746 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00002747 ShadowContextRAII Shadow(Visited);
2748 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2749}
2750
2751void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00002752 VisibleDeclConsumer &Consumer,
2753 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002754 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2755 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00002756 if (!IncludeGlobalScope)
2757 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00002758 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002759 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002760 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002761}
2762
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002763LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc) {
2764 // Do a lookup to see if we have a label with this name already.
2765 NamedDecl *Res = LookupSingleName(CurScope, II, Loc, LookupLabel,
2766 NotForRedeclaration);
2767 // If we found a label, check to see if it is in the same context as us. When
2768 // in a Block, we don't want to reuse a label in an enclosing function.
2769 if (Res && Res->getDeclContext() != CurContext)
2770 Res = 0;
2771
2772 if (Res == 0) {
2773 // If not forward referenced or defined already, create the backing decl.
2774 Res = LabelDecl::Create(Context, CurContext, Loc, II);
2775 PushOnScopeChains(Res, CurScope->getFnParent(), true);
2776 }
2777
2778 return cast<LabelDecl>(Res);
2779}
2780
2781//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00002782// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002783//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00002784
2785namespace {
2786class TypoCorrectionConsumer : public VisibleDeclConsumer {
2787 /// \brief The name written that is a typo in the source.
2788 llvm::StringRef Typo;
2789
2790 /// \brief The results found that have the smallest edit distance
2791 /// found (so far) with the typo name.
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002792 ///
2793 /// The boolean value indicates whether there is a keyword with this name.
2794 llvm::StringMap<bool, llvm::BumpPtrAllocator> BestResults;
Douglas Gregor2d435302009-12-30 17:04:44 +00002795
2796 /// \brief The best edit distance found so far.
2797 unsigned BestEditDistance;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002798
Douglas Gregor2d435302009-12-30 17:04:44 +00002799public:
2800 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002801 : Typo(Typo->getName()),
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002802 BestEditDistance((std::numeric_limits<unsigned>::max)()) { }
Douglas Gregor2d435302009-12-30 17:04:44 +00002803
Douglas Gregor09bbc652010-01-14 15:47:35 +00002804 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregor57756ea2010-10-14 22:11:03 +00002805 void FoundName(llvm::StringRef Name);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002806 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
Douglas Gregor2d435302009-12-30 17:04:44 +00002807
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002808 typedef llvm::StringMap<bool, llvm::BumpPtrAllocator>::iterator iterator;
2809 iterator begin() { return BestResults.begin(); }
2810 iterator end() { return BestResults.end(); }
2811 void erase(iterator I) { BestResults.erase(I); }
2812 unsigned size() const { return BestResults.size(); }
2813 bool empty() const { return BestResults.empty(); }
Douglas Gregor2d435302009-12-30 17:04:44 +00002814
Douglas Gregoraf9eb592010-10-15 13:35:25 +00002815 bool &operator[](llvm::StringRef Name) {
2816 return BestResults[Name];
2817 }
2818
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002819 unsigned getBestEditDistance() const { return BestEditDistance; }
Douglas Gregor2d435302009-12-30 17:04:44 +00002820};
2821
2822}
2823
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002824void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002825 bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002826 // Don't consider hidden names for typo correction.
2827 if (Hiding)
2828 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002829
Douglas Gregor2d435302009-12-30 17:04:44 +00002830 // Only consider entities with identifiers for names, ignoring
2831 // special names (constructors, overloaded operators, selectors,
2832 // etc.).
2833 IdentifierInfo *Name = ND->getIdentifier();
2834 if (!Name)
2835 return;
2836
Douglas Gregor57756ea2010-10-14 22:11:03 +00002837 FoundName(Name->getName());
2838}
2839
2840void TypoCorrectionConsumer::FoundName(llvm::StringRef Name) {
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00002841 using namespace std;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002842
Douglas Gregor93910a52010-10-19 19:39:10 +00002843 // Use a simple length-based heuristic to determine the minimum possible
2844 // edit distance. If the minimum isn't good enough, bail out early.
2845 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
2846 if (MinED > BestEditDistance || (MinED && Typo.size() / MinED < 3))
2847 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002848
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00002849 // Compute an upper bound on the allowable edit distance, so that the
2850 // edit-distance algorithm can short-circuit.
2851 unsigned UpperBound = min(unsigned((Typo.size() + 2) / 3), BestEditDistance);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002852
Douglas Gregor2d435302009-12-30 17:04:44 +00002853 // Compute the edit distance between the typo and the name of this
2854 // entity. If this edit distance is not worse than the best edit
2855 // distance we've seen so far, add it to the list of results.
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00002856 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
Douglas Gregor57756ea2010-10-14 22:11:03 +00002857 if (ED == 0)
2858 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002859
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002860 if (ED < BestEditDistance) {
2861 // This result is better than any we've seen before; clear out
2862 // the previous results.
2863 BestResults.clear();
Douglas Gregor2d435302009-12-30 17:04:44 +00002864 BestEditDistance = ED;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002865 } else if (ED > BestEditDistance) {
2866 // This result is worse than the best results we've seen so far;
2867 // ignore it.
2868 return;
2869 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002870
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002871 // Add this name to the list of results. By not assigning a value, we
2872 // keep the current value if we've seen this name before (either as a
2873 // keyword or as a declaration), or get the default value (not a keyword)
2874 // if we haven't seen it before.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002875 (void)BestResults[Name];
Douglas Gregor2d435302009-12-30 17:04:44 +00002876}
2877
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002878void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002879 llvm::StringRef Keyword) {
2880 // Compute the edit distance between the typo and this keyword.
2881 // If this edit distance is not worse than the best edit
2882 // distance we've seen so far, add it to the list of results.
2883 unsigned ED = Typo.edit_distance(Keyword);
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002884 if (ED < BestEditDistance) {
2885 BestResults.clear();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002886 BestEditDistance = ED;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002887 } else if (ED > BestEditDistance) {
2888 // This result is worse than the best results we've seen so far;
2889 // ignore it.
2890 return;
2891 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002892
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002893 BestResults[Keyword] = true;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002894}
2895
Douglas Gregord507d772010-10-20 03:06:34 +00002896/// \brief Perform name lookup for a possible result for typo correction.
2897static void LookupPotentialTypoResult(Sema &SemaRef,
2898 LookupResult &Res,
2899 IdentifierInfo *Name,
2900 Scope *S, CXXScopeSpec *SS,
2901 DeclContext *MemberContext,
2902 bool EnteringContext,
2903 Sema::CorrectTypoContext CTC) {
2904 Res.suppressDiagnostics();
2905 Res.clear();
2906 Res.setLookupName(Name);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002907 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00002908 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
2909 if (CTC == Sema::CTC_ObjCIvarLookup) {
2910 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
2911 Res.addDecl(Ivar);
2912 Res.resolveKind();
2913 return;
2914 }
2915 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002916
Douglas Gregord507d772010-10-20 03:06:34 +00002917 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
2918 Res.addDecl(Prop);
2919 Res.resolveKind();
2920 return;
2921 }
2922 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002923
Douglas Gregord507d772010-10-20 03:06:34 +00002924 SemaRef.LookupQualifiedName(Res, MemberContext);
2925 return;
2926 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002927
2928 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00002929 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002930
Douglas Gregord507d772010-10-20 03:06:34 +00002931 // Fake ivar lookup; this should really be part of
2932 // LookupParsedName.
2933 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2934 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002935 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00002936 (Res.isSingleResult() &&
2937 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002938 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00002939 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
2940 Res.addDecl(IV);
2941 Res.resolveKind();
2942 }
2943 }
2944 }
2945}
2946
Douglas Gregor2d435302009-12-30 17:04:44 +00002947/// \brief Try to "correct" a typo in the source code by finding
2948/// visible declarations whose names are similar to the name that was
2949/// present in the source code.
2950///
2951/// \param Res the \c LookupResult structure that contains the name
2952/// that was present in the source code along with the name-lookup
2953/// criteria used to search for the name. On success, this structure
2954/// will contain the results of name lookup.
2955///
2956/// \param S the scope in which name lookup occurs.
2957///
2958/// \param SS the nested-name-specifier that precedes the name we're
2959/// looking for, if present.
2960///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002961/// \param MemberContext if non-NULL, the context in which to look for
2962/// a member access expression.
2963///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002964/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00002965/// the nested-name-specifier SS.
2966///
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002967/// \param CTC The context in which typo correction occurs, which impacts the
2968/// set of keywords permitted.
2969///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002970/// \param OPT when non-NULL, the search for visible declarations will
2971/// also walk the protocols in the qualified interfaces of \p OPT.
2972///
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002973/// \returns the corrected name if the typo was corrected, otherwise returns an
2974/// empty \c DeclarationName. When a typo was corrected, the result structure
2975/// may contain the results of name lookup for the correct name or it may be
2976/// empty.
2977DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002978 DeclContext *MemberContext,
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002979 bool EnteringContext,
2980 CorrectTypoContext CTC,
2981 const ObjCObjectPointerType *OPT) {
Douglas Gregor8ed0c0b2010-07-09 17:35:33 +00002982 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002983 return DeclarationName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002984
Douglas Gregor2d435302009-12-30 17:04:44 +00002985 // We only attempt to correct typos for identifiers.
2986 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2987 if (!Typo)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002988 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002989
2990 // If the scope specifier itself was invalid, don't try to correct
2991 // typos.
2992 if (SS && SS->isInvalid())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002993 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002994
2995 // Never try to correct typos during template deduction or
2996 // instantiation.
2997 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002998 return DeclarationName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002999
Douglas Gregor2d435302009-12-30 17:04:44 +00003000 TypoCorrectionConsumer Consumer(Typo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003001
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003002 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor87074f12010-10-20 01:32:02 +00003003 bool IsUnqualifiedLookup = false;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003004 if (MemberContext) {
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003005 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003006
3007 // Look in qualified interfaces.
3008 if (OPT) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003009 for (ObjCObjectPointerType::qual_iterator
3010 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003011 I != E; ++I)
3012 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
3013 }
3014 } else if (SS && SS->isSet()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003015 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
3016 if (!DC)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003017 return DeclarationName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003018
Douglas Gregor87074f12010-10-20 01:32:02 +00003019 // Provide a stop gap for files that are just seriously broken. Trying
3020 // to correct all typos can turn into a HUGE performance penalty, causing
3021 // some files to take minutes to get rejected by the parser.
3022 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
3023 return DeclarationName();
3024 ++TyposCorrected;
3025
Douglas Gregor2d435302009-12-30 17:04:44 +00003026 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
3027 } else {
Douglas Gregor87074f12010-10-20 01:32:02 +00003028 IsUnqualifiedLookup = true;
3029 UnqualifiedTyposCorrectedMap::iterator Cached
3030 = UnqualifiedTyposCorrected.find(Typo);
3031 if (Cached == UnqualifiedTyposCorrected.end()) {
3032 // Provide a stop gap for files that are just seriously broken. Trying
3033 // to correct all typos can turn into a HUGE performance penalty, causing
3034 // some files to take minutes to get rejected by the parser.
3035 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
3036 return DeclarationName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003037
Douglas Gregor87074f12010-10-20 01:32:02 +00003038 // For unqualified lookup, look through all of the names that we have
3039 // seen in this translation unit.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003040 for (IdentifierTable::iterator I = Context.Idents.begin(),
Douglas Gregor87074f12010-10-20 01:32:02 +00003041 IEnd = Context.Idents.end();
3042 I != IEnd; ++I)
3043 Consumer.FoundName(I->getKey());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003044
Douglas Gregor87074f12010-10-20 01:32:02 +00003045 // Walk through identifiers in external identifier sources.
3046 if (IdentifierInfoLookup *External
Douglas Gregor57756ea2010-10-14 22:11:03 +00003047 = Context.Idents.getExternalIdentifierLookup()) {
Ted Kremenekb4ea9a82010-11-07 06:11:33 +00003048 llvm::OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Douglas Gregor87074f12010-10-20 01:32:02 +00003049 do {
3050 llvm::StringRef Name = Iter->Next();
3051 if (Name.empty())
3052 break;
Douglas Gregor57756ea2010-10-14 22:11:03 +00003053
Douglas Gregor87074f12010-10-20 01:32:02 +00003054 Consumer.FoundName(Name);
3055 } while (true);
3056 }
3057 } else {
3058 // Use the cached value, unless it's a keyword. In the keyword case, we'll
3059 // end up adding the keyword below.
3060 if (Cached->second.first.empty())
3061 return DeclarationName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003062
Douglas Gregor87074f12010-10-20 01:32:02 +00003063 if (!Cached->second.second)
3064 Consumer.FoundName(Cached->second.first);
Douglas Gregor57756ea2010-10-14 22:11:03 +00003065 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003066 }
3067
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003068 // Add context-dependent keywords.
3069 bool WantTypeSpecifiers = false;
3070 bool WantExpressionKeywords = false;
3071 bool WantCXXNamedCasts = false;
3072 bool WantRemainingKeywords = false;
3073 switch (CTC) {
3074 case CTC_Unknown:
3075 WantTypeSpecifiers = true;
3076 WantExpressionKeywords = true;
3077 WantCXXNamedCasts = true;
3078 WantRemainingKeywords = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003079
Douglas Gregor5fd04d42010-05-18 16:14:23 +00003080 if (ObjCMethodDecl *Method = getCurMethodDecl())
3081 if (Method->getClassInterface() &&
3082 Method->getClassInterface()->getSuperClass())
3083 Consumer.addKeywordResult(Context, "super");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003084
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003085 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003086
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003087 case CTC_NoKeywords:
3088 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003089
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003090 case CTC_Type:
3091 WantTypeSpecifiers = true;
3092 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003093
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003094 case CTC_ObjCMessageReceiver:
3095 Consumer.addKeywordResult(Context, "super");
3096 // Fall through to handle message receivers like expressions.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003097
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003098 case CTC_Expression:
3099 if (getLangOptions().CPlusPlus)
3100 WantTypeSpecifiers = true;
3101 WantExpressionKeywords = true;
3102 // Fall through to get C++ named casts.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003103
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003104 case CTC_CXXCasts:
3105 WantCXXNamedCasts = true;
3106 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003107
Douglas Gregord507d772010-10-20 03:06:34 +00003108 case CTC_ObjCPropertyLookup:
3109 // FIXME: Add "isa"?
3110 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003111
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003112 case CTC_MemberLookup:
3113 if (getLangOptions().CPlusPlus)
3114 Consumer.addKeywordResult(Context, "template");
3115 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003116
Douglas Gregord507d772010-10-20 03:06:34 +00003117 case CTC_ObjCIvarLookup:
3118 break;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003119 }
3120
3121 if (WantTypeSpecifiers) {
3122 // Add type-specifier keywords to the set of results.
3123 const char *CTypeSpecs[] = {
3124 "char", "const", "double", "enum", "float", "int", "long", "short",
3125 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
3126 "_Complex", "_Imaginary",
3127 // storage-specifiers as well
3128 "extern", "inline", "static", "typedef"
3129 };
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003130
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003131 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3132 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3133 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003134
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003135 if (getLangOptions().C99)
3136 Consumer.addKeywordResult(Context, "restrict");
3137 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
3138 Consumer.addKeywordResult(Context, "bool");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003139
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003140 if (getLangOptions().CPlusPlus) {
3141 Consumer.addKeywordResult(Context, "class");
3142 Consumer.addKeywordResult(Context, "typename");
3143 Consumer.addKeywordResult(Context, "wchar_t");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003144
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003145 if (getLangOptions().CPlusPlus0x) {
3146 Consumer.addKeywordResult(Context, "char16_t");
3147 Consumer.addKeywordResult(Context, "char32_t");
3148 Consumer.addKeywordResult(Context, "constexpr");
3149 Consumer.addKeywordResult(Context, "decltype");
3150 Consumer.addKeywordResult(Context, "thread_local");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003151 }
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003152 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003153
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003154 if (getLangOptions().GNUMode)
3155 Consumer.addKeywordResult(Context, "typeof");
3156 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003157
Douglas Gregor86ad0852010-05-18 16:30:22 +00003158 if (WantCXXNamedCasts && getLangOptions().CPlusPlus) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003159 Consumer.addKeywordResult(Context, "const_cast");
3160 Consumer.addKeywordResult(Context, "dynamic_cast");
3161 Consumer.addKeywordResult(Context, "reinterpret_cast");
3162 Consumer.addKeywordResult(Context, "static_cast");
3163 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003164
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003165 if (WantExpressionKeywords) {
3166 Consumer.addKeywordResult(Context, "sizeof");
3167 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
3168 Consumer.addKeywordResult(Context, "false");
3169 Consumer.addKeywordResult(Context, "true");
3170 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003171
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003172 if (getLangOptions().CPlusPlus) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003173 const char *CXXExprs[] = {
3174 "delete", "new", "operator", "throw", "typeid"
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003175 };
3176 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3177 for (unsigned I = 0; I != NumCXXExprs; ++I)
3178 Consumer.addKeywordResult(Context, CXXExprs[I]);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003179
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003180 if (isa<CXXMethodDecl>(CurContext) &&
3181 cast<CXXMethodDecl>(CurContext)->isInstance())
3182 Consumer.addKeywordResult(Context, "this");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003183
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003184 if (getLangOptions().CPlusPlus0x) {
3185 Consumer.addKeywordResult(Context, "alignof");
3186 Consumer.addKeywordResult(Context, "nullptr");
3187 }
3188 }
3189 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003190
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003191 if (WantRemainingKeywords) {
3192 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
3193 // Statements.
3194 const char *CStmts[] = {
3195 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3196 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3197 for (unsigned I = 0; I != NumCStmts; ++I)
3198 Consumer.addKeywordResult(Context, CStmts[I]);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003199
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003200 if (getLangOptions().CPlusPlus) {
3201 Consumer.addKeywordResult(Context, "catch");
3202 Consumer.addKeywordResult(Context, "try");
3203 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003204
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003205 if (S && S->getBreakParent())
3206 Consumer.addKeywordResult(Context, "break");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003207
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003208 if (S && S->getContinueParent())
3209 Consumer.addKeywordResult(Context, "continue");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003210
John McCallaab3e412010-08-25 08:40:02 +00003211 if (!getCurFunction()->SwitchStack.empty()) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003212 Consumer.addKeywordResult(Context, "case");
3213 Consumer.addKeywordResult(Context, "default");
3214 }
3215 } else {
3216 if (getLangOptions().CPlusPlus) {
3217 Consumer.addKeywordResult(Context, "namespace");
3218 Consumer.addKeywordResult(Context, "template");
3219 }
3220
3221 if (S && S->isClassScope()) {
3222 Consumer.addKeywordResult(Context, "explicit");
3223 Consumer.addKeywordResult(Context, "friend");
3224 Consumer.addKeywordResult(Context, "mutable");
3225 Consumer.addKeywordResult(Context, "private");
3226 Consumer.addKeywordResult(Context, "protected");
3227 Consumer.addKeywordResult(Context, "public");
3228 Consumer.addKeywordResult(Context, "virtual");
3229 }
3230 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003231
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003232 if (getLangOptions().CPlusPlus) {
3233 Consumer.addKeywordResult(Context, "using");
3234
3235 if (getLangOptions().CPlusPlus0x)
3236 Consumer.addKeywordResult(Context, "static_assert");
3237 }
3238 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003239
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003240 // If we haven't found anything, we're done.
Douglas Gregor87074f12010-10-20 01:32:02 +00003241 if (Consumer.empty()) {
3242 // If this was an unqualified lookup, note that no correction was found.
3243 if (IsUnqualifiedLookup)
3244 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003245
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003246 return DeclarationName();
Douglas Gregor87074f12010-10-20 01:32:02 +00003247 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003248
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003249 // Make sure that the user typed at least 3 characters for each correction
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003250 // made. Otherwise, we don't even both looking at the results.
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00003251
3252 // We also suppress exact matches; those should be handled by a
3253 // different mechanism (e.g., one that introduces qualification in
3254 // C++).
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003255 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregor87074f12010-10-20 01:32:02 +00003256 if (ED > 0 && Typo->getName().size() / ED < 3) {
3257 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregoraf1daa92010-10-27 14:20:34 +00003258 if (IsUnqualifiedLookup)
Douglas Gregor87074f12010-10-20 01:32:02 +00003259 (void)UnqualifiedTyposCorrected[Typo];
3260
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003261 return DeclarationName();
Douglas Gregor87074f12010-10-20 01:32:02 +00003262 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003263
3264 // Weed out any names that could not be found by name lookup.
Douglas Gregor26c55782010-10-15 16:49:56 +00003265 bool LastLookupWasAccepted = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003266 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003267 IEnd = Consumer.end();
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003268 I != IEnd; /* Increment in loop. */) {
3269 // Keywords are always found.
3270 if (I->second) {
3271 ++I;
3272 continue;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003273 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003274
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003275 // Perform name lookup on this name.
3276 IdentifierInfo *Name = &Context.Idents.get(I->getKey());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003277 LookupPotentialTypoResult(*this, Res, Name, S, SS, MemberContext,
Douglas Gregord507d772010-10-20 03:06:34 +00003278 EnteringContext, CTC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003279
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003280 switch (Res.getResultKind()) {
3281 case LookupResult::NotFound:
3282 case LookupResult::NotFoundInCurrentInstantiation:
3283 case LookupResult::Ambiguous:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003284 // We didn't find this name in our scope, or didn't like what we found;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003285 // ignore it.
3286 Res.suppressDiagnostics();
3287 {
3288 TypoCorrectionConsumer::iterator Next = I;
3289 ++Next;
3290 Consumer.erase(I);
3291 I = Next;
3292 }
Douglas Gregor26c55782010-10-15 16:49:56 +00003293 LastLookupWasAccepted = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003294 break;
3295
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003296 case LookupResult::Found:
3297 case LookupResult::FoundOverloaded:
3298 case LookupResult::FoundUnresolvedValue:
3299 ++I;
Douglas Gregord507d772010-10-20 03:06:34 +00003300 LastLookupWasAccepted = true;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003301 break;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003302 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003303
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003304 if (Res.isAmbiguous()) {
3305 // We don't deal with ambiguities.
3306 Res.suppressDiagnostics();
3307 Res.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003308 return DeclarationName();
3309 }
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003310 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003311
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003312 // If only a single name remains, return that result.
Douglas Gregor26c55782010-10-15 16:49:56 +00003313 if (Consumer.size() == 1) {
3314 IdentifierInfo *Name = &Context.Idents.get(Consumer.begin()->getKey());
Douglas Gregor1f32ebe2010-10-20 01:01:57 +00003315 if (Consumer.begin()->second) {
3316 Res.suppressDiagnostics();
3317 Res.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003318
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00003319 // Don't correct to a keyword that's the same as the typo; the keyword
3320 // wasn't actually in scope.
3321 if (ED == 0) {
3322 Res.setLookupName(Typo);
3323 return DeclarationName();
3324 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003325
Douglas Gregor1f32ebe2010-10-20 01:01:57 +00003326 } else if (!LastLookupWasAccepted) {
Douglas Gregor26c55782010-10-15 16:49:56 +00003327 // Perform name lookup on this name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003328 LookupPotentialTypoResult(*this, Res, Name, S, SS, MemberContext,
Douglas Gregord507d772010-10-20 03:06:34 +00003329 EnteringContext, CTC);
Douglas Gregor26c55782010-10-15 16:49:56 +00003330 }
3331
Douglas Gregor87074f12010-10-20 01:32:02 +00003332 // Record the correction for unqualified lookup.
3333 if (IsUnqualifiedLookup)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003334 UnqualifiedTyposCorrected[Typo]
Douglas Gregord507d772010-10-20 03:06:34 +00003335 = std::make_pair(Name->getName(), Consumer.begin()->second);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003336
3337 return &Context.Idents.get(Consumer.begin()->getKey());
Douglas Gregor26c55782010-10-15 16:49:56 +00003338 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003339 else if (Consumer.size() > 1 && CTC == CTC_ObjCMessageReceiver
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003340 && Consumer["super"]) {
3341 // Prefix 'super' when we're completing in a message-receiver
3342 // context.
3343 Res.suppressDiagnostics();
3344 Res.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003345
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00003346 // Don't correct to a keyword that's the same as the typo; the keyword
3347 // wasn't actually in scope.
3348 if (ED == 0) {
3349 Res.setLookupName(Typo);
3350 return DeclarationName();
3351 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003352
Douglas Gregor87074f12010-10-20 01:32:02 +00003353 // Record the correction for unqualified lookup.
3354 if (IsUnqualifiedLookup)
3355 UnqualifiedTyposCorrected[Typo]
Douglas Gregord507d772010-10-20 03:06:34 +00003356 = std::make_pair("super", Consumer.begin()->second);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003357
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003358 return &Context.Idents.get("super");
3359 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003360
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003361 Res.suppressDiagnostics();
3362 Res.setLookupName(Typo);
Douglas Gregor2d435302009-12-30 17:04:44 +00003363 Res.clear();
Douglas Gregor87074f12010-10-20 01:32:02 +00003364 // Record the correction for unqualified lookup.
3365 if (IsUnqualifiedLookup)
3366 (void)UnqualifiedTyposCorrected[Typo];
3367
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003368 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00003369}