blob: e09ec66457eb062e8d2ea72b37f4c6db8d1395e6 [file] [log] [blame]
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
Douglas Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
John McCall2d887082010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Lookup.h"
Sean Hunt308742c2011-06-04 04:32:43 +000017#include "clang/Sema/Overload.h"
John McCall19510852010-08-20 18:27:03 +000018#include "clang/Sema/DeclSpec.h"
John McCall5f1e0942010-08-24 08:50:51 +000019#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000020#include "clang/Sema/ScopeInfo.h"
John McCall2a7fb272010-08-25 05:32:35 +000021#include "clang/Sema/TemplateDeduction.h"
Axel Naumannf8291a12011-02-24 16:47:47 +000022#include "clang/Sema/ExternalSemaSource.h"
Douglas Gregor7176fff2009-01-15 00:26:24 +000023#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000024#include "clang/AST/CXXInheritance.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000025#include "clang/AST/Decl.h"
26#include "clang/AST/DeclCXX.h"
27#include "clang/AST/DeclObjC.h"
Douglas Gregor42af25f2009-05-11 19:58:34 +000028#include "clang/AST/DeclTemplate.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000029#include "clang/AST/Expr.h"
Douglas Gregordaa439a2009-07-08 10:57:20 +000030#include "clang/AST/ExprCXX.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000031#include "clang/Basic/Builtins.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000032#include "clang/Basic/LangOptions.h"
John McCall50df6ae2010-08-25 07:03:20 +000033#include "llvm/ADT/DenseSet.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000034#include "llvm/ADT/STLExtras.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000035#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregore24b5752010-10-14 20:34:08 +000036#include "llvm/ADT/StringMap.h"
John McCall6e247262009-10-10 05:48:19 +000037#include "llvm/Support/ErrorHandling.h"
Douglas Gregore24b5752010-10-14 20:34:08 +000038#include <limits>
Douglas Gregor546be3c2009-12-30 17:04:44 +000039#include <list>
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +000040#include <set>
Douglas Gregor2a3009a2009-02-03 19:21:40 +000041#include <vector>
42#include <iterator>
43#include <utility>
44#include <algorithm>
Douglas Gregoreb11cd02009-01-14 22:20:51 +000045
46using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000047using namespace sema;
Douglas Gregoreb11cd02009-01-14 22:20:51 +000048
John McCalld7be78a2009-11-10 07:01:13 +000049namespace {
50 class UnqualUsingEntry {
51 const DeclContext *Nominated;
52 const DeclContext *CommonAncestor;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000053
John McCalld7be78a2009-11-10 07:01:13 +000054 public:
55 UnqualUsingEntry(const DeclContext *Nominated,
56 const DeclContext *CommonAncestor)
57 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
58 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000059
John McCalld7be78a2009-11-10 07:01:13 +000060 const DeclContext *getCommonAncestor() const {
61 return CommonAncestor;
62 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000063
John McCalld7be78a2009-11-10 07:01:13 +000064 const DeclContext *getNominatedNamespace() const {
65 return Nominated;
66 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000067
John McCalld7be78a2009-11-10 07:01:13 +000068 // Sort by the pointer value of the common ancestor.
69 struct Comparator {
70 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
71 return L.getCommonAncestor() < R.getCommonAncestor();
72 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000073
John McCalld7be78a2009-11-10 07:01:13 +000074 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
75 return E.getCommonAncestor() < DC;
76 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000077
John McCalld7be78a2009-11-10 07:01:13 +000078 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
79 return DC < E.getCommonAncestor();
80 }
81 };
82 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +000083
John McCalld7be78a2009-11-10 07:01:13 +000084 /// A collection of using directives, as used by C++ unqualified
85 /// lookup.
86 class UnqualUsingDirectiveSet {
87 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000088
John McCalld7be78a2009-11-10 07:01:13 +000089 ListTy list;
90 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000091
John McCalld7be78a2009-11-10 07:01:13 +000092 public:
93 UnqualUsingDirectiveSet() {}
Douglas Gregor2a3009a2009-02-03 19:21:40 +000094
John McCalld7be78a2009-11-10 07:01:13 +000095 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000096 // C++ [namespace.udir]p1:
John McCalld7be78a2009-11-10 07:01:13 +000097 // During unqualified name lookup, the names appear as if they
98 // were declared in the nearest enclosing namespace which contains
99 // both the using-directive and the nominated namespace.
100 DeclContext *InnermostFileDC
101 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
102 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000103
John McCalld7be78a2009-11-10 07:01:13 +0000104 for (; S; S = S->getParent()) {
John McCalld7be78a2009-11-10 07:01:13 +0000105 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
106 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
107 visit(Ctx, EffectiveDC);
108 } else {
109 Scope::udir_iterator I = S->using_directives_begin(),
110 End = S->using_directives_end();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000111
John McCalld7be78a2009-11-10 07:01:13 +0000112 for (; I != End; ++I)
John McCalld226f652010-08-21 09:40:31 +0000113 visit(*I, InnermostFileDC);
John McCalld7be78a2009-11-10 07:01:13 +0000114 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000115 }
116 }
John McCalld7be78a2009-11-10 07:01:13 +0000117
118 // Visits a context and collect all of its using directives
119 // recursively. Treats all using directives as if they were
120 // declared in the context.
121 //
122 // A given context is only every visited once, so it is important
123 // that contexts be visited from the inside out in order to get
124 // the effective DCs right.
125 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
126 if (!visited.insert(DC))
127 return;
128
129 addUsingDirectives(DC, EffectiveDC);
130 }
131
132 // Visits a using directive and collects all of its using
133 // directives recursively. Treats all using directives as if they
134 // were declared in the effective DC.
135 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
136 DeclContext *NS = UD->getNominatedNamespace();
137 if (!visited.insert(NS))
138 return;
139
140 addUsingDirective(UD, EffectiveDC);
141 addUsingDirectives(NS, EffectiveDC);
142 }
143
144 // Adds all the using directives in a context (and those nominated
145 // by its using directives, transitively) as if they appeared in
146 // the given effective context.
147 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
148 llvm::SmallVector<DeclContext*,4> queue;
149 while (true) {
150 DeclContext::udir_iterator I, End;
151 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
152 UsingDirectiveDecl *UD = *I;
153 DeclContext *NS = UD->getNominatedNamespace();
154 if (visited.insert(NS)) {
155 addUsingDirective(UD, EffectiveDC);
156 queue.push_back(NS);
157 }
158 }
159
160 if (queue.empty())
161 return;
162
163 DC = queue.back();
164 queue.pop_back();
165 }
166 }
167
168 // Add a using directive as if it had been declared in the given
169 // context. This helps implement C++ [namespace.udir]p3:
170 // The using-directive is transitive: if a scope contains a
171 // using-directive that nominates a second namespace that itself
172 // contains using-directives, the effect is as if the
173 // using-directives from the second namespace also appeared in
174 // the first.
175 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
176 // Find the common ancestor between the effective context and
177 // the nominated namespace.
178 DeclContext *Common = UD->getNominatedNamespace();
179 while (!Common->Encloses(EffectiveDC))
180 Common = Common->getParent();
John McCall12ea5782009-11-10 09:20:04 +0000181 Common = Common->getPrimaryContext();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000182
John McCalld7be78a2009-11-10 07:01:13 +0000183 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
184 }
185
186 void done() {
187 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
188 }
189
John McCalld7be78a2009-11-10 07:01:13 +0000190 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000191
John McCalld7be78a2009-11-10 07:01:13 +0000192 const_iterator begin() const { return list.begin(); }
193 const_iterator end() const { return list.end(); }
194
195 std::pair<const_iterator,const_iterator>
196 getNamespacesFor(DeclContext *DC) const {
John McCall12ea5782009-11-10 09:20:04 +0000197 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCalld7be78a2009-11-10 07:01:13 +0000198 UnqualUsingEntry::Comparator());
199 }
200 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000201}
202
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000203// Retrieve the set of identifier namespaces that correspond to a
204// specific kind of name lookup.
John McCall1d7c5282009-12-18 10:40:03 +0000205static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
206 bool CPlusPlus,
207 bool Redeclaration) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000208 unsigned IDNS = 0;
209 switch (NameKind) {
210 case Sema::LookupOrdinaryName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000211 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000212 IDNS = Decl::IDNS_Ordinary;
John McCall1d7c5282009-12-18 10:40:03 +0000213 if (CPlusPlus) {
John McCall0d6b1642010-04-23 18:46:30 +0000214 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattner337e5502011-02-18 01:27:55 +0000215 if (Redeclaration)
216 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCall1d7c5282009-12-18 10:40:03 +0000217 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000218 break;
219
John McCall76d32642010-04-24 01:30:58 +0000220 case Sema::LookupOperatorName:
221 // Operator lookup is its own crazy thing; it is not the same
222 // as (e.g.) looking up an operator name for redeclaration.
223 assert(!Redeclaration && "cannot do redeclaration operator lookup");
224 IDNS = Decl::IDNS_NonMemberOperator;
225 break;
226
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000227 case Sema::LookupTagName:
John McCall0d6b1642010-04-23 18:46:30 +0000228 if (CPlusPlus) {
229 IDNS = Decl::IDNS_Type;
230
231 // When looking for a redeclaration of a tag name, we add:
232 // 1) TagFriend to find undeclared friend decls
233 // 2) Namespace because they can't "overload" with tag decls.
234 // 3) Tag because it includes class templates, which can't
235 // "overload" with tag decls.
236 if (Redeclaration)
237 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
238 } else {
239 IDNS = Decl::IDNS_Tag;
240 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000241 break;
Chris Lattner337e5502011-02-18 01:27:55 +0000242 case Sema::LookupLabel:
243 IDNS = Decl::IDNS_Label;
244 break;
245
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000246 case Sema::LookupMemberName:
247 IDNS = Decl::IDNS_Member;
248 if (CPlusPlus)
Mike Stump1eb44332009-09-09 15:08:12 +0000249 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000250 break;
251
252 case Sema::LookupNestedNameSpecifierName:
John McCall0d6b1642010-04-23 18:46:30 +0000253 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
254 break;
255
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000256 case Sema::LookupNamespaceName:
John McCall0d6b1642010-04-23 18:46:30 +0000257 IDNS = Decl::IDNS_Namespace;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000258 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000259
John McCall9f54ad42009-12-10 09:41:52 +0000260 case Sema::LookupUsingDeclName:
261 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
262 | Decl::IDNS_Member | Decl::IDNS_Using;
263 break;
264
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000265 case Sema::LookupObjCProtocolName:
266 IDNS = Decl::IDNS_ObjCProtocol;
267 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000268
Douglas Gregor8071e422010-08-15 06:18:01 +0000269 case Sema::LookupAnyName:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000270 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor8071e422010-08-15 06:18:01 +0000271 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
272 | Decl::IDNS_Type;
273 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000274 }
275 return IDNS;
276}
277
John McCall1d7c5282009-12-18 10:40:03 +0000278void LookupResult::configure() {
Chris Lattner337e5502011-02-18 01:27:55 +0000279 IDNS = getIDNS(LookupKind, SemaRef.getLangOptions().CPlusPlus,
John McCall1d7c5282009-12-18 10:40:03 +0000280 isForRedeclaration());
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000281
282 // If we're looking for one of the allocation or deallocation
283 // operators, make sure that the implicitly-declared new and delete
284 // operators can be found.
285 if (!isForRedeclaration()) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000286 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000287 case OO_New:
288 case OO_Delete:
289 case OO_Array_New:
290 case OO_Array_Delete:
291 SemaRef.DeclareGlobalNewDelete();
292 break;
293
294 default:
295 break;
296 }
297 }
John McCall1d7c5282009-12-18 10:40:03 +0000298}
299
John McCall2a7fb272010-08-25 05:32:35 +0000300void LookupResult::sanity() const {
301 assert(ResultKind != NotFound || Decls.size() == 0);
302 assert(ResultKind != Found || Decls.size() == 1);
303 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
304 (Decls.size() == 1 &&
305 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
306 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
307 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorf17b58c2010-10-22 22:08:47 +0000308 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
309 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall2a7fb272010-08-25 05:32:35 +0000310 assert((Paths != NULL) == (ResultKind == Ambiguous &&
311 (Ambiguity == AmbiguousBaseSubobjectTypes ||
312 Ambiguity == AmbiguousBaseSubobjects)));
313}
John McCall2a7fb272010-08-25 05:32:35 +0000314
John McCallf36e02d2009-10-09 21:13:30 +0000315// Necessary because CXXBasePaths is not complete in Sema.h
John McCall7d384dd2009-11-18 07:57:50 +0000316void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCallf36e02d2009-10-09 21:13:30 +0000317 delete Paths;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000318}
319
John McCall7453ed42009-11-22 00:44:51 +0000320/// Resolves the result kind of this lookup.
John McCall7d384dd2009-11-18 07:57:50 +0000321void LookupResult::resolveKind() {
John McCallf36e02d2009-10-09 21:13:30 +0000322 unsigned N = Decls.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000323
John McCallf36e02d2009-10-09 21:13:30 +0000324 // Fast case: no possible ambiguity.
John McCall68263142009-11-18 22:49:29 +0000325 if (N == 0) {
John McCalldc5c7862010-01-15 21:27:01 +0000326 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall68263142009-11-18 22:49:29 +0000327 return;
328 }
329
John McCall7453ed42009-11-22 00:44:51 +0000330 // If there's a single decl, we need to examine it to decide what
331 // kind of lookup this is.
John McCall7ba107a2009-11-18 02:36:19 +0000332 if (N == 1) {
Douglas Gregor2b147f02010-04-25 21:15:30 +0000333 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
334 if (isa<FunctionTemplateDecl>(D))
John McCall7453ed42009-11-22 00:44:51 +0000335 ResultKind = FoundOverloaded;
Douglas Gregor2b147f02010-04-25 21:15:30 +0000336 else if (isa<UnresolvedUsingValueDecl>(D))
John McCall7ba107a2009-11-18 02:36:19 +0000337 ResultKind = FoundUnresolvedValue;
338 return;
339 }
John McCallf36e02d2009-10-09 21:13:30 +0000340
John McCall6e247262009-10-10 05:48:19 +0000341 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000342 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000343
John McCallf36e02d2009-10-09 21:13:30 +0000344 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000345 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000346
John McCallf36e02d2009-10-09 21:13:30 +0000347 bool Ambiguous = false;
348 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000349 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000350
351 unsigned UniqueTagIndex = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000352
John McCallf36e02d2009-10-09 21:13:30 +0000353 unsigned I = 0;
354 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000355 NamedDecl *D = Decls[I]->getUnderlyingDecl();
356 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000357
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000358 // Redeclarations of types via typedef can occur both within a scope
359 // and, through using declarations and directives, across scopes. There is
360 // no ambiguity if they all refer to the same type, so unique based on the
361 // canonical type.
362 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
363 if (!TD->getDeclContext()->isRecord()) {
364 QualType T = SemaRef.Context.getTypeDeclType(TD);
365 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
366 // The type is not unique; pull something off the back and continue
367 // at this index.
368 Decls[I] = Decls[--N];
369 continue;
370 }
371 }
372 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000373
John McCall314be4e2009-11-17 07:50:12 +0000374 if (!Unique.insert(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000375 // If it's not unique, pull something off the back (and
376 // continue at this index).
377 Decls[I] = Decls[--N];
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000378 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000379 }
380
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000381 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000382
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000383 if (isa<UnresolvedUsingValueDecl>(D)) {
384 HasUnresolved = true;
385 } else if (isa<TagDecl>(D)) {
386 if (HasTag)
387 Ambiguous = true;
388 UniqueTagIndex = I;
389 HasTag = true;
390 } else if (isa<FunctionTemplateDecl>(D)) {
391 HasFunction = true;
392 HasFunctionTemplate = true;
393 } else if (isa<FunctionDecl>(D)) {
394 HasFunction = true;
395 } else {
396 if (HasNonFunction)
397 Ambiguous = true;
398 HasNonFunction = true;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000399 }
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000400 I++;
Mike Stump1eb44332009-09-09 15:08:12 +0000401 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000402
John McCallf36e02d2009-10-09 21:13:30 +0000403 // C++ [basic.scope.hiding]p2:
404 // A class name or enumeration name can be hidden by the name of
405 // an object, function, or enumerator declared in the same
406 // scope. If a class or enumeration name and an object, function,
407 // or enumerator are declared in the same scope (in any order)
408 // with the same name, the class or enumeration name is hidden
409 // wherever the object, function, or enumerator name is visible.
410 // But it's still an error if there are distinct tag types found,
411 // even if they're not visible. (ref?)
John McCallfda8e122009-12-03 00:58:24 +0000412 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregor77a1a882010-10-23 16:06:17 +0000413 (HasFunction || HasNonFunction || HasUnresolved)) {
414 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
415 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
416 Decls[UniqueTagIndex] = Decls[--N];
417 else
418 Ambiguous = true;
419 }
Anders Carlsson8b50d012009-06-26 03:37:05 +0000420
John McCallf36e02d2009-10-09 21:13:30 +0000421 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000422
John McCallfda8e122009-12-03 00:58:24 +0000423 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000424 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000425
John McCallf36e02d2009-10-09 21:13:30 +0000426 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000427 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000428 else if (HasUnresolved)
429 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000430 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000431 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000432 else
John McCalla24dc2e2009-11-17 02:14:36 +0000433 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000434}
435
John McCall7d384dd2009-11-18 07:57:50 +0000436void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall6b2accb2010-02-10 09:31:12 +0000437 CXXBasePaths::const_paths_iterator I, E;
John McCallf36e02d2009-10-09 21:13:30 +0000438 DeclContext::lookup_iterator DI, DE;
439 for (I = P.begin(), E = P.end(); I != E; ++I)
440 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
441 addDecl(*DI);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000442}
443
John McCall7d384dd2009-11-18 07:57:50 +0000444void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000445 Paths = new CXXBasePaths;
446 Paths->swap(P);
447 addDeclsFromBasePaths(*Paths);
448 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000449 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000450}
451
John McCall7d384dd2009-11-18 07:57:50 +0000452void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000453 Paths = new CXXBasePaths;
454 Paths->swap(P);
455 addDeclsFromBasePaths(*Paths);
456 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000457 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000458}
459
John McCall7d384dd2009-11-18 07:57:50 +0000460void LookupResult::print(llvm::raw_ostream &Out) {
John McCallf36e02d2009-10-09 21:13:30 +0000461 Out << Decls.size() << " result(s)";
462 if (isAmbiguous()) Out << ", ambiguous";
463 if (Paths) Out << ", base paths present";
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000464
John McCallf36e02d2009-10-09 21:13:30 +0000465 for (iterator I = begin(), E = end(); I != E; ++I) {
466 Out << "\n";
467 (*I)->print(Out, 2);
468 }
469}
470
Douglas Gregor85910982010-02-12 05:48:04 +0000471/// \brief Lookup a builtin function, when name lookup would otherwise
472/// fail.
473static bool LookupBuiltin(Sema &S, LookupResult &R) {
474 Sema::LookupNameKind NameKind = R.getLookupKind();
475
476 // If we didn't find a use of this identifier, and if the identifier
477 // corresponds to a compiler builtin, create the decl object for the builtin
478 // now, injecting it into translation unit scope, and return it.
479 if (NameKind == Sema::LookupOrdinaryName ||
480 NameKind == Sema::LookupRedeclarationWithLinkage) {
481 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
482 if (II) {
483 // If this is a builtin on this (or all) targets, create the decl.
484 if (unsigned BuiltinID = II->getBuiltinID()) {
485 // In C++, we don't have any predefined library functions like
486 // 'malloc'. Instead, we'll just error.
487 if (S.getLangOptions().CPlusPlus &&
488 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
489 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000490
491 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
492 BuiltinID, S.TUScope,
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000493 R.isForRedeclaration(),
494 R.getNameLoc())) {
Douglas Gregor85910982010-02-12 05:48:04 +0000495 R.addDecl(D);
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000496 return true;
497 }
498
499 if (R.isForRedeclaration()) {
500 // If we're redeclaring this function anyway, forget that
501 // this was a builtin at all.
502 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
503 }
504
505 return false;
Douglas Gregor85910982010-02-12 05:48:04 +0000506 }
507 }
508 }
509
510 return false;
511}
512
Douglas Gregor4923aa22010-07-02 20:37:36 +0000513/// \brief Determine whether we can declare a special member function within
514/// the class at this point.
515static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
516 const CXXRecordDecl *Class) {
John McCallb3b50a82010-08-11 23:52:36 +0000517 // Don't do it if the class is invalid.
518 if (Class->isInvalidDecl())
519 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000520
Douglas Gregor4923aa22010-07-02 20:37:36 +0000521 // We need to have a definition for the class.
522 if (!Class->getDefinition() || Class->isDependentContext())
523 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000524
Douglas Gregor4923aa22010-07-02 20:37:36 +0000525 // We can't be in the middle of defining the class.
526 if (const RecordType *RecordTy
527 = Context.getTypeDeclType(Class)->getAs<RecordType>())
528 return !RecordTy->isBeingDefined();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000529
Douglas Gregor4923aa22010-07-02 20:37:36 +0000530 return false;
531}
532
533void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregor22584312010-07-02 23:41:54 +0000534 if (!CanDeclareSpecialMemberFunction(Context, Class))
535 return;
Douglas Gregor18274032010-07-03 00:47:00 +0000536
537 // If the default constructor has not yet been declared, do so now.
Sean Huntcdee3fe2011-05-11 22:34:38 +0000538 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +0000539 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000540
Douglas Gregor22584312010-07-02 23:41:54 +0000541 // If the copy constructor has not yet been declared, do so now.
542 if (!Class->hasDeclaredCopyConstructor())
543 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000544
Douglas Gregora376d102010-07-02 21:50:04 +0000545 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000546 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +0000547 DeclareImplicitCopyAssignment(Class);
548
Douglas Gregor4923aa22010-07-02 20:37:36 +0000549 // If the destructor has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000550 if (!Class->hasDeclaredDestructor())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000551 DeclareImplicitDestructor(Class);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000552}
553
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000554/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregora376d102010-07-02 21:50:04 +0000555/// special member function.
556static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
557 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000558 case DeclarationName::CXXConstructorName:
Douglas Gregora376d102010-07-02 21:50:04 +0000559 case DeclarationName::CXXDestructorName:
560 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000561
Douglas Gregora376d102010-07-02 21:50:04 +0000562 case DeclarationName::CXXOperatorName:
563 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000564
Douglas Gregora376d102010-07-02 21:50:04 +0000565 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000566 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000567 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000568
Douglas Gregora376d102010-07-02 21:50:04 +0000569 return false;
570}
571
572/// \brief If there are any implicit member functions with the given name
573/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000574static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregora376d102010-07-02 21:50:04 +0000575 DeclarationName Name,
576 const DeclContext *DC) {
577 if (!DC)
578 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000579
Douglas Gregora376d102010-07-02 21:50:04 +0000580 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000581 case DeclarationName::CXXConstructorName:
582 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor18274032010-07-03 00:47:00 +0000583 if (Record->getDefinition() &&
584 CanDeclareSpecialMemberFunction(S.Context, Record)) {
Sean Huntcdee3fe2011-05-11 22:34:38 +0000585 if (Record->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +0000586 S.DeclareImplicitDefaultConstructor(
587 const_cast<CXXRecordDecl *>(Record));
588 if (!Record->hasDeclaredCopyConstructor())
589 S.DeclareImplicitCopyConstructor(const_cast<CXXRecordDecl *>(Record));
590 }
Douglas Gregor22584312010-07-02 23:41:54 +0000591 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000592
Douglas Gregora376d102010-07-02 21:50:04 +0000593 case DeclarationName::CXXDestructorName:
594 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
595 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
596 CanDeclareSpecialMemberFunction(S.Context, Record))
597 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregora376d102010-07-02 21:50:04 +0000598 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000599
Douglas Gregora376d102010-07-02 21:50:04 +0000600 case DeclarationName::CXXOperatorName:
601 if (Name.getCXXOverloadedOperator() != OO_Equal)
602 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000603
Douglas Gregora376d102010-07-02 21:50:04 +0000604 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
605 if (Record->getDefinition() && !Record->hasDeclaredCopyAssignment() &&
606 CanDeclareSpecialMemberFunction(S.Context, Record))
607 S.DeclareImplicitCopyAssignment(const_cast<CXXRecordDecl *>(Record));
608 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000609
Douglas Gregora376d102010-07-02 21:50:04 +0000610 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000611 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000612 }
613}
Douglas Gregor4923aa22010-07-02 20:37:36 +0000614
John McCallf36e02d2009-10-09 21:13:30 +0000615// Adds all qualifying matches for a name within a decl context to the
616// given lookup result. Returns true if any matches were found.
Douglas Gregor85910982010-02-12 05:48:04 +0000617static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000618 bool Found = false;
619
Douglas Gregor4923aa22010-07-02 20:37:36 +0000620 // Lazily declare C++ special member functions.
Douglas Gregora376d102010-07-02 21:50:04 +0000621 if (S.getLangOptions().CPlusPlus)
622 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000623
Douglas Gregor4923aa22010-07-02 20:37:36 +0000624 // Perform lookup into this declaration context.
John McCalld7be78a2009-11-10 07:01:13 +0000625 DeclContext::lookup_const_iterator I, E;
Douglas Gregor48026d22010-01-11 18:40:55 +0000626 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall46460a62010-01-20 21:53:11 +0000627 NamedDecl *D = *I;
628 if (R.isAcceptableDecl(D)) {
629 R.addDecl(D);
Douglas Gregor48026d22010-01-11 18:40:55 +0000630 Found = true;
631 }
632 }
John McCallf36e02d2009-10-09 21:13:30 +0000633
Douglas Gregor85910982010-02-12 05:48:04 +0000634 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
635 return true;
636
Douglas Gregor48026d22010-01-11 18:40:55 +0000637 if (R.getLookupName().getNameKind()
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000638 != DeclarationName::CXXConversionFunctionName ||
639 R.getLookupName().getCXXNameType()->isDependentType() ||
640 !isa<CXXRecordDecl>(DC))
641 return Found;
642
643 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000644 // A specialization of a conversion function template is not found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000645 // name lookup. Instead, any conversion function templates visible in the
646 // context of the use are considered. [...]
647 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
648 if (!Record->isDefinition())
649 return Found;
650
651 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000652 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000653 UEnd = Unresolved->end(); U != UEnd; ++U) {
654 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
655 if (!ConvTemplate)
656 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000657
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000658 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000659 // add the conversion function template. When we deduce template
660 // arguments for specializations, we'll end up unifying the return
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000661 // type of the new declaration with the type of the function template.
662 if (R.isForRedeclaration()) {
663 R.addDecl(ConvTemplate);
664 Found = true;
665 continue;
666 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000667
Douglas Gregor48026d22010-01-11 18:40:55 +0000668 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000669 // [...] For each such operator, if argument deduction succeeds
670 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000671 // name lookup.
672 //
673 // When referencing a conversion function for any purpose other than
674 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000675 // result), perform template argument deduction and place the
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000676 // specialization into the result set. We do this to avoid forcing all
677 // callers to perform special deduction for conversion functions.
John McCall2a7fb272010-08-25 05:32:35 +0000678 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000679 FunctionDecl *Specialization = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000680
681 const FunctionProtoType *ConvProto
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000682 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
683 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3f477a12010-01-12 01:17:50 +0000684
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000685 // Compute the type of the function that we would expect the conversion
686 // function to have, if it were to match the name given.
687 // FIXME: Calling convention!
John McCalle23cf432010-12-14 08:05:40 +0000688 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
689 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
Sebastian Redl8b5b4092011-03-06 10:52:04 +0000690 EPI.ExceptionSpecType = EST_None;
John McCalle23cf432010-12-14 08:05:40 +0000691 EPI.NumExceptions = 0;
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000692 QualType ExpectedType
693 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
John McCalle23cf432010-12-14 08:05:40 +0000694 0, 0, EPI);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000695
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000696 // Perform template argument deduction against the type that we would
697 // expect the function to have.
698 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
699 Specialization, Info)
700 == Sema::TDK_Success) {
701 R.addDecl(Specialization);
702 Found = true;
Douglas Gregor48026d22010-01-11 18:40:55 +0000703 }
704 }
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000705
John McCallf36e02d2009-10-09 21:13:30 +0000706 return Found;
707}
708
John McCalld7be78a2009-11-10 07:01:13 +0000709// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000710static bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000711CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregor85910982010-02-12 05:48:04 +0000712 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000713
714 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
715
John McCalld7be78a2009-11-10 07:01:13 +0000716 // Perform direct name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +0000717 bool Found = LookupDirect(S, R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000718
John McCalld7be78a2009-11-10 07:01:13 +0000719 // Perform direct name lookup into the namespaces nominated by the
720 // using directives whose common ancestor is this namespace.
721 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
722 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000723
John McCalld7be78a2009-11-10 07:01:13 +0000724 for (; UI != UEnd; ++UI)
Douglas Gregor85910982010-02-12 05:48:04 +0000725 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000726 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000727
728 R.resolveKind();
729
730 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000731}
732
733static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000734 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000735 return Ctx->isFileContext();
736 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000737}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000738
Douglas Gregor711be1e2010-03-15 14:33:29 +0000739// Find the next outer declaration context from this scope. This
740// routine actually returns the semantic outer context, which may
741// differ from the lexical context (encoded directly in the Scope
742// stack) when we are parsing a member of a class template. In this
743// case, the second element of the pair will be true, to indicate that
744// name lookup should continue searching in this semantic context when
745// it leaves the current template parameter scope.
746static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
747 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
748 DeclContext *Lexical = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000749 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor711be1e2010-03-15 14:33:29 +0000750 OuterS = OuterS->getParent()) {
751 if (OuterS->getEntity()) {
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000752 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor711be1e2010-03-15 14:33:29 +0000753 break;
754 }
755 }
756
757 // C++ [temp.local]p8:
758 // In the definition of a member of a class template that appears
759 // outside of the namespace containing the class template
760 // definition, the name of a template-parameter hides the name of
761 // a member of this namespace.
762 //
763 // Example:
764 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000765 // namespace N {
766 // class C { };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000767 //
768 // template<class T> class B {
769 // void f(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000770 // };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000771 // }
772 //
773 // template<class C> void N::B<C>::f(C) {
774 // C b; // C is the template parameter, not N::C
775 // }
776 //
777 // In this example, the lexical context we return is the
778 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000779 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor711be1e2010-03-15 14:33:29 +0000780 !S->getParent()->isTemplateParamScope())
781 return std::make_pair(Lexical, false);
782
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000783 // Find the outermost template parameter scope.
Douglas Gregor711be1e2010-03-15 14:33:29 +0000784 // For the example, this is the scope for the template parameters of
785 // template<class C>.
786 Scope *OutermostTemplateScope = S->getParent();
787 while (OutermostTemplateScope->getParent() &&
788 OutermostTemplateScope->getParent()->isTemplateParamScope())
789 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000790
Douglas Gregor711be1e2010-03-15 14:33:29 +0000791 // Find the namespace context in which the original scope occurs. In
792 // the example, this is namespace N.
793 DeclContext *Semantic = DC;
794 while (!Semantic->isFileContext())
795 Semantic = Semantic->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000796
Douglas Gregor711be1e2010-03-15 14:33:29 +0000797 // Find the declaration context just outside of the template
798 // parameter scope. This is the context in which the template is
799 // being lexically declaration (a namespace context). In the
800 // example, this is the global scope.
801 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
802 Lexical->Encloses(Semantic))
803 return std::make_pair(Semantic, true);
804
805 return std::make_pair(Lexical, false);
Douglas Gregore942bbe2009-09-10 16:57:35 +0000806}
807
John McCalla24dc2e2009-11-17 02:14:36 +0000808bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCall1d7c5282009-12-18 10:40:03 +0000809 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000810
811 DeclarationName Name = R.getLookupName();
812
Douglas Gregora376d102010-07-02 21:50:04 +0000813 // If this is the name of an implicitly-declared special member function,
814 // go through the scope stack to implicitly declare
815 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
816 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
817 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
818 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
819 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000820
Douglas Gregora376d102010-07-02 21:50:04 +0000821 // Implicitly declare member functions with the name we're looking for, if in
822 // fact we are in a scope where it matters.
823
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000824 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000825 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000826 I = IdResolver.begin(Name),
827 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000828
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000829 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000830 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000831 // ...During unqualified name lookup (3.4.1), the names appear as if
832 // they were declared in the nearest enclosing namespace which contains
833 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000834 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000835 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000836 //
837 // For example:
838 // namespace A { int i; }
839 // void foo() {
840 // int i;
841 // {
842 // using namespace A;
843 // ++i; // finds local 'i', A::i appears at global scope
844 // }
845 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000846 //
Douglas Gregor711be1e2010-03-15 14:33:29 +0000847 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000848 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregord2235f62010-05-20 20:58:56 +0000849 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
850
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000851 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000852 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000853 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000854 if (R.isAcceptableDecl(*I)) {
John McCallf36e02d2009-10-09 21:13:30 +0000855 Found = true;
856 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000857 }
858 }
John McCallf36e02d2009-10-09 21:13:30 +0000859 if (Found) {
860 R.resolveKind();
Douglas Gregord2235f62010-05-20 20:58:56 +0000861 if (S->isClassScope())
862 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
863 R.setNamingClass(Record);
John McCallf36e02d2009-10-09 21:13:30 +0000864 return true;
865 }
866
Douglas Gregor711be1e2010-03-15 14:33:29 +0000867 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
868 S->getParent() && !S->getParent()->isTemplateParamScope()) {
869 // We've just searched the last template parameter scope and
870 // found nothing, so look into the the contexts between the
871 // lexical and semantic declaration contexts returned by
872 // findOuterContext(). This implements the name lookup behavior
873 // of C++ [temp.local]p8.
874 Ctx = OutsideOfTemplateParamDC;
875 OutsideOfTemplateParamDC = 0;
876 }
877
878 if (Ctx) {
879 DeclContext *OuterCtx;
880 bool SearchAfterTemplateScope;
881 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
882 if (SearchAfterTemplateScope)
883 OutsideOfTemplateParamDC = OuterCtx;
884
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000885 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-02-19 16:08:35 +0000886 // We do not directly look into transparent contexts, since
887 // those entities will be found in the nearest enclosing
888 // non-transparent context.
889 if (Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000890 continue;
Douglas Gregor36262b82010-02-19 16:08:35 +0000891
892 // We do not look directly into function or method contexts,
893 // since all of the local variables and parameters of the
894 // function/method are present within the Scope.
895 if (Ctx->isFunctionOrMethod()) {
896 // If we have an Objective-C instance method, look for ivars
897 // in the corresponding interface.
898 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
899 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
900 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
901 ObjCInterfaceDecl *ClassDeclared;
902 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000903 Name.getAsIdentifierInfo(),
Douglas Gregor36262b82010-02-19 16:08:35 +0000904 ClassDeclared)) {
905 if (R.isAcceptableDecl(Ivar)) {
906 R.addDecl(Ivar);
907 R.resolveKind();
908 return true;
909 }
910 }
911 }
912 }
913
914 continue;
915 }
916
Douglas Gregore942bbe2009-09-10 16:57:35 +0000917 // Perform qualified name lookup into this context.
918 // FIXME: In some cases, we know that every name that could be found by
919 // this qualified name lookup will also be on the identifier chain. For
920 // example, inside a class without any base classes, we never need to
921 // perform qualified lookup because all of the members are on top of the
922 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000923 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +0000924 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +0000925 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000926 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000927 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000928
John McCalld7be78a2009-11-10 07:01:13 +0000929 // Stop if we ran out of scopes.
930 // FIXME: This really, really shouldn't be happening.
931 if (!S) return false;
932
Argyrios Kyrtzidis78f59112010-10-29 16:12:50 +0000933 // If we are looking for members, no need to look into global/namespace scope.
934 if (R.getLookupKind() == LookupMemberName)
935 return false;
936
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000937 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000938 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +0000939 //
Mike Stump390b4cc2009-05-16 07:39:55 +0000940 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
941 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000942
John McCalld7be78a2009-11-10 07:01:13 +0000943 UnqualUsingDirectiveSet UDirs;
944 UDirs.visitScopeChain(Initial, S);
945 UDirs.done();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000946
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000947 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000948 // Unqualified name lookup in C++ requires looking into scopes
949 // that aren't strictly lexical, and therefore we walk through the
950 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000951
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000952 for (; S; S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000953 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000954 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000955 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000956 if (R.isAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000957 // We found something. Look for anything else in our scope
958 // with this same name and in an acceptable identifier
959 // namespace, so that we can construct an overload set if we
960 // need to.
John McCallf36e02d2009-10-09 21:13:30 +0000961 Found = true;
962 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000963 }
964 }
965
Douglas Gregor00b4b032010-05-14 04:53:42 +0000966 if (Found && S->isTemplateParamScope()) {
John McCallf36e02d2009-10-09 21:13:30 +0000967 R.resolveKind();
968 return true;
969 }
970
Douglas Gregor00b4b032010-05-14 04:53:42 +0000971 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
972 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
973 S->getParent() && !S->getParent()->isTemplateParamScope()) {
974 // We've just searched the last template parameter scope and
975 // found nothing, so look into the the contexts between the
976 // lexical and semantic declaration contexts returned by
977 // findOuterContext(). This implements the name lookup behavior
978 // of C++ [temp.local]p8.
979 Ctx = OutsideOfTemplateParamDC;
980 OutsideOfTemplateParamDC = 0;
981 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000982
Douglas Gregor00b4b032010-05-14 04:53:42 +0000983 if (Ctx) {
984 DeclContext *OuterCtx;
985 bool SearchAfterTemplateScope;
986 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
987 if (SearchAfterTemplateScope)
988 OutsideOfTemplateParamDC = OuterCtx;
989
990 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
991 // We do not directly look into transparent contexts, since
992 // those entities will be found in the nearest enclosing
993 // non-transparent context.
994 if (Ctx->isTransparentContext())
995 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000996
Douglas Gregor00b4b032010-05-14 04:53:42 +0000997 // If we have a context, and it's not a context stashed in the
998 // template parameter scope for an out-of-line definition, also
999 // look into that context.
1000 if (!(Found && S && S->isTemplateParamScope())) {
1001 assert(Ctx->isFileContext() &&
1002 "We should have been looking only at file context here already.");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001003
Douglas Gregor00b4b032010-05-14 04:53:42 +00001004 // Look into context considering using-directives.
1005 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1006 Found = true;
1007 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001008
Douglas Gregor00b4b032010-05-14 04:53:42 +00001009 if (Found) {
1010 R.resolveKind();
1011 return true;
1012 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001013
Douglas Gregor00b4b032010-05-14 04:53:42 +00001014 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1015 return false;
1016 }
1017 }
1018
Douglas Gregor1df0ee92010-02-05 07:07:10 +00001019 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +00001020 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001021 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001022
John McCallf36e02d2009-10-09 21:13:30 +00001023 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001024}
1025
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001026/// @brief Perform unqualified name lookup starting from a given
1027/// scope.
1028///
1029/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1030/// used to find names within the current scope. For example, 'x' in
1031/// @code
1032/// int x;
1033/// int f() {
1034/// return x; // unqualified name look finds 'x' in the global scope
1035/// }
1036/// @endcode
1037///
1038/// Different lookup criteria can find different names. For example, a
1039/// particular scope can have both a struct and a function of the same
1040/// name, and each can be found by certain lookup criteria. For more
1041/// information about lookup criteria, see the documentation for the
1042/// class LookupCriteria.
1043///
1044/// @param S The scope from which unqualified name lookup will
1045/// begin. If the lookup criteria permits, name lookup may also search
1046/// in the parent scopes.
1047///
1048/// @param Name The name of the entity that we are searching for.
1049///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001050/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001051/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001052/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001053///
1054/// @returns The result of name lookup, which includes zero or more
1055/// declarations and possibly additional information used to diagnose
1056/// ambiguities.
John McCalla24dc2e2009-11-17 02:14:36 +00001057bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1058 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +00001059 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001060
John McCalla24dc2e2009-11-17 02:14:36 +00001061 LookupNameKind NameKind = R.getLookupKind();
1062
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001063 if (!getLangOptions().CPlusPlus) {
1064 // Unqualified name lookup in C/Objective-C is purely lexical, so
1065 // search in the declarations attached to the name.
John McCall1d7c5282009-12-18 10:40:03 +00001066 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001067 // Find the nearest non-transparent declaration scope.
1068 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001069 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001070 static_cast<DeclContext *>(S->getEntity())
1071 ->isTransparentContext()))
1072 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001073 }
1074
John McCall1d7c5282009-12-18 10:40:03 +00001075 unsigned IDNS = R.getIdentifierNamespace();
1076
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001077 // Scan up the scope chain looking for a decl that matches this
1078 // identifier that is in the appropriate namespace. This search
1079 // should not take long, as shadowing of names is uncommon, and
1080 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001081 bool LeftStartingScope = false;
1082
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001083 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +00001084 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001085 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001086 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001087 if (NameKind == LookupRedeclarationWithLinkage) {
1088 // Determine whether this (or a previous) declaration is
1089 // out-of-scope.
John McCalld226f652010-08-21 09:40:31 +00001090 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001091 LeftStartingScope = true;
1092
1093 // If we found something outside of our starting scope that
1094 // does not have linkage, skip it.
1095 if (LeftStartingScope && !((*I)->hasLinkage()))
1096 continue;
1097 }
1098
John McCallf36e02d2009-10-09 21:13:30 +00001099 R.addDecl(*I);
1100
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001101 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00001102 // If this declaration has the "overloadable" attribute, we
1103 // might have a set of overloaded functions.
1104
1105 // Figure out what scope the identifier is in.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001106 while (!(S->getFlags() & Scope::DeclScope) ||
John McCalld226f652010-08-21 09:40:31 +00001107 !S->isDeclScope(*I))
Douglas Gregorf9201e02009-02-11 23:02:49 +00001108 S = S->getParent();
1109
1110 // Find the last declaration in this scope (with the same
1111 // name, naturally).
1112 IdentifierResolver::iterator LastI = I;
1113 for (++LastI; LastI != IEnd; ++LastI) {
John McCalld226f652010-08-21 09:40:31 +00001114 if (!S->isDeclScope(*LastI))
Douglas Gregorf9201e02009-02-11 23:02:49 +00001115 break;
John McCallf36e02d2009-10-09 21:13:30 +00001116 R.addDecl(*LastI);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001117 }
Douglas Gregorf9201e02009-02-11 23:02:49 +00001118 }
1119
John McCallf36e02d2009-10-09 21:13:30 +00001120 R.resolveKind();
1121
1122 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +00001123 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001124 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001125 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +00001126 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +00001127 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001128 }
1129
1130 // If we didn't find a use of this identifier, and if the identifier
1131 // corresponds to a compiler builtin, create the decl object for the builtin
1132 // now, injecting it into translation unit scope, and return it.
Axel Naumann42151d52011-04-13 13:19:46 +00001133 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1134 return true;
Douglas Gregor3e41d602009-02-13 23:20:09 +00001135
Axel Naumannf8291a12011-02-24 16:47:47 +00001136 // If we didn't find a use of this identifier, the ExternalSource
1137 // may be able to handle the situation.
1138 // Note: some lookup failures are expected!
1139 // See e.g. R.isForRedeclaration().
1140 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001141}
1142
John McCall6e247262009-10-10 05:48:19 +00001143/// @brief Perform qualified name lookup in the namespaces nominated by
1144/// using directives by the given context.
1145///
1146/// C++98 [namespace.qual]p2:
1147/// Given X::m (where X is a user-declared namespace), or given ::m
1148/// (where X is the global namespace), let S be the set of all
1149/// declarations of m in X and in the transitive closure of all
1150/// namespaces nominated by using-directives in X and its used
1151/// namespaces, except that using-directives are ignored in any
1152/// namespace, including X, directly containing one or more
1153/// declarations of m. No namespace is searched more than once in
1154/// the lookup of a name. If S is the empty set, the program is
1155/// ill-formed. Otherwise, if S has exactly one member, or if the
1156/// context of the reference is a using-declaration
1157/// (namespace.udecl), S is the required set of declarations of
1158/// m. Otherwise if the use of m is not one that allows a unique
1159/// declaration to be chosen from S, the program is ill-formed.
1160/// C++98 [namespace.qual]p5:
1161/// During the lookup of a qualified namespace member name, if the
1162/// lookup finds more than one declaration of the member, and if one
1163/// declaration introduces a class name or enumeration name and the
1164/// other declarations either introduce the same object, the same
1165/// enumerator or a set of functions, the non-type name hides the
1166/// class or enumeration name if and only if the declarations are
1167/// from the same namespace; otherwise (the declarations are from
1168/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +00001169static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +00001170 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +00001171 assert(StartDC->isFileContext() && "start context is not a file context");
1172
1173 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1174 DeclContext::udir_iterator E = StartDC->using_directives_end();
1175
1176 if (I == E) return false;
1177
1178 // We have at least added all these contexts to the queue.
1179 llvm::DenseSet<DeclContext*> Visited;
1180 Visited.insert(StartDC);
1181
1182 // We have not yet looked into these namespaces, much less added
1183 // their "using-children" to the queue.
1184 llvm::SmallVector<NamespaceDecl*, 8> Queue;
1185
1186 // We have already looked into the initial namespace; seed the queue
1187 // with its using-children.
1188 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001189 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6e247262009-10-10 05:48:19 +00001190 if (Visited.insert(ND).second)
1191 Queue.push_back(ND);
1192 }
1193
1194 // The easiest way to implement the restriction in [namespace.qual]p5
1195 // is to check whether any of the individual results found a tag
1196 // and, if so, to declare an ambiguity if the final result is not
1197 // a tag.
1198 bool FoundTag = false;
1199 bool FoundNonTag = false;
1200
John McCall7d384dd2009-11-18 07:57:50 +00001201 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001202
1203 bool Found = false;
1204 while (!Queue.empty()) {
1205 NamespaceDecl *ND = Queue.back();
1206 Queue.pop_back();
1207
1208 // We go through some convolutions here to avoid copying results
1209 // between LookupResults.
1210 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001211 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001212 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001213
1214 if (FoundDirect) {
1215 // First do any local hiding.
1216 DirectR.resolveKind();
1217
1218 // If the local result is a tag, remember that.
1219 if (DirectR.isSingleTagDecl())
1220 FoundTag = true;
1221 else
1222 FoundNonTag = true;
1223
1224 // Append the local results to the total results if necessary.
1225 if (UseLocal) {
1226 R.addAllDecls(LocalR);
1227 LocalR.clear();
1228 }
1229 }
1230
1231 // If we find names in this namespace, ignore its using directives.
1232 if (FoundDirect) {
1233 Found = true;
1234 continue;
1235 }
1236
1237 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1238 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1239 if (Visited.insert(Nom).second)
1240 Queue.push_back(Nom);
1241 }
1242 }
1243
1244 if (Found) {
1245 if (FoundTag && FoundNonTag)
1246 R.setAmbiguousQualifiedTagHiding();
1247 else
1248 R.resolveKind();
1249 }
1250
1251 return Found;
1252}
1253
Douglas Gregor8071e422010-08-15 06:18:01 +00001254/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001255static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor8071e422010-08-15 06:18:01 +00001256 CXXBasePath &Path,
1257 void *Name) {
1258 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001259
Douglas Gregor8071e422010-08-15 06:18:01 +00001260 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1261 Path.Decls = BaseRecord->lookup(N);
1262 return Path.Decls.first != Path.Decls.second;
1263}
1264
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001265/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001266/// static members, nested types, and enumerators.
1267template<typename InputIterator>
1268static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1269 Decl *D = (*First)->getUnderlyingDecl();
1270 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1271 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001272
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001273 if (isa<CXXMethodDecl>(D)) {
1274 // Determine whether all of the methods are static.
1275 bool AllMethodsAreStatic = true;
1276 for(; First != Last; ++First) {
1277 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001278
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001279 if (!isa<CXXMethodDecl>(D)) {
1280 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1281 break;
1282 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001283
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001284 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1285 AllMethodsAreStatic = false;
1286 break;
1287 }
1288 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001289
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001290 if (AllMethodsAreStatic)
1291 return true;
1292 }
1293
1294 return false;
1295}
1296
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001297/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001298///
1299/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1300/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001301/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001302///
1303/// Different lookup criteria can find different names. For example, a
1304/// particular scope can have both a struct and a function of the same
1305/// name, and each can be found by certain lookup criteria. For more
1306/// information about lookup criteria, see the documentation for the
1307/// class LookupCriteria.
1308///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001309/// \param R captures both the lookup criteria and any lookup results found.
1310///
1311/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001312/// search. If the lookup criteria permits, name lookup may also search
1313/// in the parent contexts or (for C++ classes) base classes.
1314///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001315/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001316/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001317///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001318/// \returns true if lookup succeeded, false if it failed.
1319bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1320 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001321 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001322
John McCalla24dc2e2009-11-17 02:14:36 +00001323 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001324 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001325
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001326 // Make sure that the declaration context is complete.
1327 assert((!isa<TagDecl>(LookupCtx) ||
1328 LookupCtx->isDependentContext() ||
1329 cast<TagDecl>(LookupCtx)->isDefinition() ||
1330 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1331 ->isBeingDefined()) &&
1332 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001333
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001334 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001335 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001336 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001337 if (isa<CXXRecordDecl>(LookupCtx))
1338 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001339 return true;
1340 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001341
John McCall6e247262009-10-10 05:48:19 +00001342 // Don't descend into implied contexts for redeclarations.
1343 // C++98 [namespace.qual]p6:
1344 // In a declaration for a namespace member in which the
1345 // declarator-id is a qualified-id, given that the qualified-id
1346 // for the namespace member has the form
1347 // nested-name-specifier unqualified-id
1348 // the unqualified-id shall name a member of the namespace
1349 // designated by the nested-name-specifier.
1350 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001351 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001352 return false;
1353
John McCalla24dc2e2009-11-17 02:14:36 +00001354 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001355 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001356 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001357
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001358 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001359 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001360 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor025291b2010-07-01 00:21:21 +00001361 if (!LookupRec || !LookupRec->getDefinition())
John McCallf36e02d2009-10-09 21:13:30 +00001362 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001363
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001364 // If we're performing qualified name lookup into a dependent class,
1365 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001366 // dependent base classes, then we either have to delay lookup until
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001367 // template instantiation time (at which point all bases will be available)
1368 // or we have to fail.
1369 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1370 LookupRec->hasAnyDependentBases()) {
1371 R.setNotFoundInCurrentInstantiation();
1372 return false;
1373 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001374
Douglas Gregor7176fff2009-01-15 00:26:24 +00001375 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001376 CXXBasePaths Paths;
1377 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001378
1379 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001380 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001381 switch (R.getLookupKind()) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001382 case LookupOrdinaryName:
1383 case LookupMemberName:
1384 case LookupRedeclarationWithLinkage:
1385 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1386 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001387
Douglas Gregora8f32e02009-10-06 17:59:45 +00001388 case LookupTagName:
1389 BaseCallback = &CXXRecordDecl::FindTagMember;
1390 break;
John McCall9f54ad42009-12-10 09:41:52 +00001391
Douglas Gregor8071e422010-08-15 06:18:01 +00001392 case LookupAnyName:
1393 BaseCallback = &LookupAnyMember;
1394 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001395
John McCall9f54ad42009-12-10 09:41:52 +00001396 case LookupUsingDeclName:
1397 // This lookup is for redeclarations only.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001398
Douglas Gregora8f32e02009-10-06 17:59:45 +00001399 case LookupOperatorName:
1400 case LookupNamespaceName:
1401 case LookupObjCProtocolName:
Chris Lattner337e5502011-02-18 01:27:55 +00001402 case LookupLabel:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001403 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001404 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001405
Douglas Gregora8f32e02009-10-06 17:59:45 +00001406 case LookupNestedNameSpecifierName:
1407 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1408 break;
1409 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001410
John McCalla24dc2e2009-11-17 02:14:36 +00001411 if (!LookupRec->lookupInBases(BaseCallback,
1412 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001413 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001414
John McCall92f88312010-01-23 00:46:32 +00001415 R.setNamingClass(LookupRec);
1416
Douglas Gregor7176fff2009-01-15 00:26:24 +00001417 // C++ [class.member.lookup]p2:
1418 // [...] If the resulting set of declarations are not all from
1419 // sub-objects of the same type, or the set has a nonstatic member
1420 // and includes members from distinct sub-objects, there is an
1421 // ambiguity and the program is ill-formed. Otherwise that set is
1422 // the result of the lookup.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001423 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001424 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001425 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001426
Douglas Gregora8f32e02009-10-06 17:59:45 +00001427 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001428 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001429 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001430
John McCall46460a62010-01-20 21:53:11 +00001431 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1432 // across all paths.
1433 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001434
Douglas Gregor7176fff2009-01-15 00:26:24 +00001435 // Determine whether we're looking at a distinct sub-object or not.
1436 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001437 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001438 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1439 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001440 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001441 }
1442
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001443 if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001444 != Context.getCanonicalType(PathElement.Base->getType())) {
1445 // We found members of the given name in two subobjects of
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001446 // different types. If the declaration sets aren't the same, this
1447 // this lookup is ambiguous.
1448 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1449 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1450 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1451 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001452
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001453 while (FirstD != FirstPath->Decls.second &&
1454 CurrentD != Path->Decls.second) {
1455 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1456 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1457 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001458
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001459 ++FirstD;
1460 ++CurrentD;
1461 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001462
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001463 if (FirstD == FirstPath->Decls.second &&
1464 CurrentD == Path->Decls.second)
1465 continue;
1466 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001467
John McCallf36e02d2009-10-09 21:13:30 +00001468 R.setAmbiguousBaseSubobjectTypes(Paths);
1469 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001470 }
1471
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001472 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001473 // We have a different subobject of the same type.
1474
1475 // C++ [class.member.lookup]p5:
1476 // A static member, a nested type or an enumerator defined in
1477 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001478 // has more than one base class subobject of type T.
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001479 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
Douglas Gregor7176fff2009-01-15 00:26:24 +00001480 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001481
Douglas Gregor7176fff2009-01-15 00:26:24 +00001482 // We have found a nonstatic member name in multiple, distinct
1483 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001484 R.setAmbiguousBaseSubobjects(Paths);
1485 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001486 }
1487 }
1488
1489 // Lookup in a base class succeeded; return these results.
1490
John McCallf36e02d2009-10-09 21:13:30 +00001491 DeclContext::lookup_iterator I, E;
John McCall92f88312010-01-23 00:46:32 +00001492 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1493 NamedDecl *D = *I;
1494 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1495 D->getAccess());
1496 R.addDecl(D, AS);
1497 }
John McCallf36e02d2009-10-09 21:13:30 +00001498 R.resolveKind();
1499 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001500}
1501
1502/// @brief Performs name lookup for a name that was parsed in the
1503/// source code, and may contain a C++ scope specifier.
1504///
1505/// This routine is a convenience routine meant to be called from
1506/// contexts that receive a name and an optional C++ scope specifier
1507/// (e.g., "N::M::x"). It will then perform either qualified or
1508/// unqualified name lookup (with LookupQualifiedName or LookupName,
1509/// respectively) on the given name and return those results.
1510///
1511/// @param S The scope from which unqualified name lookup will
1512/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001513///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001514/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001515///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001516/// @param EnteringContext Indicates whether we are going to enter the
1517/// context of the scope-specifier SS (if present).
1518///
John McCallf36e02d2009-10-09 21:13:30 +00001519/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001520bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001521 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001522 if (SS && SS->isInvalid()) {
1523 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001524 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001525 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001526 }
Mike Stump1eb44332009-09-09 15:08:12 +00001527
Douglas Gregor495c35d2009-08-25 22:51:20 +00001528 if (SS && SS->isSet()) {
1529 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001530 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001531 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001532 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001533 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001534
John McCalla24dc2e2009-11-17 02:14:36 +00001535 R.setContextRange(SS->getRange());
1536
1537 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001538 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001539
Douglas Gregor495c35d2009-08-25 22:51:20 +00001540 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001541 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001542 // Name lookup can't find anything in this case.
John McCallf36e02d2009-10-09 21:13:30 +00001543 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001544 }
1545
Mike Stump1eb44332009-09-09 15:08:12 +00001546 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001547 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001548}
1549
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001550
Douglas Gregor7176fff2009-01-15 00:26:24 +00001551/// @brief Produce a diagnostic describing the ambiguity that resulted
1552/// from name lookup.
1553///
1554/// @param Result The ambiguous name lookup result.
Mike Stump1eb44332009-09-09 15:08:12 +00001555///
Douglas Gregor7176fff2009-01-15 00:26:24 +00001556/// @param Name The name of the entity that name lookup was
1557/// searching for.
1558///
1559/// @param NameLoc The location of the name within the source code.
1560///
1561/// @param LookupRange A source range that provides more
1562/// source-location information concerning the lookup itself. For
1563/// example, this range might highlight a nested-name-specifier that
1564/// precedes the name.
1565///
1566/// @returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001567bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001568 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1569
John McCalla24dc2e2009-11-17 02:14:36 +00001570 DeclarationName Name = Result.getLookupName();
1571 SourceLocation NameLoc = Result.getNameLoc();
1572 SourceRange LookupRange = Result.getContextRange();
1573
John McCall6e247262009-10-10 05:48:19 +00001574 switch (Result.getAmbiguityKind()) {
1575 case LookupResult::AmbiguousBaseSubobjects: {
1576 CXXBasePaths *Paths = Result.getBasePaths();
1577 QualType SubobjectType = Paths->front().back().Base->getType();
1578 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1579 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1580 << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001581
John McCall6e247262009-10-10 05:48:19 +00001582 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1583 while (isa<CXXMethodDecl>(*Found) &&
1584 cast<CXXMethodDecl>(*Found)->isStatic())
1585 ++Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001586
John McCall6e247262009-10-10 05:48:19 +00001587 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001588
John McCall6e247262009-10-10 05:48:19 +00001589 return true;
1590 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001591
John McCall6e247262009-10-10 05:48:19 +00001592 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001593 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1594 << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001595
John McCall6e247262009-10-10 05:48:19 +00001596 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001597 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001598 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1599 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001600 Path != PathEnd; ++Path) {
1601 Decl *D = *Path->Decls.first;
1602 if (DeclsPrinted.insert(D).second)
1603 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1604 }
1605
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001606 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001607 }
1608
John McCall6e247262009-10-10 05:48:19 +00001609 case LookupResult::AmbiguousTagHiding: {
1610 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001611
John McCall6e247262009-10-10 05:48:19 +00001612 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1613
1614 LookupResult::iterator DI, DE = Result.end();
1615 for (DI = Result.begin(); DI != DE; ++DI)
1616 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1617 TagDecls.insert(TD);
1618 Diag(TD->getLocation(), diag::note_hidden_tag);
1619 }
1620
1621 for (DI = Result.begin(); DI != DE; ++DI)
1622 if (!isa<TagDecl>(*DI))
1623 Diag((*DI)->getLocation(), diag::note_hiding_object);
1624
1625 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001626 LookupResult::Filter F = Result.makeFilter();
1627 while (F.hasNext()) {
1628 if (TagDecls.count(F.next()))
1629 F.erase();
1630 }
1631 F.done();
John McCall6e247262009-10-10 05:48:19 +00001632
1633 return true;
1634 }
1635
1636 case LookupResult::AmbiguousReference: {
1637 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001638
John McCall6e247262009-10-10 05:48:19 +00001639 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1640 for (; DI != DE; ++DI)
1641 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001642
John McCall6e247262009-10-10 05:48:19 +00001643 return true;
1644 }
1645 }
1646
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001647 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001648 return true;
1649}
Douglas Gregorfa047642009-02-04 00:32:51 +00001650
John McCallc7e04da2010-05-28 18:45:08 +00001651namespace {
1652 struct AssociatedLookup {
1653 AssociatedLookup(Sema &S,
1654 Sema::AssociatedNamespaceSet &Namespaces,
1655 Sema::AssociatedClassSet &Classes)
1656 : S(S), Namespaces(Namespaces), Classes(Classes) {
1657 }
1658
1659 Sema &S;
1660 Sema::AssociatedNamespaceSet &Namespaces;
1661 Sema::AssociatedClassSet &Classes;
1662 };
1663}
1664
Mike Stump1eb44332009-09-09 15:08:12 +00001665static void
John McCallc7e04da2010-05-28 18:45:08 +00001666addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCall6ff07852009-08-07 22:18:02 +00001667
Douglas Gregor54022952010-04-30 07:08:38 +00001668static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1669 DeclContext *Ctx) {
1670 // Add the associated namespace for this class.
1671
1672 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1673 // be a locally scoped record.
1674
Sebastian Redl410c4f22010-08-31 20:53:31 +00001675 // We skip out of inline namespaces. The innermost non-inline namespace
1676 // contains all names of all its nested inline namespaces anyway, so we can
1677 // replace the entire inline namespace tree with its root.
1678 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1679 Ctx->isInlineNamespace())
Douglas Gregor54022952010-04-30 07:08:38 +00001680 Ctx = Ctx->getParent();
1681
John McCall6ff07852009-08-07 22:18:02 +00001682 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001683 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001684}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001685
Mike Stump1eb44332009-09-09 15:08:12 +00001686// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001687// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001688static void
John McCallc7e04da2010-05-28 18:45:08 +00001689addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1690 const TemplateArgument &Arg) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001691 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001692 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001693 switch (Arg.getKind()) {
1694 case TemplateArgument::Null:
1695 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001696
Douglas Gregor69be8d62009-07-08 07:51:57 +00001697 case TemplateArgument::Type:
1698 // [...] the namespaces and classes associated with the types of the
1699 // template arguments provided for template type parameters (excluding
1700 // template template parameters)
John McCallc7e04da2010-05-28 18:45:08 +00001701 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor69be8d62009-07-08 07:51:57 +00001702 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001703
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001704 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001705 case TemplateArgument::TemplateExpansion: {
Mike Stump1eb44332009-09-09 15:08:12 +00001706 // [...] the namespaces in which any template template arguments are
1707 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001708 // template template arguments are defined.
Douglas Gregora7fc9012011-01-05 18:58:31 +00001709 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump1eb44332009-09-09 15:08:12 +00001710 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001711 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001712 DeclContext *Ctx = ClassTemplate->getDeclContext();
1713 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001714 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001715 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001716 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001717 }
1718 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001719 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001720
Douglas Gregor788cd062009-11-11 01:00:40 +00001721 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001722 case TemplateArgument::Integral:
1723 case TemplateArgument::Expression:
Mike Stump1eb44332009-09-09 15:08:12 +00001724 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001725 // associated namespaces. ]
1726 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001727
Douglas Gregor69be8d62009-07-08 07:51:57 +00001728 case TemplateArgument::Pack:
1729 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1730 PEnd = Arg.pack_end();
1731 P != PEnd; ++P)
John McCallc7e04da2010-05-28 18:45:08 +00001732 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001733 break;
1734 }
1735}
1736
Douglas Gregorfa047642009-02-04 00:32:51 +00001737// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001738// argument-dependent lookup with an argument of class type
1739// (C++ [basic.lookup.koenig]p2).
1740static void
John McCallc7e04da2010-05-28 18:45:08 +00001741addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1742 CXXRecordDecl *Class) {
1743
1744 // Just silently ignore anything whose name is __va_list_tag.
1745 if (Class->getDeclName() == Result.S.VAListTagName)
1746 return;
1747
Douglas Gregorfa047642009-02-04 00:32:51 +00001748 // C++ [basic.lookup.koenig]p2:
1749 // [...]
1750 // -- If T is a class type (including unions), its associated
1751 // classes are: the class itself; the class of which it is a
1752 // member, if any; and its direct and indirect base
1753 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001754 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001755
1756 // Add the class of which it is a member, if any.
1757 DeclContext *Ctx = Class->getDeclContext();
1758 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001759 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001760 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001761 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001762
Douglas Gregorfa047642009-02-04 00:32:51 +00001763 // Add the class itself. If we've already seen this class, we don't
1764 // need to visit base classes.
John McCallc7e04da2010-05-28 18:45:08 +00001765 if (!Result.Classes.insert(Class))
Douglas Gregorfa047642009-02-04 00:32:51 +00001766 return;
1767
Mike Stump1eb44332009-09-09 15:08:12 +00001768 // -- If T is a template-id, its associated namespaces and classes are
1769 // the namespace in which the template is defined; for member
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001770 // templates, the member template's class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001771 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001772 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001773 // namespaces in which any template template arguments are defined; and
1774 // the classes in which any member templates used as template template
1775 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001776 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001777 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001778 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1779 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1780 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001781 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001782 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001783 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001784
Douglas Gregor69be8d62009-07-08 07:51:57 +00001785 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1786 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallc7e04da2010-05-28 18:45:08 +00001787 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001788 }
Mike Stump1eb44332009-09-09 15:08:12 +00001789
John McCall86ff3082010-02-04 22:26:26 +00001790 // Only recurse into base classes for complete types.
1791 if (!Class->hasDefinition()) {
1792 // FIXME: we might need to instantiate templates here
1793 return;
1794 }
1795
Douglas Gregorfa047642009-02-04 00:32:51 +00001796 // Add direct and indirect base classes along with their associated
1797 // namespaces.
1798 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1799 Bases.push_back(Class);
1800 while (!Bases.empty()) {
1801 // Pop this class off the stack.
1802 Class = Bases.back();
1803 Bases.pop_back();
1804
1805 // Visit the base classes.
1806 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1807 BaseEnd = Class->bases_end();
1808 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001809 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001810 // In dependent contexts, we do ADL twice, and the first time around,
1811 // the base type might be a dependent TemplateSpecializationType, or a
1812 // TemplateTypeParmType. If that happens, simply ignore it.
1813 // FIXME: If we want to support export, we probably need to add the
1814 // namespace of the template in a TemplateSpecializationType, or even
1815 // the classes and namespaces of known non-dependent arguments.
1816 if (!BaseType)
1817 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001818 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001819 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001820 // Find the associated namespace for this base class.
1821 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallc7e04da2010-05-28 18:45:08 +00001822 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001823
1824 // Make sure we visit the bases of this base class.
1825 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1826 Bases.push_back(BaseDecl);
1827 }
1828 }
1829 }
1830}
1831
1832// \brief Add the associated classes and namespaces for
1833// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001834// (C++ [basic.lookup.koenig]p2).
1835static void
John McCallc7e04da2010-05-28 18:45:08 +00001836addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001837 // C++ [basic.lookup.koenig]p2:
1838 //
1839 // For each argument type T in the function call, there is a set
1840 // of zero or more associated namespaces and a set of zero or more
1841 // associated classes to be considered. The sets of namespaces and
1842 // classes is determined entirely by the types of the function
1843 // arguments (and the namespace of any template template
1844 // argument). Typedef names and using-declarations used to specify
1845 // the types do not contribute to this set. The sets of namespaces
1846 // and classes are determined in the following way:
Douglas Gregorfa047642009-02-04 00:32:51 +00001847
John McCallfa4edcf2010-05-28 06:08:54 +00001848 llvm::SmallVector<const Type *, 16> Queue;
1849 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1850
Douglas Gregorfa047642009-02-04 00:32:51 +00001851 while (true) {
John McCallfa4edcf2010-05-28 06:08:54 +00001852 switch (T->getTypeClass()) {
1853
1854#define TYPE(Class, Base)
1855#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1856#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1857#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1858#define ABSTRACT_TYPE(Class, Base)
1859#include "clang/AST/TypeNodes.def"
1860 // T is canonical. We can also ignore dependent types because
1861 // we don't need to do ADL at the definition point, but if we
1862 // wanted to implement template export (or if we find some other
1863 // use for associated classes and namespaces...) this would be
1864 // wrong.
Douglas Gregorfa047642009-02-04 00:32:51 +00001865 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00001866
John McCallfa4edcf2010-05-28 06:08:54 +00001867 // -- If T is a pointer to U or an array of U, its associated
1868 // namespaces and classes are those associated with U.
1869 case Type::Pointer:
1870 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1871 continue;
1872 case Type::ConstantArray:
1873 case Type::IncompleteArray:
1874 case Type::VariableArray:
1875 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1876 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001877
John McCallfa4edcf2010-05-28 06:08:54 +00001878 // -- If T is a fundamental type, its associated sets of
1879 // namespaces and classes are both empty.
1880 case Type::Builtin:
1881 break;
1882
1883 // -- If T is a class type (including unions), its associated
1884 // classes are: the class itself; the class of which it is a
1885 // member, if any; and its direct and indirect base
1886 // classes. Its associated namespaces are the namespaces in
1887 // which its associated classes are defined.
1888 case Type::Record: {
1889 CXXRecordDecl *Class
1890 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001891 addAssociatedClassesAndNamespaces(Result, Class);
John McCallfa4edcf2010-05-28 06:08:54 +00001892 break;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001893 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00001894
John McCallfa4edcf2010-05-28 06:08:54 +00001895 // -- If T is an enumeration type, its associated namespace is
1896 // the namespace in which it is defined. If it is class
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001897 // member, its associated class is the member's class; else
John McCallfa4edcf2010-05-28 06:08:54 +00001898 // it has no associated class.
1899 case Type::Enum: {
1900 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001901
John McCallfa4edcf2010-05-28 06:08:54 +00001902 DeclContext *Ctx = Enum->getDeclContext();
1903 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001904 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001905
John McCallfa4edcf2010-05-28 06:08:54 +00001906 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001907 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001908
John McCallfa4edcf2010-05-28 06:08:54 +00001909 break;
1910 }
1911
1912 // -- If T is a function type, its associated namespaces and
1913 // classes are those associated with the function parameter
1914 // types and those associated with the return type.
1915 case Type::FunctionProto: {
1916 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1917 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1918 ArgEnd = Proto->arg_type_end();
1919 Arg != ArgEnd; ++Arg)
1920 Queue.push_back(Arg->getTypePtr());
1921 // fallthrough
1922 }
1923 case Type::FunctionNoProto: {
1924 const FunctionType *FnType = cast<FunctionType>(T);
1925 T = FnType->getResultType().getTypePtr();
1926 continue;
1927 }
1928
1929 // -- If T is a pointer to a member function of a class X, its
1930 // associated namespaces and classes are those associated
1931 // with the function parameter types and return type,
1932 // together with those associated with X.
1933 //
1934 // -- If T is a pointer to a data member of class X, its
1935 // associated namespaces and classes are those associated
1936 // with the member type together with those associated with
1937 // X.
1938 case Type::MemberPointer: {
1939 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1940
1941 // Queue up the class type into which this points.
1942 Queue.push_back(MemberPtr->getClass());
1943
1944 // And directly continue with the pointee type.
1945 T = MemberPtr->getPointeeType().getTypePtr();
1946 continue;
1947 }
1948
1949 // As an extension, treat this like a normal pointer.
1950 case Type::BlockPointer:
1951 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1952 continue;
1953
1954 // References aren't covered by the standard, but that's such an
1955 // obvious defect that we cover them anyway.
1956 case Type::LValueReference:
1957 case Type::RValueReference:
1958 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1959 continue;
1960
1961 // These are fundamental types.
1962 case Type::Vector:
1963 case Type::ExtVector:
1964 case Type::Complex:
1965 break;
1966
Douglas Gregorf25760e2011-04-12 01:02:45 +00001967 // If T is an Objective-C object or interface type, or a pointer to an
1968 // object or interface type, the associated namespace is the global
1969 // namespace.
John McCallfa4edcf2010-05-28 06:08:54 +00001970 case Type::ObjCObject:
1971 case Type::ObjCInterface:
1972 case Type::ObjCObjectPointer:
Douglas Gregorf25760e2011-04-12 01:02:45 +00001973 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCallfa4edcf2010-05-28 06:08:54 +00001974 break;
1975 }
1976
1977 if (Queue.empty()) break;
1978 T = Queue.back();
1979 Queue.pop_back();
Douglas Gregorfa047642009-02-04 00:32:51 +00001980 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001981}
1982
1983/// \brief Find the associated classes and namespaces for
1984/// argument-dependent lookup for a call with the given set of
1985/// arguments.
1986///
1987/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00001988/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00001989/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001990void
Douglas Gregorfa047642009-02-04 00:32:51 +00001991Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1992 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001993 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001994 AssociatedNamespaces.clear();
1995 AssociatedClasses.clear();
1996
John McCallc7e04da2010-05-28 18:45:08 +00001997 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
1998
Douglas Gregorfa047642009-02-04 00:32:51 +00001999 // C++ [basic.lookup.koenig]p2:
2000 // For each argument type T in the function call, there is a set
2001 // of zero or more associated namespaces and a set of zero or more
2002 // associated classes to be considered. The sets of namespaces and
2003 // classes is determined entirely by the types of the function
2004 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00002005 // argument).
Douglas Gregorfa047642009-02-04 00:32:51 +00002006 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
2007 Expr *Arg = Args[ArgIdx];
2008
2009 if (Arg->getType() != Context.OverloadTy) {
John McCallc7e04da2010-05-28 18:45:08 +00002010 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002011 continue;
2012 }
2013
2014 // [...] In addition, if the argument is the name or address of a
2015 // set of overloaded functions and/or function templates, its
2016 // associated classes and namespaces are the union of those
2017 // associated with each of the members of the set: the namespace
2018 // in which the function or function template is defined and the
2019 // classes and namespaces associated with its (non-dependent)
2020 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00002021 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00002022 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCall2de56d12010-08-25 11:45:40 +00002023 if (unaryOp->getOpcode() == UO_AddrOf)
John McCallba135432009-11-21 08:51:07 +00002024 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002025
John McCallc7e04da2010-05-28 18:45:08 +00002026 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2027 if (!ULE) continue;
John McCallba135432009-11-21 08:51:07 +00002028
John McCallc7e04da2010-05-28 18:45:08 +00002029 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2030 I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00002031 // Look through any using declarations to find the underlying function.
2032 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002033
Chandler Carruthbd647292009-12-29 06:17:27 +00002034 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2035 if (!FDecl)
2036 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002037
2038 // Add the classes and namespaces associated with the parameter
2039 // types and return type of this function.
John McCallc7e04da2010-05-28 18:45:08 +00002040 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002041 }
2042 }
2043}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002044
2045/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2046/// an acceptable non-member overloaded operator for a call whose
2047/// arguments have types T1 (and, if non-empty, T2). This routine
2048/// implements the check in C++ [over.match.oper]p3b2 concerning
2049/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00002050static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002051IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2052 QualType T1, QualType T2,
2053 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00002054 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2055 return true;
2056
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002057 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2058 return true;
2059
John McCall183700f2009-09-21 23:43:11 +00002060 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002061 if (Proto->getNumArgs() < 1)
2062 return false;
2063
2064 if (T1->isEnumeralType()) {
2065 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002066 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002067 return true;
2068 }
2069
2070 if (Proto->getNumArgs() < 2)
2071 return false;
2072
2073 if (!T2.isNull() && T2->isEnumeralType()) {
2074 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002075 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002076 return true;
2077 }
2078
2079 return false;
2080}
2081
John McCall7d384dd2009-11-18 07:57:50 +00002082NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002083 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00002084 LookupNameKind NameKind,
2085 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002086 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00002087 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00002088 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00002089}
2090
Douglas Gregor6e378de2009-04-23 23:18:26 +00002091/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002092ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002093 SourceLocation IdLoc) {
2094 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2095 LookupObjCProtocolName);
Douglas Gregor6e378de2009-04-23 23:18:26 +00002096 return cast_or_null<ObjCProtocolDecl>(D);
2097}
2098
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002099void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00002100 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00002101 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002102 // C++ [over.match.oper]p3:
2103 // -- The set of non-member candidates is the result of the
2104 // unqualified lookup of operator@ in the context of the
2105 // expression according to the usual rules for name lookup in
2106 // unqualified function calls (3.4.2) except that all member
2107 // functions are ignored. However, if no operand has a class
2108 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00002109 // that have a first parameter of type T1 or "reference to
2110 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002111 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00002112 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002113 // when T2 is an enumeration type, are candidate functions.
2114 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00002115 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2116 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002117
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002118 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2119
John McCallf36e02d2009-10-09 21:13:30 +00002120 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002121 return;
2122
2123 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2124 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002125 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2126 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002127 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002128 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00002129 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002130 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00002131 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00002132 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00002133 // later?
2134 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002135 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00002136 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002137 }
2138}
2139
Sean Huntc39b6bc2011-06-24 02:11:39 +00002140Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Sean Hunt308742c2011-06-04 04:32:43 +00002141 CXXSpecialMember SM,
2142 bool ConstArg,
2143 bool VolatileArg,
2144 bool RValueThis,
2145 bool ConstThis,
2146 bool VolatileThis) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002147 RD = RD->getDefinition();
2148 assert((RD && !RD->isBeingDefined()) &&
Sean Hunt308742c2011-06-04 04:32:43 +00002149 "doing special member lookup into record that isn't fully complete");
2150 if (RValueThis || ConstThis || VolatileThis)
2151 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2152 "constructors and destructors always have unqualified lvalue this");
2153 if (ConstArg || VolatileArg)
2154 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2155 "parameter-less special members can't have qualified arguments");
2156
2157 llvm::FoldingSetNodeID ID;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002158 ID.AddPointer(RD);
Sean Hunt308742c2011-06-04 04:32:43 +00002159 ID.AddInteger(SM);
2160 ID.AddInteger(ConstArg);
2161 ID.AddInteger(VolatileArg);
2162 ID.AddInteger(RValueThis);
2163 ID.AddInteger(ConstThis);
2164 ID.AddInteger(VolatileThis);
2165
2166 void *InsertPoint;
2167 SpecialMemberOverloadResult *Result =
2168 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2169
2170 // This was already cached
2171 if (Result)
2172 return Result;
2173
Sean Hunt30543582011-06-07 00:11:58 +00002174 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2175 Result = new (Result) SpecialMemberOverloadResult(ID);
Sean Hunt308742c2011-06-04 04:32:43 +00002176 SpecialMemberCache.InsertNode(Result, InsertPoint);
2177
2178 if (SM == CXXDestructor) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002179 if (!RD->hasDeclaredDestructor())
2180 DeclareImplicitDestructor(RD);
2181 CXXDestructorDecl *DD = RD->getDestructor();
Sean Hunt308742c2011-06-04 04:32:43 +00002182 assert(DD && "record without a destructor");
2183 Result->setMethod(DD);
2184 Result->setSuccess(DD->isDeleted());
2185 Result->setConstParamMatch(false);
2186 return Result;
2187 }
2188
Sean Huntb320e0c2011-06-10 03:50:41 +00002189 // Prepare for overload resolution. Here we construct a synthetic argument
2190 // if necessary and make sure that implicit functions are declared.
Sean Huntc39b6bc2011-06-24 02:11:39 +00002191 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Sean Huntb320e0c2011-06-10 03:50:41 +00002192 DeclarationName Name;
2193 Expr *Arg = 0;
2194 unsigned NumArgs;
2195
2196 if (SM == CXXDefaultConstructor) {
2197 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2198 NumArgs = 0;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002199 if (RD->needsImplicitDefaultConstructor())
2200 DeclareImplicitDefaultConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002201 } else {
2202 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2203 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002204 if (!RD->hasDeclaredCopyConstructor())
2205 DeclareImplicitCopyConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002206 // TODO: Move constructors
2207 } else {
2208 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002209 if (!RD->hasDeclaredCopyAssignment())
2210 DeclareImplicitCopyAssignment(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002211 // TODO: Move assignment
2212 }
2213
2214 QualType ArgType = CanTy;
2215 if (ConstArg)
2216 ArgType.addConst();
2217 if (VolatileArg)
2218 ArgType.addVolatile();
2219
2220 // This isn't /really/ specified by the standard, but it's implied
2221 // we should be working from an RValue in the case of move to ensure
2222 // that we prefer to bind to rvalue references, and an LValue in the
2223 // case of copy to ensure we don't bind to rvalue references.
2224 // Possibly an XValue is actually correct in the case of move, but
2225 // there is no semantic difference for class types in this restricted
2226 // case.
2227 ExprValueKind VK;
Sean Huntab183df2011-06-22 22:13:13 +00002228 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Sean Huntb320e0c2011-06-10 03:50:41 +00002229 VK = VK_LValue;
2230 else
2231 VK = VK_RValue;
2232
2233 NumArgs = 1;
2234 Arg = new (Context) OpaqueValueExpr(SourceLocation(), ArgType, VK);
2235 }
2236
2237 // Create the object argument
2238 QualType ThisTy = CanTy;
2239 if (ConstThis)
2240 ThisTy.addConst();
2241 if (VolatileThis)
2242 ThisTy.addVolatile();
Sean Hunt4cc12c62011-06-23 00:26:20 +00002243 Expr::Classification Classification =
Sean Huntb320e0c2011-06-10 03:50:41 +00002244 (new (Context) OpaqueValueExpr(SourceLocation(), ThisTy,
2245 RValueThis ? VK_RValue : VK_LValue))->
2246 Classify(Context);
2247
2248 // Now we perform lookup on the name we computed earlier and do overload
2249 // resolution. Lookup is only performed directly into the class since there
2250 // will always be a (possibly implicit) declaration to shadow any others.
2251 OverloadCandidateSet OCS((SourceLocation()));
2252 DeclContext::lookup_iterator I, E;
2253 Result->setConstParamMatch(false);
2254
Sean Huntc39b6bc2011-06-24 02:11:39 +00002255 llvm::tie(I, E) = RD->lookup(Name);
Sean Huntb320e0c2011-06-10 03:50:41 +00002256 assert((I != E) &&
2257 "lookup for a constructor or assignment operator was empty");
2258 for ( ; I != E; ++I) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002259 Decl *Cand = *I;
Sean Hunt4cc12c62011-06-23 00:26:20 +00002260
Sean Huntc39b6bc2011-06-24 02:11:39 +00002261 if (Cand->isInvalidDecl())
Sean Huntb320e0c2011-06-10 03:50:41 +00002262 continue;
2263
Sean Huntc39b6bc2011-06-24 02:11:39 +00002264 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2265 // FIXME: [namespace.udecl]p15 says that we should only consider a
2266 // using declaration here if it does not match a declaration in the
2267 // derived class. We do not implement this correctly in other cases
2268 // either.
2269 Cand = U->getTargetDecl();
2270
2271 if (Cand->isInvalidDecl())
2272 continue;
2273 }
2274
2275 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002276 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Sean Huntc39b6bc2011-06-24 02:11:39 +00002277 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Sean Hunt4cc12c62011-06-23 00:26:20 +00002278 Classification, &Arg, NumArgs, OCS, true);
2279 else
2280 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public), &Arg,
2281 NumArgs, OCS, true);
Sean Huntb320e0c2011-06-10 03:50:41 +00002282
2283 // Here we're looking for a const parameter to speed up creation of
2284 // implicit copy methods.
2285 if ((SM == CXXCopyAssignment && M->isCopyAssignmentOperator()) ||
2286 (SM == CXXCopyConstructor &&
2287 cast<CXXConstructorDecl>(M)->isCopyConstructor())) {
2288 QualType ArgType = M->getType()->getAs<FunctionProtoType>()->getArgType(0);
Sean Hunt661c67a2011-06-21 23:42:56 +00002289 if (!ArgType->isReferenceType() ||
2290 ArgType->getPointeeType().isConstQualified())
Sean Huntb320e0c2011-06-10 03:50:41 +00002291 Result->setConstParamMatch(true);
2292 }
Sean Hunt431a1cb2011-06-22 02:58:46 +00002293 } else if (FunctionTemplateDecl *Tmpl =
Sean Huntc39b6bc2011-06-24 02:11:39 +00002294 dyn_cast<FunctionTemplateDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002295 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2296 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Sean Huntc39b6bc2011-06-24 02:11:39 +00002297 RD, 0, ThisTy, Classification, &Arg, NumArgs,
Sean Hunt4cc12c62011-06-23 00:26:20 +00002298 OCS, true);
2299 else
2300 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
2301 0, &Arg, NumArgs, OCS, true);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002302 } else {
2303 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Sean Huntb320e0c2011-06-10 03:50:41 +00002304 }
2305 }
2306
2307 OverloadCandidateSet::iterator Best;
2308 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2309 case OR_Success:
2310 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2311 Result->setSuccess(true);
2312 break;
2313
2314 case OR_Deleted:
2315 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2316 Result->setSuccess(false);
2317 break;
2318
2319 case OR_Ambiguous:
2320 case OR_No_Viable_Function:
2321 Result->setMethod(0);
2322 Result->setSuccess(false);
2323 break;
2324 }
2325
2326 return Result;
2327}
2328
2329/// \brief Look up the default constructor for the given class.
2330CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Sean Huntc530d172011-06-10 04:44:37 +00002331 SpecialMemberOverloadResult *Result =
Sean Huntb320e0c2011-06-10 03:50:41 +00002332 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2333 false, false);
2334
2335 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Sean Hunt308742c2011-06-04 04:32:43 +00002336}
2337
Sean Hunt661c67a2011-06-21 23:42:56 +00002338/// \brief Look up the copying constructor for the given class.
2339CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
2340 unsigned Quals,
2341 bool *ConstParamMatch) {
Sean Huntc530d172011-06-10 04:44:37 +00002342 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2343 "non-const, non-volatile qualifiers for copy ctor arg");
2344 SpecialMemberOverloadResult *Result =
2345 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2346 Quals & Qualifiers::Volatile, false, false, false);
2347
2348 if (ConstParamMatch)
2349 *ConstParamMatch = Result->hasConstParamMatch();
2350
2351 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2352}
2353
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002354/// \brief Look up the constructors for the given class.
2355DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002356 // If the implicit constructors have not yet been declared, do so now.
Douglas Gregor18274032010-07-03 00:47:00 +00002357 if (CanDeclareSpecialMemberFunction(Context, Class)) {
Sean Huntcdee3fe2011-05-11 22:34:38 +00002358 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002359 DeclareImplicitDefaultConstructor(Class);
2360 if (!Class->hasDeclaredCopyConstructor())
2361 DeclareImplicitCopyConstructor(Class);
2362 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002363
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002364 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2365 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2366 return Class->lookup(Name);
2367}
2368
Sean Hunt661c67a2011-06-21 23:42:56 +00002369/// \brief Look up the copying assignment operator for the given class.
2370CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2371 unsigned Quals, bool RValueThis,
2372 unsigned ThisQuals,
2373 bool *ConstParamMatch) {
2374 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2375 "non-const, non-volatile qualifiers for copy assignment arg");
2376 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2377 "non-const, non-volatile qualifiers for copy assignment this");
2378 SpecialMemberOverloadResult *Result =
2379 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2380 Quals & Qualifiers::Volatile, RValueThis,
2381 ThisQuals & Qualifiers::Const,
2382 ThisQuals & Qualifiers::Volatile);
2383
2384 if (ConstParamMatch)
2385 *ConstParamMatch = Result->hasConstParamMatch();
2386
2387 return Result->getMethod();
2388}
2389
Douglas Gregordb89f282010-07-01 22:47:18 +00002390/// \brief Look for the destructor of the given class.
2391///
Sean Huntc5c9b532011-06-03 21:10:40 +00002392/// During semantic analysis, this routine should be used in lieu of
2393/// CXXRecordDecl::getDestructor().
Douglas Gregordb89f282010-07-01 22:47:18 +00002394///
2395/// \returns The destructor for this class.
2396CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Sean Hunt308742c2011-06-04 04:32:43 +00002397 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2398 false, false, false,
2399 false, false)->getMethod());
Douglas Gregordb89f282010-07-01 22:47:18 +00002400}
2401
John McCall7edb5fd2010-01-26 07:16:45 +00002402void ADLResult::insert(NamedDecl *New) {
2403 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2404
2405 // If we haven't yet seen a decl for this key, or the last decl
2406 // was exactly this one, we're done.
2407 if (Old == 0 || Old == New) {
2408 Old = New;
2409 return;
2410 }
2411
2412 // Otherwise, decide which is a more recent redeclaration.
2413 FunctionDecl *OldFD, *NewFD;
2414 if (isa<FunctionTemplateDecl>(New)) {
2415 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2416 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2417 } else {
2418 OldFD = cast<FunctionDecl>(Old);
2419 NewFD = cast<FunctionDecl>(New);
2420 }
2421
2422 FunctionDecl *Cursor = NewFD;
2423 while (true) {
2424 Cursor = Cursor->getPreviousDeclaration();
2425
2426 // If we got to the end without finding OldFD, OldFD is the newer
2427 // declaration; leave things as they are.
2428 if (!Cursor) return;
2429
2430 // If we do find OldFD, then NewFD is newer.
2431 if (Cursor == OldFD) break;
2432
2433 // Otherwise, keep looking.
2434 }
2435
2436 Old = New;
2437}
2438
Sebastian Redl644be852009-10-23 19:23:15 +00002439void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002440 Expr **Args, unsigned NumArgs,
Richard Smithad762fc2011-04-14 22:09:26 +00002441 ADLResult &Result,
2442 bool StdNamespaceIsAssociated) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002443 // Find all of the associated namespaces and classes based on the
2444 // arguments we have.
2445 AssociatedNamespaceSet AssociatedNamespaces;
2446 AssociatedClassSet AssociatedClasses;
Mike Stump1eb44332009-09-09 15:08:12 +00002447 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCall6ff07852009-08-07 22:18:02 +00002448 AssociatedNamespaces,
2449 AssociatedClasses);
Richard Smithad762fc2011-04-14 22:09:26 +00002450 if (StdNamespaceIsAssociated && StdNamespace)
2451 AssociatedNamespaces.insert(getStdNamespace());
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002452
Sebastian Redl644be852009-10-23 19:23:15 +00002453 QualType T1, T2;
2454 if (Operator) {
2455 T1 = Args[0]->getType();
2456 if (NumArgs >= 2)
2457 T2 = Args[1]->getType();
2458 }
2459
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002460 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002461 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2462 // and let Y be the lookup set produced by argument dependent
2463 // lookup (defined as follows). If X contains [...] then Y is
2464 // empty. Otherwise Y is the set of declarations found in the
2465 // namespaces associated with the argument types as described
2466 // below. The set of declarations found by the lookup of the name
2467 // is the union of X and Y.
2468 //
2469 // Here, we compute Y and add its members to the overloaded
2470 // candidate set.
2471 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002472 NSEnd = AssociatedNamespaces.end();
2473 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002474 // When considering an associated namespace, the lookup is the
2475 // same as the lookup performed when the associated namespace is
2476 // used as a qualifier (3.4.3.2) except that:
2477 //
2478 // -- Any using-directives in the associated namespace are
2479 // ignored.
2480 //
John McCall6ff07852009-08-07 22:18:02 +00002481 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002482 // associated classes are visible within their respective
2483 // namespaces even if they are not visible during an ordinary
2484 // lookup (11.4).
2485 DeclContext::lookup_iterator I, E;
John McCall3f9a8a62009-08-11 06:59:38 +00002486 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall6e266892010-01-26 03:27:55 +00002487 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00002488 // If the only declaration here is an ordinary friend, consider
2489 // it only if it was declared in an associated classes.
2490 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00002491 DeclContext *LexDC = D->getLexicalDeclContext();
2492 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2493 continue;
2494 }
Mike Stump1eb44332009-09-09 15:08:12 +00002495
John McCalla113e722010-01-26 06:04:06 +00002496 if (isa<UsingShadowDecl>(D))
2497 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00002498
John McCalla113e722010-01-26 06:04:06 +00002499 if (isa<FunctionDecl>(D)) {
2500 if (Operator &&
2501 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2502 T1, T2, Context))
2503 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00002504 } else if (!isa<FunctionTemplateDecl>(D))
2505 continue;
2506
2507 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00002508 }
2509 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002510}
Douglas Gregor546be3c2009-12-30 17:04:44 +00002511
2512//----------------------------------------------------------------------------
2513// Search for all visible declarations.
2514//----------------------------------------------------------------------------
2515VisibleDeclConsumer::~VisibleDeclConsumer() { }
2516
2517namespace {
2518
2519class ShadowContextRAII;
2520
2521class VisibleDeclsRecord {
2522public:
2523 /// \brief An entry in the shadow map, which is optimized to store a
2524 /// single declaration (the common case) but can also store a list
2525 /// of declarations.
2526 class ShadowMapEntry {
2527 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002528
Douglas Gregor546be3c2009-12-30 17:04:44 +00002529 /// \brief Contains either the solitary NamedDecl * or a vector
2530 /// of declarations.
2531 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2532
2533 public:
2534 ShadowMapEntry() : DeclOrVector() { }
2535
2536 void Add(NamedDecl *ND);
2537 void Destroy();
2538
2539 // Iteration.
Argyrios Kyrtzidisaef05d72011-02-19 04:02:34 +00002540 typedef NamedDecl * const *iterator;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002541 iterator begin();
2542 iterator end();
2543 };
2544
2545private:
2546 /// \brief A mapping from declaration names to the declarations that have
2547 /// this name within a particular scope.
2548 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2549
2550 /// \brief A list of shadow maps, which is used to model name hiding.
2551 std::list<ShadowMap> ShadowMaps;
2552
2553 /// \brief The declaration contexts we have already visited.
2554 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2555
2556 friend class ShadowContextRAII;
2557
2558public:
2559 /// \brief Determine whether we have already visited this context
2560 /// (and, if not, note that we are going to visit that context now).
2561 bool visitedContext(DeclContext *Ctx) {
2562 return !VisitedContexts.insert(Ctx);
2563 }
2564
Douglas Gregor8071e422010-08-15 06:18:01 +00002565 bool alreadyVisitedContext(DeclContext *Ctx) {
2566 return VisitedContexts.count(Ctx);
2567 }
2568
Douglas Gregor546be3c2009-12-30 17:04:44 +00002569 /// \brief Determine whether the given declaration is hidden in the
2570 /// current scope.
2571 ///
2572 /// \returns the declaration that hides the given declaration, or
2573 /// NULL if no such declaration exists.
2574 NamedDecl *checkHidden(NamedDecl *ND);
2575
2576 /// \brief Add a declaration to the current shadow map.
2577 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2578};
2579
2580/// \brief RAII object that records when we've entered a shadow context.
2581class ShadowContextRAII {
2582 VisibleDeclsRecord &Visible;
2583
2584 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2585
2586public:
2587 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2588 Visible.ShadowMaps.push_back(ShadowMap());
2589 }
2590
2591 ~ShadowContextRAII() {
2592 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2593 EEnd = Visible.ShadowMaps.back().end();
2594 E != EEnd;
2595 ++E)
2596 E->second.Destroy();
2597
2598 Visible.ShadowMaps.pop_back();
2599 }
2600};
2601
2602} // end anonymous namespace
2603
2604void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2605 if (DeclOrVector.isNull()) {
2606 // 0 - > 1 elements: just set the single element information.
2607 DeclOrVector = ND;
2608 return;
2609 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002610
Douglas Gregor546be3c2009-12-30 17:04:44 +00002611 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2612 // 1 -> 2 elements: create the vector of results and push in the
2613 // existing declaration.
2614 DeclVector *Vec = new DeclVector;
2615 Vec->push_back(PrevND);
2616 DeclOrVector = Vec;
2617 }
2618
2619 // Add the new element to the end of the vector.
2620 DeclOrVector.get<DeclVector*>()->push_back(ND);
2621}
2622
2623void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2624 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2625 delete Vec;
2626 DeclOrVector = ((NamedDecl *)0);
2627 }
2628}
2629
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002630VisibleDeclsRecord::ShadowMapEntry::iterator
Douglas Gregor546be3c2009-12-30 17:04:44 +00002631VisibleDeclsRecord::ShadowMapEntry::begin() {
2632 if (DeclOrVector.isNull())
2633 return 0;
2634
Argyrios Kyrtzidisaef05d72011-02-19 04:02:34 +00002635 if (DeclOrVector.is<NamedDecl *>())
2636 return DeclOrVector.getAddrOf<NamedDecl *>();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002637
2638 return DeclOrVector.get<DeclVector *>()->begin();
2639}
2640
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002641VisibleDeclsRecord::ShadowMapEntry::iterator
Douglas Gregor546be3c2009-12-30 17:04:44 +00002642VisibleDeclsRecord::ShadowMapEntry::end() {
2643 if (DeclOrVector.isNull())
2644 return 0;
2645
Chandler Carruth7193b3e2011-05-02 18:54:36 +00002646 if (DeclOrVector.is<NamedDecl *>())
2647 return DeclOrVector.getAddrOf<NamedDecl *>() + 1;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002648
2649 return DeclOrVector.get<DeclVector *>()->end();
2650}
2651
2652NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002653 // Look through using declarations.
2654 ND = ND->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002655
Douglas Gregor546be3c2009-12-30 17:04:44 +00002656 unsigned IDNS = ND->getIdentifierNamespace();
2657 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2658 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2659 SM != SMEnd; ++SM) {
2660 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2661 if (Pos == SM->end())
2662 continue;
2663
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002664 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00002665 IEnd = Pos->second.end();
2666 I != IEnd; ++I) {
2667 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002668 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002669 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor546be3c2009-12-30 17:04:44 +00002670 Decl::IDNS_ObjCProtocol)))
2671 continue;
2672
2673 // Protocols are in distinct namespaces from everything else.
2674 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2675 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2676 (*I)->getIdentifierNamespace() != IDNS)
2677 continue;
2678
Douglas Gregor0cc84042010-01-14 15:47:35 +00002679 // Functions and function templates in the same scope overload
2680 // rather than hide. FIXME: Look for hiding based on function
2681 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002682 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002683 ND->isFunctionOrFunctionTemplate() &&
2684 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002685 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002686
Douglas Gregor546be3c2009-12-30 17:04:44 +00002687 // We've found a declaration that hides this one.
2688 return *I;
2689 }
2690 }
2691
2692 return 0;
2693}
2694
2695static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2696 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002697 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002698 VisibleDeclConsumer &Consumer,
2699 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00002700 if (!Ctx)
2701 return;
2702
Douglas Gregor546be3c2009-12-30 17:04:44 +00002703 // Make sure we don't visit the same context twice.
2704 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2705 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002706
Douglas Gregor4923aa22010-07-02 20:37:36 +00002707 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2708 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2709
Douglas Gregor546be3c2009-12-30 17:04:44 +00002710 // Enumerate all of the results in this context.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002711 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002712 CurCtx = CurCtx->getNextContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002713 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00002714 DEnd = CurCtx->decls_end();
2715 D != DEnd; ++D) {
Douglas Gregor70c23352010-12-09 21:44:02 +00002716 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002717 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002718 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002719 Visited.add(ND);
2720 }
Douglas Gregor70c23352010-12-09 21:44:02 +00002721 } else if (ObjCForwardProtocolDecl *ForwardProto
2722 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
2723 for (ObjCForwardProtocolDecl::protocol_iterator
2724 P = ForwardProto->protocol_begin(),
2725 PEnd = ForwardProto->protocol_end();
2726 P != PEnd;
2727 ++P) {
2728 if (Result.isAcceptableDecl(*P)) {
2729 Consumer.FoundDecl(*P, Visited.checkHidden(*P), InBaseClass);
2730 Visited.add(*P);
2731 }
2732 }
Douglas Gregord98abd82011-02-16 01:39:26 +00002733 } else if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D)) {
2734 for (ObjCClassDecl::iterator I = Class->begin(), IEnd = Class->end();
2735 I != IEnd; ++I) {
2736 ObjCInterfaceDecl *IFace = I->getInterface();
2737 if (Result.isAcceptableDecl(IFace)) {
2738 Consumer.FoundDecl(IFace, Visited.checkHidden(IFace), InBaseClass);
2739 Visited.add(IFace);
2740 }
2741 }
Douglas Gregor70c23352010-12-09 21:44:02 +00002742 }
Douglas Gregord98abd82011-02-16 01:39:26 +00002743
Sebastian Redl410c4f22010-08-31 20:53:31 +00002744 // Visit transparent contexts and inline namespaces inside this context.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002745 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
Sebastian Redl410c4f22010-08-31 20:53:31 +00002746 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Douglas Gregor0cc84042010-01-14 15:47:35 +00002747 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002748 Consumer, Visited);
2749 }
2750 }
2751 }
2752
2753 // Traverse using directives for qualified name lookup.
2754 if (QualifiedNameLookup) {
2755 ShadowContextRAII Shadow(Visited);
2756 DeclContext::udir_iterator I, E;
2757 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002758 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002759 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002760 }
2761 }
2762
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002763 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002764 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00002765 if (!Record->hasDefinition())
2766 return;
2767
Douglas Gregor546be3c2009-12-30 17:04:44 +00002768 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2769 BEnd = Record->bases_end();
2770 B != BEnd; ++B) {
2771 QualType BaseType = B->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002772
Douglas Gregor546be3c2009-12-30 17:04:44 +00002773 // Don't look into dependent bases, because name lookup can't look
2774 // there anyway.
2775 if (BaseType->isDependentType())
2776 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002777
Douglas Gregor546be3c2009-12-30 17:04:44 +00002778 const RecordType *Record = BaseType->getAs<RecordType>();
2779 if (!Record)
2780 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002781
Douglas Gregor546be3c2009-12-30 17:04:44 +00002782 // FIXME: It would be nice to be able to determine whether referencing
2783 // a particular member would be ambiguous. For example, given
2784 //
2785 // struct A { int member; };
2786 // struct B { int member; };
2787 // struct C : A, B { };
2788 //
2789 // void f(C *c) { c->### }
2790 //
2791 // accessing 'member' would result in an ambiguity. However, we
2792 // could be smart enough to qualify the member with the base
2793 // class, e.g.,
2794 //
2795 // c->B::member
2796 //
2797 // or
2798 //
2799 // c->A::member
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002800
Douglas Gregor546be3c2009-12-30 17:04:44 +00002801 // Find results in this base class (and its bases).
2802 ShadowContextRAII Shadow(Visited);
2803 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002804 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002805 }
2806 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002807
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002808 // Traverse the contexts of Objective-C classes.
2809 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2810 // Traverse categories.
2811 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2812 Category; Category = Category->getNextClassCategory()) {
2813 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002814 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002815 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002816 }
2817
2818 // Traverse protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00002819 for (ObjCInterfaceDecl::all_protocol_iterator
2820 I = IFace->all_referenced_protocol_begin(),
2821 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002822 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002823 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002824 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002825 }
2826
2827 // Traverse the superclass.
2828 if (IFace->getSuperClass()) {
2829 ShadowContextRAII Shadow(Visited);
2830 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002831 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002832 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002833
Douglas Gregorc220a182010-04-19 18:02:19 +00002834 // If there is an implementation, traverse it. We do this to find
2835 // synthesized ivars.
2836 if (IFace->getImplementation()) {
2837 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002838 LookupVisibleDecls(IFace->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00002839 QualifiedNameLookup, true, Consumer, Visited);
2840 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002841 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2842 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2843 E = Protocol->protocol_end(); I != E; ++I) {
2844 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002845 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002846 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002847 }
2848 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2849 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2850 E = Category->protocol_end(); I != E; ++I) {
2851 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002852 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002853 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002854 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002855
Douglas Gregorc220a182010-04-19 18:02:19 +00002856 // If there is an implementation, traverse it.
2857 if (Category->getImplementation()) {
2858 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002859 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00002860 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002861 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002862 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002863}
2864
2865static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2866 UnqualUsingDirectiveSet &UDirs,
2867 VisibleDeclConsumer &Consumer,
2868 VisibleDeclsRecord &Visited) {
2869 if (!S)
2870 return;
2871
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002872 if (!S->getEntity() ||
2873 (!S->getParent() &&
Douglas Gregor8071e422010-08-15 06:18:01 +00002874 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor539c5c32010-01-07 00:31:29 +00002875 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2876 // Walk through the declarations in this Scope.
2877 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2878 D != DEnd; ++D) {
John McCalld226f652010-08-21 09:40:31 +00002879 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor539c5c32010-01-07 00:31:29 +00002880 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002881 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002882 Visited.add(ND);
2883 }
2884 }
2885 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002886
Douglas Gregor711be1e2010-03-15 14:33:29 +00002887 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00002888 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00002889 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002890 // Look into this scope's declaration context, along with any of its
2891 // parent lookup contexts (e.g., enclosing classes), up to the point
2892 // where we hit the context stored in the next outer scope.
2893 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00002894 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002895
Douglas Gregordbdf5e72010-03-15 15:26:48 +00002896 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002897 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002898 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2899 if (Method->isInstanceMethod()) {
2900 // For instance methods, look for ivars in the method's interface.
2901 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2902 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregorca45da02010-11-02 20:36:02 +00002903 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002904 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Douglas Gregor62021192010-02-04 23:42:48 +00002905 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002906
Douglas Gregorca45da02010-11-02 20:36:02 +00002907 // Look for properties from which we can synthesize ivars, if
2908 // permitted.
2909 if (Result.getSema().getLangOptions().ObjCNonFragileABI2 &&
2910 IFace->getImplementation() &&
2911 Result.getLookupKind() == Sema::LookupOrdinaryName) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002912 for (ObjCInterfaceDecl::prop_iterator
Douglas Gregorca45da02010-11-02 20:36:02 +00002913 P = IFace->prop_begin(),
2914 PEnd = IFace->prop_end();
2915 P != PEnd; ++P) {
2916 if (Result.getSema().canSynthesizeProvisionalIvar(*P) &&
2917 !IFace->lookupInstanceVariable((*P)->getIdentifier())) {
2918 Consumer.FoundDecl(*P, Visited.checkHidden(*P), false);
2919 Visited.add(*P);
2920 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002921 }
2922 }
Douglas Gregorca45da02010-11-02 20:36:02 +00002923 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002924 }
2925
2926 // We've already performed all of the name lookup that we need
2927 // to for Objective-C methods; the next context will be the
2928 // outer scope.
2929 break;
2930 }
2931
Douglas Gregor546be3c2009-12-30 17:04:44 +00002932 if (Ctx->isFunctionOrMethod())
2933 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002934
2935 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002936 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002937 }
2938 } else if (!S->getParent()) {
2939 // Look into the translation unit scope. We walk through the translation
2940 // unit's declaration context, because the Scope itself won't have all of
2941 // the declarations if we loaded a precompiled header.
2942 // FIXME: We would like the translation unit's Scope object to point to the
2943 // translation unit, so we don't need this special "if" branch. However,
2944 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002945 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002946 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00002947 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002948 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002949 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002950 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002951 }
2952
Douglas Gregor546be3c2009-12-30 17:04:44 +00002953 if (Entity) {
2954 // Lookup visible declarations in any namespaces found by using
2955 // directives.
2956 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2957 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2958 for (; UI != UEnd; ++UI)
2959 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002960 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002961 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002962 }
2963
2964 // Lookup names in the parent scope.
2965 ShadowContextRAII Shadow(Visited);
2966 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2967}
2968
2969void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00002970 VisibleDeclConsumer &Consumer,
2971 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002972 // Determine the set of using directives available during
2973 // unqualified name lookup.
2974 Scope *Initial = S;
2975 UnqualUsingDirectiveSet UDirs;
2976 if (getLangOptions().CPlusPlus) {
2977 // Find the first namespace or translation-unit scope.
2978 while (S && !isNamespaceOrTranslationUnitScope(S))
2979 S = S->getParent();
2980
2981 UDirs.visitScopeChain(Initial, S);
2982 }
2983 UDirs.done();
2984
2985 // Look for visible declarations.
2986 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2987 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00002988 if (!IncludeGlobalScope)
2989 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00002990 ShadowContextRAII Shadow(Visited);
2991 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2992}
2993
2994void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00002995 VisibleDeclConsumer &Consumer,
2996 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002997 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2998 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00002999 if (!IncludeGlobalScope)
3000 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003001 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003002 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003003 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003004}
3005
Chris Lattner4ae493c2011-02-18 02:08:43 +00003006/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara67843042011-03-05 18:21:20 +00003007/// If GnuLabelLoc is a valid source location, then this is a definition
3008/// of an __label__ label name, otherwise it is a normal label definition
3009/// or use.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003010LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara67843042011-03-05 18:21:20 +00003011 SourceLocation GnuLabelLoc) {
Chris Lattner337e5502011-02-18 01:27:55 +00003012 // Do a lookup to see if we have a label with this name already.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003013 NamedDecl *Res = 0;
Abramo Bagnara67843042011-03-05 18:21:20 +00003014
3015 if (GnuLabelLoc.isValid()) {
3016 // Local label definitions always shadow existing labels.
3017 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3018 Scope *S = CurScope;
3019 PushOnScopeChains(Res, S, true);
3020 return cast<LabelDecl>(Res);
3021 }
3022
3023 // Not a GNU local label.
3024 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3025 // If we found a label, check to see if it is in the same context as us.
3026 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattner337e5502011-02-18 01:27:55 +00003027 if (Res && Res->getDeclContext() != CurContext)
3028 Res = 0;
Chris Lattner337e5502011-02-18 01:27:55 +00003029 if (Res == 0) {
3030 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara67843042011-03-05 18:21:20 +00003031 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3032 Scope *S = CurScope->getFnParent();
Chris Lattnerfebb5b82011-02-18 21:16:39 +00003033 assert(S && "Not in a function?");
3034 PushOnScopeChains(Res, S, true);
Chris Lattner337e5502011-02-18 01:27:55 +00003035 }
Chris Lattner337e5502011-02-18 01:27:55 +00003036 return cast<LabelDecl>(Res);
3037}
3038
3039//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003040// Typo correction
Chris Lattner337e5502011-02-18 01:27:55 +00003041//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003042
3043namespace {
3044class TypoCorrectionConsumer : public VisibleDeclConsumer {
3045 /// \brief The name written that is a typo in the source.
3046 llvm::StringRef Typo;
3047
3048 /// \brief The results found that have the smallest edit distance
3049 /// found (so far) with the typo name.
Douglas Gregore24b5752010-10-14 20:34:08 +00003050 ///
3051 /// The boolean value indicates whether there is a keyword with this name.
3052 llvm::StringMap<bool, llvm::BumpPtrAllocator> BestResults;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003053
3054 /// \brief The best edit distance found so far.
3055 unsigned BestEditDistance;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003056
Douglas Gregor546be3c2009-12-30 17:04:44 +00003057public:
3058 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003059 : Typo(Typo->getName()),
Douglas Gregore24b5752010-10-14 20:34:08 +00003060 BestEditDistance((std::numeric_limits<unsigned>::max)()) { }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003061
Douglas Gregor0cc84042010-01-14 15:47:35 +00003062 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregor95f42922010-10-14 22:11:03 +00003063 void FoundName(llvm::StringRef Name);
Douglas Gregoraaf87162010-04-14 20:04:41 +00003064 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003065
Douglas Gregore24b5752010-10-14 20:34:08 +00003066 typedef llvm::StringMap<bool, llvm::BumpPtrAllocator>::iterator iterator;
3067 iterator begin() { return BestResults.begin(); }
3068 iterator end() { return BestResults.end(); }
3069 void erase(iterator I) { BestResults.erase(I); }
3070 unsigned size() const { return BestResults.size(); }
3071 bool empty() const { return BestResults.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003072
Douglas Gregor7b824e82010-10-15 13:35:25 +00003073 bool &operator[](llvm::StringRef Name) {
3074 return BestResults[Name];
3075 }
3076
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003077 unsigned getBestEditDistance() const { return BestEditDistance; }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003078};
3079
3080}
3081
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003082void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003083 bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003084 // Don't consider hidden names for typo correction.
3085 if (Hiding)
3086 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003087
Douglas Gregor546be3c2009-12-30 17:04:44 +00003088 // Only consider entities with identifiers for names, ignoring
3089 // special names (constructors, overloaded operators, selectors,
3090 // etc.).
3091 IdentifierInfo *Name = ND->getIdentifier();
3092 if (!Name)
3093 return;
3094
Douglas Gregor95f42922010-10-14 22:11:03 +00003095 FoundName(Name->getName());
3096}
3097
3098void TypoCorrectionConsumer::FoundName(llvm::StringRef Name) {
Douglas Gregor362a8f22010-10-19 19:39:10 +00003099 // Use a simple length-based heuristic to determine the minimum possible
3100 // edit distance. If the minimum isn't good enough, bail out early.
3101 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
3102 if (MinED > BestEditDistance || (MinED && Typo.size() / MinED < 3))
3103 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003104
Douglas Gregora1194772010-10-19 22:14:33 +00003105 // Compute an upper bound on the allowable edit distance, so that the
3106 // edit-distance algorithm can short-circuit.
Jay Foadf1cc1d02011-04-23 09:06:00 +00003107 unsigned UpperBound =
3108 std::min(unsigned((Typo.size() + 2) / 3), BestEditDistance);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003109
Douglas Gregor546be3c2009-12-30 17:04:44 +00003110 // Compute the edit distance between the typo and the name of this
3111 // entity. If this edit distance is not worse than the best edit
3112 // distance we've seen so far, add it to the list of results.
Douglas Gregora1194772010-10-19 22:14:33 +00003113 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
Douglas Gregor95f42922010-10-14 22:11:03 +00003114 if (ED == 0)
3115 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003116
Douglas Gregore24b5752010-10-14 20:34:08 +00003117 if (ED < BestEditDistance) {
3118 // This result is better than any we've seen before; clear out
3119 // the previous results.
3120 BestResults.clear();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003121 BestEditDistance = ED;
Douglas Gregore24b5752010-10-14 20:34:08 +00003122 } else if (ED > BestEditDistance) {
3123 // This result is worse than the best results we've seen so far;
3124 // ignore it.
3125 return;
3126 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003127
Douglas Gregore24b5752010-10-14 20:34:08 +00003128 // Add this name to the list of results. By not assigning a value, we
3129 // keep the current value if we've seen this name before (either as a
3130 // keyword or as a declaration), or get the default value (not a keyword)
3131 // if we haven't seen it before.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003132 (void)BestResults[Name];
Douglas Gregor546be3c2009-12-30 17:04:44 +00003133}
3134
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003135void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
Douglas Gregoraaf87162010-04-14 20:04:41 +00003136 llvm::StringRef Keyword) {
3137 // Compute the edit distance between the typo and this keyword.
3138 // If this edit distance is not worse than the best edit
3139 // distance we've seen so far, add it to the list of results.
3140 unsigned ED = Typo.edit_distance(Keyword);
Douglas Gregore24b5752010-10-14 20:34:08 +00003141 if (ED < BestEditDistance) {
3142 BestResults.clear();
Douglas Gregoraaf87162010-04-14 20:04:41 +00003143 BestEditDistance = ED;
Douglas Gregore24b5752010-10-14 20:34:08 +00003144 } else if (ED > BestEditDistance) {
3145 // This result is worse than the best results we've seen so far;
3146 // ignore it.
3147 return;
3148 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003149
Douglas Gregore24b5752010-10-14 20:34:08 +00003150 BestResults[Keyword] = true;
Douglas Gregoraaf87162010-04-14 20:04:41 +00003151}
3152
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003153/// \brief Perform name lookup for a possible result for typo correction.
3154static void LookupPotentialTypoResult(Sema &SemaRef,
3155 LookupResult &Res,
3156 IdentifierInfo *Name,
3157 Scope *S, CXXScopeSpec *SS,
3158 DeclContext *MemberContext,
3159 bool EnteringContext,
3160 Sema::CorrectTypoContext CTC) {
3161 Res.suppressDiagnostics();
3162 Res.clear();
3163 Res.setLookupName(Name);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003164 if (MemberContext) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003165 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
3166 if (CTC == Sema::CTC_ObjCIvarLookup) {
3167 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3168 Res.addDecl(Ivar);
3169 Res.resolveKind();
3170 return;
3171 }
3172 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003173
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003174 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3175 Res.addDecl(Prop);
3176 Res.resolveKind();
3177 return;
3178 }
3179 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003180
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003181 SemaRef.LookupQualifiedName(Res, MemberContext);
3182 return;
3183 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003184
3185 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003186 EnteringContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003187
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003188 // Fake ivar lookup; this should really be part of
3189 // LookupParsedName.
3190 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3191 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003192 (Res.empty() ||
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003193 (Res.isSingleResult() &&
3194 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003195 if (ObjCIvarDecl *IV
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003196 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3197 Res.addDecl(IV);
3198 Res.resolveKind();
3199 }
3200 }
3201 }
3202}
3203
Douglas Gregor546be3c2009-12-30 17:04:44 +00003204/// \brief Try to "correct" a typo in the source code by finding
3205/// visible declarations whose names are similar to the name that was
3206/// present in the source code.
3207///
3208/// \param Res the \c LookupResult structure that contains the name
3209/// that was present in the source code along with the name-lookup
3210/// criteria used to search for the name. On success, this structure
3211/// will contain the results of name lookup.
3212///
3213/// \param S the scope in which name lookup occurs.
3214///
3215/// \param SS the nested-name-specifier that precedes the name we're
3216/// looking for, if present.
3217///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003218/// \param MemberContext if non-NULL, the context in which to look for
3219/// a member access expression.
3220///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003221/// \param EnteringContext whether we're entering the context described by
Douglas Gregorbb092ba2009-12-31 05:20:13 +00003222/// the nested-name-specifier SS.
3223///
Douglas Gregoraaf87162010-04-14 20:04:41 +00003224/// \param CTC The context in which typo correction occurs, which impacts the
3225/// set of keywords permitted.
3226///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003227/// \param OPT when non-NULL, the search for visible declarations will
3228/// also walk the protocols in the qualified interfaces of \p OPT.
3229///
Douglas Gregor931f98a2010-04-14 17:09:22 +00003230/// \returns the corrected name if the typo was corrected, otherwise returns an
3231/// empty \c DeclarationName. When a typo was corrected, the result structure
3232/// may contain the results of name lookup for the correct name or it may be
3233/// empty.
3234DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003235 DeclContext *MemberContext,
Douglas Gregoraaf87162010-04-14 20:04:41 +00003236 bool EnteringContext,
3237 CorrectTypoContext CTC,
3238 const ObjCObjectPointerType *OPT) {
Douglas Gregora0068fc2010-07-09 17:35:33 +00003239 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregor931f98a2010-04-14 17:09:22 +00003240 return DeclarationName();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003241
Douglas Gregor546be3c2009-12-30 17:04:44 +00003242 // We only attempt to correct typos for identifiers.
3243 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
3244 if (!Typo)
Douglas Gregor931f98a2010-04-14 17:09:22 +00003245 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003246
3247 // If the scope specifier itself was invalid, don't try to correct
3248 // typos.
3249 if (SS && SS->isInvalid())
Douglas Gregor931f98a2010-04-14 17:09:22 +00003250 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003251
3252 // Never try to correct typos during template deduction or
3253 // instantiation.
3254 if (!ActiveTemplateInstantiations.empty())
Douglas Gregor931f98a2010-04-14 17:09:22 +00003255 return DeclarationName();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003256
Douglas Gregor546be3c2009-12-30 17:04:44 +00003257 TypoCorrectionConsumer Consumer(Typo);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003258
Douglas Gregoraaf87162010-04-14 20:04:41 +00003259 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003260 bool IsUnqualifiedLookup = false;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003261 if (MemberContext) {
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003262 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003263
3264 // Look in qualified interfaces.
3265 if (OPT) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003266 for (ObjCObjectPointerType::qual_iterator
3267 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003268 I != E; ++I)
3269 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
3270 }
3271 } else if (SS && SS->isSet()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003272 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
3273 if (!DC)
Douglas Gregor931f98a2010-04-14 17:09:22 +00003274 return DeclarationName();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003275
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003276 // Provide a stop gap for files that are just seriously broken. Trying
3277 // to correct all typos can turn into a HUGE performance penalty, causing
3278 // some files to take minutes to get rejected by the parser.
3279 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
3280 return DeclarationName();
3281 ++TyposCorrected;
3282
Douglas Gregor546be3c2009-12-30 17:04:44 +00003283 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
3284 } else {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003285 IsUnqualifiedLookup = true;
3286 UnqualifiedTyposCorrectedMap::iterator Cached
3287 = UnqualifiedTyposCorrected.find(Typo);
3288 if (Cached == UnqualifiedTyposCorrected.end()) {
3289 // Provide a stop gap for files that are just seriously broken. Trying
3290 // to correct all typos can turn into a HUGE performance penalty, causing
3291 // some files to take minutes to get rejected by the parser.
3292 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
3293 return DeclarationName();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003294
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003295 // For unqualified lookup, look through all of the names that we have
3296 // seen in this translation unit.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003297 for (IdentifierTable::iterator I = Context.Idents.begin(),
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003298 IEnd = Context.Idents.end();
3299 I != IEnd; ++I)
3300 Consumer.FoundName(I->getKey());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003301
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003302 // Walk through identifiers in external identifier sources.
3303 if (IdentifierInfoLookup *External
Douglas Gregor95f42922010-10-14 22:11:03 +00003304 = Context.Idents.getExternalIdentifierLookup()) {
Ted Kremenek7a054b12010-11-07 06:11:33 +00003305 llvm::OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003306 do {
3307 llvm::StringRef Name = Iter->Next();
3308 if (Name.empty())
3309 break;
Douglas Gregor95f42922010-10-14 22:11:03 +00003310
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003311 Consumer.FoundName(Name);
3312 } while (true);
3313 }
3314 } else {
3315 // Use the cached value, unless it's a keyword. In the keyword case, we'll
3316 // end up adding the keyword below.
3317 if (Cached->second.first.empty())
3318 return DeclarationName();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003319
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003320 if (!Cached->second.second)
3321 Consumer.FoundName(Cached->second.first);
Douglas Gregor95f42922010-10-14 22:11:03 +00003322 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003323 }
3324
Douglas Gregoraaf87162010-04-14 20:04:41 +00003325 // Add context-dependent keywords.
3326 bool WantTypeSpecifiers = false;
3327 bool WantExpressionKeywords = false;
3328 bool WantCXXNamedCasts = false;
3329 bool WantRemainingKeywords = false;
3330 switch (CTC) {
3331 case CTC_Unknown:
3332 WantTypeSpecifiers = true;
3333 WantExpressionKeywords = true;
3334 WantCXXNamedCasts = true;
3335 WantRemainingKeywords = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003336
Douglas Gregor91f7ac72010-05-18 16:14:23 +00003337 if (ObjCMethodDecl *Method = getCurMethodDecl())
3338 if (Method->getClassInterface() &&
3339 Method->getClassInterface()->getSuperClass())
3340 Consumer.addKeywordResult(Context, "super");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003341
Douglas Gregoraaf87162010-04-14 20:04:41 +00003342 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003343
Douglas Gregoraaf87162010-04-14 20:04:41 +00003344 case CTC_NoKeywords:
3345 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003346
Douglas Gregoraaf87162010-04-14 20:04:41 +00003347 case CTC_Type:
3348 WantTypeSpecifiers = true;
3349 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003350
Douglas Gregoraaf87162010-04-14 20:04:41 +00003351 case CTC_ObjCMessageReceiver:
3352 Consumer.addKeywordResult(Context, "super");
3353 // Fall through to handle message receivers like expressions.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003354
Douglas Gregoraaf87162010-04-14 20:04:41 +00003355 case CTC_Expression:
3356 if (getLangOptions().CPlusPlus)
3357 WantTypeSpecifiers = true;
3358 WantExpressionKeywords = true;
3359 // Fall through to get C++ named casts.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003360
Douglas Gregoraaf87162010-04-14 20:04:41 +00003361 case CTC_CXXCasts:
3362 WantCXXNamedCasts = true;
3363 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003364
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003365 case CTC_ObjCPropertyLookup:
3366 // FIXME: Add "isa"?
3367 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003368
Douglas Gregoraaf87162010-04-14 20:04:41 +00003369 case CTC_MemberLookup:
3370 if (getLangOptions().CPlusPlus)
3371 Consumer.addKeywordResult(Context, "template");
3372 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003373
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003374 case CTC_ObjCIvarLookup:
3375 break;
Douglas Gregoraaf87162010-04-14 20:04:41 +00003376 }
3377
3378 if (WantTypeSpecifiers) {
3379 // Add type-specifier keywords to the set of results.
3380 const char *CTypeSpecs[] = {
3381 "char", "const", "double", "enum", "float", "int", "long", "short",
3382 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
3383 "_Complex", "_Imaginary",
3384 // storage-specifiers as well
3385 "extern", "inline", "static", "typedef"
3386 };
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003387
Douglas Gregoraaf87162010-04-14 20:04:41 +00003388 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3389 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3390 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003391
Douglas Gregoraaf87162010-04-14 20:04:41 +00003392 if (getLangOptions().C99)
3393 Consumer.addKeywordResult(Context, "restrict");
3394 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
3395 Consumer.addKeywordResult(Context, "bool");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003396
Douglas Gregoraaf87162010-04-14 20:04:41 +00003397 if (getLangOptions().CPlusPlus) {
3398 Consumer.addKeywordResult(Context, "class");
3399 Consumer.addKeywordResult(Context, "typename");
3400 Consumer.addKeywordResult(Context, "wchar_t");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003401
Douglas Gregoraaf87162010-04-14 20:04:41 +00003402 if (getLangOptions().CPlusPlus0x) {
3403 Consumer.addKeywordResult(Context, "char16_t");
3404 Consumer.addKeywordResult(Context, "char32_t");
3405 Consumer.addKeywordResult(Context, "constexpr");
3406 Consumer.addKeywordResult(Context, "decltype");
3407 Consumer.addKeywordResult(Context, "thread_local");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003408 }
Douglas Gregoraaf87162010-04-14 20:04:41 +00003409 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003410
Douglas Gregoraaf87162010-04-14 20:04:41 +00003411 if (getLangOptions().GNUMode)
3412 Consumer.addKeywordResult(Context, "typeof");
3413 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003414
Douglas Gregord0785ea2010-05-18 16:30:22 +00003415 if (WantCXXNamedCasts && getLangOptions().CPlusPlus) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00003416 Consumer.addKeywordResult(Context, "const_cast");
3417 Consumer.addKeywordResult(Context, "dynamic_cast");
3418 Consumer.addKeywordResult(Context, "reinterpret_cast");
3419 Consumer.addKeywordResult(Context, "static_cast");
3420 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003421
Douglas Gregoraaf87162010-04-14 20:04:41 +00003422 if (WantExpressionKeywords) {
3423 Consumer.addKeywordResult(Context, "sizeof");
3424 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
3425 Consumer.addKeywordResult(Context, "false");
3426 Consumer.addKeywordResult(Context, "true");
3427 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003428
Douglas Gregoraaf87162010-04-14 20:04:41 +00003429 if (getLangOptions().CPlusPlus) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003430 const char *CXXExprs[] = {
3431 "delete", "new", "operator", "throw", "typeid"
Douglas Gregoraaf87162010-04-14 20:04:41 +00003432 };
3433 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3434 for (unsigned I = 0; I != NumCXXExprs; ++I)
3435 Consumer.addKeywordResult(Context, CXXExprs[I]);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003436
Douglas Gregoraaf87162010-04-14 20:04:41 +00003437 if (isa<CXXMethodDecl>(CurContext) &&
3438 cast<CXXMethodDecl>(CurContext)->isInstance())
3439 Consumer.addKeywordResult(Context, "this");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003440
Douglas Gregoraaf87162010-04-14 20:04:41 +00003441 if (getLangOptions().CPlusPlus0x) {
3442 Consumer.addKeywordResult(Context, "alignof");
3443 Consumer.addKeywordResult(Context, "nullptr");
3444 }
3445 }
3446 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003447
Douglas Gregoraaf87162010-04-14 20:04:41 +00003448 if (WantRemainingKeywords) {
3449 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
3450 // Statements.
3451 const char *CStmts[] = {
3452 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3453 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3454 for (unsigned I = 0; I != NumCStmts; ++I)
3455 Consumer.addKeywordResult(Context, CStmts[I]);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003456
Douglas Gregoraaf87162010-04-14 20:04:41 +00003457 if (getLangOptions().CPlusPlus) {
3458 Consumer.addKeywordResult(Context, "catch");
3459 Consumer.addKeywordResult(Context, "try");
3460 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003461
Douglas Gregoraaf87162010-04-14 20:04:41 +00003462 if (S && S->getBreakParent())
3463 Consumer.addKeywordResult(Context, "break");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003464
Douglas Gregoraaf87162010-04-14 20:04:41 +00003465 if (S && S->getContinueParent())
3466 Consumer.addKeywordResult(Context, "continue");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003467
John McCall781472f2010-08-25 08:40:02 +00003468 if (!getCurFunction()->SwitchStack.empty()) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00003469 Consumer.addKeywordResult(Context, "case");
3470 Consumer.addKeywordResult(Context, "default");
3471 }
3472 } else {
3473 if (getLangOptions().CPlusPlus) {
3474 Consumer.addKeywordResult(Context, "namespace");
3475 Consumer.addKeywordResult(Context, "template");
3476 }
3477
3478 if (S && S->isClassScope()) {
3479 Consumer.addKeywordResult(Context, "explicit");
3480 Consumer.addKeywordResult(Context, "friend");
3481 Consumer.addKeywordResult(Context, "mutable");
3482 Consumer.addKeywordResult(Context, "private");
3483 Consumer.addKeywordResult(Context, "protected");
3484 Consumer.addKeywordResult(Context, "public");
3485 Consumer.addKeywordResult(Context, "virtual");
3486 }
3487 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003488
Douglas Gregoraaf87162010-04-14 20:04:41 +00003489 if (getLangOptions().CPlusPlus) {
3490 Consumer.addKeywordResult(Context, "using");
3491
3492 if (getLangOptions().CPlusPlus0x)
3493 Consumer.addKeywordResult(Context, "static_assert");
3494 }
3495 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003496
Douglas Gregoraaf87162010-04-14 20:04:41 +00003497 // If we haven't found anything, we're done.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003498 if (Consumer.empty()) {
3499 // If this was an unqualified lookup, note that no correction was found.
3500 if (IsUnqualifiedLookup)
3501 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003502
Douglas Gregor931f98a2010-04-14 17:09:22 +00003503 return DeclarationName();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003504 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003505
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003506 // Make sure that the user typed at least 3 characters for each correction
Douglas Gregore24b5752010-10-14 20:34:08 +00003507 // made. Otherwise, we don't even both looking at the results.
Douglas Gregor53e4b552010-10-26 17:18:00 +00003508
3509 // We also suppress exact matches; those should be handled by a
3510 // different mechanism (e.g., one that introduces qualification in
3511 // C++).
Douglas Gregore24b5752010-10-14 20:34:08 +00003512 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003513 if (ED > 0 && Typo->getName().size() / ED < 3) {
3514 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregor157a3ff2010-10-27 14:20:34 +00003515 if (IsUnqualifiedLookup)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003516 (void)UnqualifiedTyposCorrected[Typo];
3517
Douglas Gregore24b5752010-10-14 20:34:08 +00003518 return DeclarationName();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003519 }
Douglas Gregore24b5752010-10-14 20:34:08 +00003520
3521 // Weed out any names that could not be found by name lookup.
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003522 bool LastLookupWasAccepted = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003523 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
Douglas Gregoraaf87162010-04-14 20:04:41 +00003524 IEnd = Consumer.end();
Douglas Gregore24b5752010-10-14 20:34:08 +00003525 I != IEnd; /* Increment in loop. */) {
3526 // Keywords are always found.
3527 if (I->second) {
3528 ++I;
3529 continue;
Douglas Gregoraaf87162010-04-14 20:04:41 +00003530 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003531
Douglas Gregore24b5752010-10-14 20:34:08 +00003532 // Perform name lookup on this name.
3533 IdentifierInfo *Name = &Context.Idents.get(I->getKey());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003534 LookupPotentialTypoResult(*this, Res, Name, S, SS, MemberContext,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003535 EnteringContext, CTC);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003536
Douglas Gregore24b5752010-10-14 20:34:08 +00003537 switch (Res.getResultKind()) {
3538 case LookupResult::NotFound:
3539 case LookupResult::NotFoundInCurrentInstantiation:
3540 case LookupResult::Ambiguous:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003541 // We didn't find this name in our scope, or didn't like what we found;
Douglas Gregore24b5752010-10-14 20:34:08 +00003542 // ignore it.
3543 Res.suppressDiagnostics();
3544 {
3545 TypoCorrectionConsumer::iterator Next = I;
3546 ++Next;
3547 Consumer.erase(I);
3548 I = Next;
3549 }
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003550 LastLookupWasAccepted = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003551 break;
3552
Douglas Gregore24b5752010-10-14 20:34:08 +00003553 case LookupResult::Found:
3554 case LookupResult::FoundOverloaded:
3555 case LookupResult::FoundUnresolvedValue:
3556 ++I;
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003557 LastLookupWasAccepted = true;
Douglas Gregoraaf87162010-04-14 20:04:41 +00003558 break;
Douglas Gregore24b5752010-10-14 20:34:08 +00003559 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003560
Douglas Gregore24b5752010-10-14 20:34:08 +00003561 if (Res.isAmbiguous()) {
3562 // We don't deal with ambiguities.
3563 Res.suppressDiagnostics();
3564 Res.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003565 return DeclarationName();
3566 }
Douglas Gregoraaf87162010-04-14 20:04:41 +00003567 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003568
Douglas Gregore24b5752010-10-14 20:34:08 +00003569 // If only a single name remains, return that result.
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003570 if (Consumer.size() == 1) {
3571 IdentifierInfo *Name = &Context.Idents.get(Consumer.begin()->getKey());
Douglas Gregorf98402d2010-10-20 01:01:57 +00003572 if (Consumer.begin()->second) {
3573 Res.suppressDiagnostics();
3574 Res.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003575
Douglas Gregor53e4b552010-10-26 17:18:00 +00003576 // Don't correct to a keyword that's the same as the typo; the keyword
3577 // wasn't actually in scope.
3578 if (ED == 0) {
3579 Res.setLookupName(Typo);
3580 return DeclarationName();
3581 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003582
Douglas Gregorf98402d2010-10-20 01:01:57 +00003583 } else if (!LastLookupWasAccepted) {
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003584 // Perform name lookup on this name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003585 LookupPotentialTypoResult(*this, Res, Name, S, SS, MemberContext,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003586 EnteringContext, CTC);
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003587 }
3588
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003589 // Record the correction for unqualified lookup.
3590 if (IsUnqualifiedLookup)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003591 UnqualifiedTyposCorrected[Typo]
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003592 = std::make_pair(Name->getName(), Consumer.begin()->second);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003593
3594 return &Context.Idents.get(Consumer.begin()->getKey());
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003595 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003596 else if (Consumer.size() > 1 && CTC == CTC_ObjCMessageReceiver
Douglas Gregor7b824e82010-10-15 13:35:25 +00003597 && Consumer["super"]) {
3598 // Prefix 'super' when we're completing in a message-receiver
3599 // context.
3600 Res.suppressDiagnostics();
3601 Res.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003602
Douglas Gregor53e4b552010-10-26 17:18:00 +00003603 // Don't correct to a keyword that's the same as the typo; the keyword
3604 // wasn't actually in scope.
3605 if (ED == 0) {
3606 Res.setLookupName(Typo);
3607 return DeclarationName();
3608 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003609
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003610 // Record the correction for unqualified lookup.
3611 if (IsUnqualifiedLookup)
3612 UnqualifiedTyposCorrected[Typo]
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003613 = std::make_pair("super", Consumer.begin()->second);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003614
Douglas Gregor7b824e82010-10-15 13:35:25 +00003615 return &Context.Idents.get("super");
3616 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003617
Douglas Gregore24b5752010-10-14 20:34:08 +00003618 Res.suppressDiagnostics();
3619 Res.setLookupName(Typo);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003620 Res.clear();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003621 // Record the correction for unqualified lookup.
3622 if (IsUnqualifiedLookup)
3623 (void)UnqualifiedTyposCorrected[Typo];
3624
Douglas Gregor931f98a2010-04-14 17:09:22 +00003625 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003626}