blob: 5507c5770dfd32459ee93ad2377c799799e80460 [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 Gregord8bba9c2011-06-28 16:20:02 +000023#include "clang/Sema/TypoCorrection.h"
Douglas Gregor7176fff2009-01-15 00:26:24 +000024#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000025#include "clang/AST/CXXInheritance.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000026#include "clang/AST/Decl.h"
27#include "clang/AST/DeclCXX.h"
28#include "clang/AST/DeclObjC.h"
Douglas Gregor42af25f2009-05-11 19:58:34 +000029#include "clang/AST/DeclTemplate.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000030#include "clang/AST/Expr.h"
Douglas Gregordaa439a2009-07-08 10:57:20 +000031#include "clang/AST/ExprCXX.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000032#include "clang/Basic/Builtins.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000033#include "clang/Basic/LangOptions.h"
Douglas Gregora1f21142012-02-01 17:04:21 +000034#include "llvm/ADT/SetVector.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000035#include "llvm/ADT/STLExtras.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000036#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregore24b5752010-10-14 20:34:08 +000037#include "llvm/ADT/StringMap.h"
Chris Lattnerb5f65472011-07-18 01:54:02 +000038#include "llvm/ADT/TinyPtrVector.h"
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +000039#include "llvm/ADT/edit_distance.h"
John McCall6e247262009-10-10 05:48:19 +000040#include "llvm/Support/ErrorHandling.h"
Douglas Gregore24b5752010-10-14 20:34:08 +000041#include <limits>
Douglas Gregor546be3c2009-12-30 17:04:44 +000042#include <list>
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +000043#include <set>
Douglas Gregor2a3009a2009-02-03 19:21:40 +000044#include <vector>
45#include <iterator>
46#include <utility>
47#include <algorithm>
Douglas Gregord8bba9c2011-06-28 16:20:02 +000048#include <map>
Douglas Gregoreb11cd02009-01-14 22:20:51 +000049
50using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000051using namespace sema;
Douglas Gregoreb11cd02009-01-14 22:20:51 +000052
John McCalld7be78a2009-11-10 07:01:13 +000053namespace {
54 class UnqualUsingEntry {
55 const DeclContext *Nominated;
56 const DeclContext *CommonAncestor;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000057
John McCalld7be78a2009-11-10 07:01:13 +000058 public:
59 UnqualUsingEntry(const DeclContext *Nominated,
60 const DeclContext *CommonAncestor)
61 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
62 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000063
John McCalld7be78a2009-11-10 07:01:13 +000064 const DeclContext *getCommonAncestor() const {
65 return CommonAncestor;
66 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000067
John McCalld7be78a2009-11-10 07:01:13 +000068 const DeclContext *getNominatedNamespace() const {
69 return Nominated;
70 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000071
John McCalld7be78a2009-11-10 07:01:13 +000072 // Sort by the pointer value of the common ancestor.
73 struct Comparator {
74 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
75 return L.getCommonAncestor() < R.getCommonAncestor();
76 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000077
John McCalld7be78a2009-11-10 07:01:13 +000078 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
79 return E.getCommonAncestor() < DC;
80 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000081
John McCalld7be78a2009-11-10 07:01:13 +000082 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
83 return DC < E.getCommonAncestor();
84 }
85 };
86 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +000087
John McCalld7be78a2009-11-10 07:01:13 +000088 /// A collection of using directives, as used by C++ unqualified
89 /// lookup.
90 class UnqualUsingDirectiveSet {
Chris Lattner5f9e2722011-07-23 10:55:15 +000091 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000092
John McCalld7be78a2009-11-10 07:01:13 +000093 ListTy list;
94 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000095
John McCalld7be78a2009-11-10 07:01:13 +000096 public:
97 UnqualUsingDirectiveSet() {}
Douglas Gregor2a3009a2009-02-03 19:21:40 +000098
John McCalld7be78a2009-11-10 07:01:13 +000099 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000100 // C++ [namespace.udir]p1:
John McCalld7be78a2009-11-10 07:01:13 +0000101 // During unqualified name lookup, the names appear as if they
102 // were declared in the nearest enclosing namespace which contains
103 // both the using-directive and the nominated namespace.
104 DeclContext *InnermostFileDC
105 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
106 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000107
John McCalld7be78a2009-11-10 07:01:13 +0000108 for (; S; S = S->getParent()) {
John McCalld7be78a2009-11-10 07:01:13 +0000109 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
110 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
111 visit(Ctx, EffectiveDC);
112 } else {
113 Scope::udir_iterator I = S->using_directives_begin(),
114 End = S->using_directives_end();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000115
John McCalld7be78a2009-11-10 07:01:13 +0000116 for (; I != End; ++I)
John McCalld226f652010-08-21 09:40:31 +0000117 visit(*I, InnermostFileDC);
John McCalld7be78a2009-11-10 07:01:13 +0000118 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000119 }
120 }
John McCalld7be78a2009-11-10 07:01:13 +0000121
122 // Visits a context and collect all of its using directives
123 // recursively. Treats all using directives as if they were
124 // declared in the context.
125 //
126 // A given context is only every visited once, so it is important
127 // that contexts be visited from the inside out in order to get
128 // the effective DCs right.
129 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
130 if (!visited.insert(DC))
131 return;
132
133 addUsingDirectives(DC, EffectiveDC);
134 }
135
136 // Visits a using directive and collects all of its using
137 // directives recursively. Treats all using directives as if they
138 // were declared in the effective DC.
139 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
140 DeclContext *NS = UD->getNominatedNamespace();
141 if (!visited.insert(NS))
142 return;
143
144 addUsingDirective(UD, EffectiveDC);
145 addUsingDirectives(NS, EffectiveDC);
146 }
147
148 // Adds all the using directives in a context (and those nominated
149 // by its using directives, transitively) as if they appeared in
150 // the given effective context.
151 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000152 SmallVector<DeclContext*,4> queue;
John McCalld7be78a2009-11-10 07:01:13 +0000153 while (true) {
154 DeclContext::udir_iterator I, End;
155 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
156 UsingDirectiveDecl *UD = *I;
157 DeclContext *NS = UD->getNominatedNamespace();
158 if (visited.insert(NS)) {
159 addUsingDirective(UD, EffectiveDC);
160 queue.push_back(NS);
161 }
162 }
163
164 if (queue.empty())
165 return;
166
167 DC = queue.back();
168 queue.pop_back();
169 }
170 }
171
172 // Add a using directive as if it had been declared in the given
173 // context. This helps implement C++ [namespace.udir]p3:
174 // The using-directive is transitive: if a scope contains a
175 // using-directive that nominates a second namespace that itself
176 // contains using-directives, the effect is as if the
177 // using-directives from the second namespace also appeared in
178 // the first.
179 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
180 // Find the common ancestor between the effective context and
181 // the nominated namespace.
182 DeclContext *Common = UD->getNominatedNamespace();
183 while (!Common->Encloses(EffectiveDC))
184 Common = Common->getParent();
John McCall12ea5782009-11-10 09:20:04 +0000185 Common = Common->getPrimaryContext();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000186
John McCalld7be78a2009-11-10 07:01:13 +0000187 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
188 }
189
190 void done() {
191 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
192 }
193
John McCalld7be78a2009-11-10 07:01:13 +0000194 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000195
John McCalld7be78a2009-11-10 07:01:13 +0000196 const_iterator begin() const { return list.begin(); }
197 const_iterator end() const { return list.end(); }
198
199 std::pair<const_iterator,const_iterator>
200 getNamespacesFor(DeclContext *DC) const {
John McCall12ea5782009-11-10 09:20:04 +0000201 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCalld7be78a2009-11-10 07:01:13 +0000202 UnqualUsingEntry::Comparator());
203 }
204 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000205}
206
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000207// Retrieve the set of identifier namespaces that correspond to a
208// specific kind of name lookup.
John McCall1d7c5282009-12-18 10:40:03 +0000209static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
210 bool CPlusPlus,
211 bool Redeclaration) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000212 unsigned IDNS = 0;
213 switch (NameKind) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +0000214 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000215 case Sema::LookupOrdinaryName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000216 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000217 IDNS = Decl::IDNS_Ordinary;
John McCall1d7c5282009-12-18 10:40:03 +0000218 if (CPlusPlus) {
John McCall0d6b1642010-04-23 18:46:30 +0000219 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattner337e5502011-02-18 01:27:55 +0000220 if (Redeclaration)
221 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCall1d7c5282009-12-18 10:40:03 +0000222 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000223 break;
224
John McCall76d32642010-04-24 01:30:58 +0000225 case Sema::LookupOperatorName:
226 // Operator lookup is its own crazy thing; it is not the same
227 // as (e.g.) looking up an operator name for redeclaration.
228 assert(!Redeclaration && "cannot do redeclaration operator lookup");
229 IDNS = Decl::IDNS_NonMemberOperator;
230 break;
231
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000232 case Sema::LookupTagName:
John McCall0d6b1642010-04-23 18:46:30 +0000233 if (CPlusPlus) {
234 IDNS = Decl::IDNS_Type;
235
236 // When looking for a redeclaration of a tag name, we add:
237 // 1) TagFriend to find undeclared friend decls
238 // 2) Namespace because they can't "overload" with tag decls.
239 // 3) Tag because it includes class templates, which can't
240 // "overload" with tag decls.
241 if (Redeclaration)
242 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
243 } else {
244 IDNS = Decl::IDNS_Tag;
245 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000246 break;
Chris Lattner337e5502011-02-18 01:27:55 +0000247 case Sema::LookupLabel:
248 IDNS = Decl::IDNS_Label;
249 break;
250
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000251 case Sema::LookupMemberName:
252 IDNS = Decl::IDNS_Member;
253 if (CPlusPlus)
Mike Stump1eb44332009-09-09 15:08:12 +0000254 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000255 break;
256
257 case Sema::LookupNestedNameSpecifierName:
John McCall0d6b1642010-04-23 18:46:30 +0000258 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
259 break;
260
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000261 case Sema::LookupNamespaceName:
John McCall0d6b1642010-04-23 18:46:30 +0000262 IDNS = Decl::IDNS_Namespace;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000263 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000264
John McCall9f54ad42009-12-10 09:41:52 +0000265 case Sema::LookupUsingDeclName:
266 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
267 | Decl::IDNS_Member | Decl::IDNS_Using;
268 break;
269
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000270 case Sema::LookupObjCProtocolName:
271 IDNS = Decl::IDNS_ObjCProtocol;
272 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000273
Douglas Gregor8071e422010-08-15 06:18:01 +0000274 case Sema::LookupAnyName:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000275 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor8071e422010-08-15 06:18:01 +0000276 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
277 | Decl::IDNS_Type;
278 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000279 }
280 return IDNS;
281}
282
John McCall1d7c5282009-12-18 10:40:03 +0000283void LookupResult::configure() {
Chris Lattner337e5502011-02-18 01:27:55 +0000284 IDNS = getIDNS(LookupKind, SemaRef.getLangOptions().CPlusPlus,
John McCall1d7c5282009-12-18 10:40:03 +0000285 isForRedeclaration());
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000286
287 // If we're looking for one of the allocation or deallocation
288 // operators, make sure that the implicitly-declared new and delete
289 // operators can be found.
290 if (!isForRedeclaration()) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000291 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000292 case OO_New:
293 case OO_Delete:
294 case OO_Array_New:
295 case OO_Array_Delete:
296 SemaRef.DeclareGlobalNewDelete();
297 break;
298
299 default:
300 break;
301 }
302 }
John McCall1d7c5282009-12-18 10:40:03 +0000303}
304
John McCall2a7fb272010-08-25 05:32:35 +0000305void LookupResult::sanity() const {
306 assert(ResultKind != NotFound || Decls.size() == 0);
307 assert(ResultKind != Found || Decls.size() == 1);
308 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
309 (Decls.size() == 1 &&
310 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
311 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
312 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorf17b58c2010-10-22 22:08:47 +0000313 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
314 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall2a7fb272010-08-25 05:32:35 +0000315 assert((Paths != NULL) == (ResultKind == Ambiguous &&
316 (Ambiguity == AmbiguousBaseSubobjectTypes ||
317 Ambiguity == AmbiguousBaseSubobjects)));
318}
John McCall2a7fb272010-08-25 05:32:35 +0000319
John McCallf36e02d2009-10-09 21:13:30 +0000320// Necessary because CXXBasePaths is not complete in Sema.h
John McCall7d384dd2009-11-18 07:57:50 +0000321void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCallf36e02d2009-10-09 21:13:30 +0000322 delete Paths;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000323}
324
Douglas Gregor55368912011-12-14 16:03:29 +0000325static NamedDecl *getVisibleDecl(NamedDecl *D);
326
327NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
328 return getVisibleDecl(D);
329}
330
John McCall7453ed42009-11-22 00:44:51 +0000331/// Resolves the result kind of this lookup.
John McCall7d384dd2009-11-18 07:57:50 +0000332void LookupResult::resolveKind() {
John McCallf36e02d2009-10-09 21:13:30 +0000333 unsigned N = Decls.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000334
John McCallf36e02d2009-10-09 21:13:30 +0000335 // Fast case: no possible ambiguity.
John McCall68263142009-11-18 22:49:29 +0000336 if (N == 0) {
John McCalldc5c7862010-01-15 21:27:01 +0000337 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall68263142009-11-18 22:49:29 +0000338 return;
339 }
340
John McCall7453ed42009-11-22 00:44:51 +0000341 // If there's a single decl, we need to examine it to decide what
342 // kind of lookup this is.
John McCall7ba107a2009-11-18 02:36:19 +0000343 if (N == 1) {
Douglas Gregor2b147f02010-04-25 21:15:30 +0000344 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
345 if (isa<FunctionTemplateDecl>(D))
John McCall7453ed42009-11-22 00:44:51 +0000346 ResultKind = FoundOverloaded;
Douglas Gregor2b147f02010-04-25 21:15:30 +0000347 else if (isa<UnresolvedUsingValueDecl>(D))
John McCall7ba107a2009-11-18 02:36:19 +0000348 ResultKind = FoundUnresolvedValue;
349 return;
350 }
John McCallf36e02d2009-10-09 21:13:30 +0000351
John McCall6e247262009-10-10 05:48:19 +0000352 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000353 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000354
John McCallf36e02d2009-10-09 21:13:30 +0000355 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000356 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000357
John McCallf36e02d2009-10-09 21:13:30 +0000358 bool Ambiguous = false;
359 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000360 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000361
362 unsigned UniqueTagIndex = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000363
John McCallf36e02d2009-10-09 21:13:30 +0000364 unsigned I = 0;
365 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000366 NamedDecl *D = Decls[I]->getUnderlyingDecl();
367 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000368
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000369 // Redeclarations of types via typedef can occur both within a scope
370 // and, through using declarations and directives, across scopes. There is
371 // no ambiguity if they all refer to the same type, so unique based on the
372 // canonical type.
373 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
374 if (!TD->getDeclContext()->isRecord()) {
375 QualType T = SemaRef.Context.getTypeDeclType(TD);
376 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
377 // The type is not unique; pull something off the back and continue
378 // at this index.
379 Decls[I] = Decls[--N];
380 continue;
381 }
382 }
383 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000384
John McCall314be4e2009-11-17 07:50:12 +0000385 if (!Unique.insert(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000386 // If it's not unique, pull something off the back (and
387 // continue at this index).
388 Decls[I] = Decls[--N];
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000389 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000390 }
391
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000392 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000393
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000394 if (isa<UnresolvedUsingValueDecl>(D)) {
395 HasUnresolved = true;
396 } else if (isa<TagDecl>(D)) {
397 if (HasTag)
398 Ambiguous = true;
399 UniqueTagIndex = I;
400 HasTag = true;
401 } else if (isa<FunctionTemplateDecl>(D)) {
402 HasFunction = true;
403 HasFunctionTemplate = true;
404 } else if (isa<FunctionDecl>(D)) {
405 HasFunction = true;
406 } else {
407 if (HasNonFunction)
408 Ambiguous = true;
409 HasNonFunction = true;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000410 }
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000411 I++;
Mike Stump1eb44332009-09-09 15:08:12 +0000412 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000413
John McCallf36e02d2009-10-09 21:13:30 +0000414 // C++ [basic.scope.hiding]p2:
415 // A class name or enumeration name can be hidden by the name of
416 // an object, function, or enumerator declared in the same
417 // scope. If a class or enumeration name and an object, function,
418 // or enumerator are declared in the same scope (in any order)
419 // with the same name, the class or enumeration name is hidden
420 // wherever the object, function, or enumerator name is visible.
421 // But it's still an error if there are distinct tag types found,
422 // even if they're not visible. (ref?)
John McCallfda8e122009-12-03 00:58:24 +0000423 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregor77a1a882010-10-23 16:06:17 +0000424 (HasFunction || HasNonFunction || HasUnresolved)) {
425 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
426 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
427 Decls[UniqueTagIndex] = Decls[--N];
428 else
429 Ambiguous = true;
430 }
Anders Carlsson8b50d012009-06-26 03:37:05 +0000431
John McCallf36e02d2009-10-09 21:13:30 +0000432 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000433
John McCallfda8e122009-12-03 00:58:24 +0000434 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000435 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000436
John McCallf36e02d2009-10-09 21:13:30 +0000437 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000438 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000439 else if (HasUnresolved)
440 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000441 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000442 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000443 else
John McCalla24dc2e2009-11-17 02:14:36 +0000444 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000445}
446
John McCall7d384dd2009-11-18 07:57:50 +0000447void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall6b2accb2010-02-10 09:31:12 +0000448 CXXBasePaths::const_paths_iterator I, E;
John McCallf36e02d2009-10-09 21:13:30 +0000449 DeclContext::lookup_iterator DI, DE;
450 for (I = P.begin(), E = P.end(); I != E; ++I)
451 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
452 addDecl(*DI);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000453}
454
John McCall7d384dd2009-11-18 07:57:50 +0000455void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000456 Paths = new CXXBasePaths;
457 Paths->swap(P);
458 addDeclsFromBasePaths(*Paths);
459 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000460 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000461}
462
John McCall7d384dd2009-11-18 07:57:50 +0000463void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000464 Paths = new CXXBasePaths;
465 Paths->swap(P);
466 addDeclsFromBasePaths(*Paths);
467 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000468 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000469}
470
Chris Lattner5f9e2722011-07-23 10:55:15 +0000471void LookupResult::print(raw_ostream &Out) {
John McCallf36e02d2009-10-09 21:13:30 +0000472 Out << Decls.size() << " result(s)";
473 if (isAmbiguous()) Out << ", ambiguous";
474 if (Paths) Out << ", base paths present";
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000475
John McCallf36e02d2009-10-09 21:13:30 +0000476 for (iterator I = begin(), E = end(); I != E; ++I) {
477 Out << "\n";
478 (*I)->print(Out, 2);
479 }
480}
481
Douglas Gregor85910982010-02-12 05:48:04 +0000482/// \brief Lookup a builtin function, when name lookup would otherwise
483/// fail.
484static bool LookupBuiltin(Sema &S, LookupResult &R) {
485 Sema::LookupNameKind NameKind = R.getLookupKind();
486
487 // If we didn't find a use of this identifier, and if the identifier
488 // corresponds to a compiler builtin, create the decl object for the builtin
489 // now, injecting it into translation unit scope, and return it.
490 if (NameKind == Sema::LookupOrdinaryName ||
491 NameKind == Sema::LookupRedeclarationWithLinkage) {
492 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
493 if (II) {
494 // If this is a builtin on this (or all) targets, create the decl.
495 if (unsigned BuiltinID = II->getBuiltinID()) {
496 // In C++, we don't have any predefined library functions like
497 // 'malloc'. Instead, we'll just error.
498 if (S.getLangOptions().CPlusPlus &&
499 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
500 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000501
502 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
503 BuiltinID, S.TUScope,
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000504 R.isForRedeclaration(),
505 R.getNameLoc())) {
Douglas Gregor85910982010-02-12 05:48:04 +0000506 R.addDecl(D);
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000507 return true;
508 }
509
510 if (R.isForRedeclaration()) {
511 // If we're redeclaring this function anyway, forget that
512 // this was a builtin at all.
513 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
514 }
515
516 return false;
Douglas Gregor85910982010-02-12 05:48:04 +0000517 }
518 }
519 }
520
521 return false;
522}
523
Douglas Gregor4923aa22010-07-02 20:37:36 +0000524/// \brief Determine whether we can declare a special member function within
525/// the class at this point.
526static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
527 const CXXRecordDecl *Class) {
John McCallb3b50a82010-08-11 23:52:36 +0000528 // Don't do it if the class is invalid.
529 if (Class->isInvalidDecl())
530 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000531
Douglas Gregor4923aa22010-07-02 20:37:36 +0000532 // We need to have a definition for the class.
533 if (!Class->getDefinition() || Class->isDependentContext())
534 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000535
Douglas Gregor4923aa22010-07-02 20:37:36 +0000536 // We can't be in the middle of defining the class.
537 if (const RecordType *RecordTy
538 = Context.getTypeDeclType(Class)->getAs<RecordType>())
539 return !RecordTy->isBeingDefined();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000540
Douglas Gregor4923aa22010-07-02 20:37:36 +0000541 return false;
542}
543
544void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregor22584312010-07-02 23:41:54 +0000545 if (!CanDeclareSpecialMemberFunction(Context, Class))
546 return;
Douglas Gregor18274032010-07-03 00:47:00 +0000547
548 // If the default constructor has not yet been declared, do so now.
Sean Huntcdee3fe2011-05-11 22:34:38 +0000549 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +0000550 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000551
Douglas Gregor22584312010-07-02 23:41:54 +0000552 // If the copy constructor has not yet been declared, do so now.
553 if (!Class->hasDeclaredCopyConstructor())
554 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000555
Douglas Gregora376d102010-07-02 21:50:04 +0000556 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000557 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +0000558 DeclareImplicitCopyAssignment(Class);
559
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000560 if (getLangOptions().CPlusPlus0x) {
561 // If the move constructor has not yet been declared, do so now.
562 if (Class->needsImplicitMoveConstructor())
563 DeclareImplicitMoveConstructor(Class); // might not actually do it
564
565 // If the move assignment operator has not yet been declared, do so now.
566 if (Class->needsImplicitMoveAssignment())
567 DeclareImplicitMoveAssignment(Class); // might not actually do it
568 }
569
Douglas Gregor4923aa22010-07-02 20:37:36 +0000570 // If the destructor has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000571 if (!Class->hasDeclaredDestructor())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000572 DeclareImplicitDestructor(Class);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000573}
574
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000575/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregora376d102010-07-02 21:50:04 +0000576/// special member function.
577static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
578 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000579 case DeclarationName::CXXConstructorName:
Douglas Gregora376d102010-07-02 21:50:04 +0000580 case DeclarationName::CXXDestructorName:
581 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000582
Douglas Gregora376d102010-07-02 21:50:04 +0000583 case DeclarationName::CXXOperatorName:
584 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000585
Douglas Gregora376d102010-07-02 21:50:04 +0000586 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000587 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000588 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000589
Douglas Gregora376d102010-07-02 21:50:04 +0000590 return false;
591}
592
593/// \brief If there are any implicit member functions with the given name
594/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000595static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregora376d102010-07-02 21:50:04 +0000596 DeclarationName Name,
597 const DeclContext *DC) {
598 if (!DC)
599 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000600
Douglas Gregora376d102010-07-02 21:50:04 +0000601 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000602 case DeclarationName::CXXConstructorName:
603 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor18274032010-07-03 00:47:00 +0000604 if (Record->getDefinition() &&
605 CanDeclareSpecialMemberFunction(S.Context, Record)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000606 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Sean Huntcdee3fe2011-05-11 22:34:38 +0000607 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000608 S.DeclareImplicitDefaultConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +0000609 if (!Record->hasDeclaredCopyConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000610 S.DeclareImplicitCopyConstructor(Class);
611 if (S.getLangOptions().CPlusPlus0x &&
612 Record->needsImplicitMoveConstructor())
613 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +0000614 }
Douglas Gregor22584312010-07-02 23:41:54 +0000615 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000616
Douglas Gregora376d102010-07-02 21:50:04 +0000617 case DeclarationName::CXXDestructorName:
618 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
619 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
620 CanDeclareSpecialMemberFunction(S.Context, Record))
621 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregora376d102010-07-02 21:50:04 +0000622 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000623
Douglas Gregora376d102010-07-02 21:50:04 +0000624 case DeclarationName::CXXOperatorName:
625 if (Name.getCXXOverloadedOperator() != OO_Equal)
626 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000627
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000628 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
629 if (Record->getDefinition() &&
630 CanDeclareSpecialMemberFunction(S.Context, Record)) {
631 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
632 if (!Record->hasDeclaredCopyAssignment())
633 S.DeclareImplicitCopyAssignment(Class);
634 if (S.getLangOptions().CPlusPlus0x &&
635 Record->needsImplicitMoveAssignment())
636 S.DeclareImplicitMoveAssignment(Class);
637 }
638 }
Douglas Gregora376d102010-07-02 21:50:04 +0000639 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000640
Douglas Gregora376d102010-07-02 21:50:04 +0000641 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000642 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000643 }
644}
Douglas Gregor4923aa22010-07-02 20:37:36 +0000645
John McCallf36e02d2009-10-09 21:13:30 +0000646// Adds all qualifying matches for a name within a decl context to the
647// given lookup result. Returns true if any matches were found.
Douglas Gregor85910982010-02-12 05:48:04 +0000648static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000649 bool Found = false;
650
Douglas Gregor4923aa22010-07-02 20:37:36 +0000651 // Lazily declare C++ special member functions.
Douglas Gregora376d102010-07-02 21:50:04 +0000652 if (S.getLangOptions().CPlusPlus)
653 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000654
Douglas Gregor4923aa22010-07-02 20:37:36 +0000655 // Perform lookup into this declaration context.
John McCalld7be78a2009-11-10 07:01:13 +0000656 DeclContext::lookup_const_iterator I, E;
Douglas Gregor48026d22010-01-11 18:40:55 +0000657 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall46460a62010-01-20 21:53:11 +0000658 NamedDecl *D = *I;
Douglas Gregor55368912011-12-14 16:03:29 +0000659 if ((D = R.getAcceptableDecl(D))) {
John McCall46460a62010-01-20 21:53:11 +0000660 R.addDecl(D);
Douglas Gregor48026d22010-01-11 18:40:55 +0000661 Found = true;
662 }
663 }
John McCallf36e02d2009-10-09 21:13:30 +0000664
Douglas Gregor85910982010-02-12 05:48:04 +0000665 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
666 return true;
667
Douglas Gregor48026d22010-01-11 18:40:55 +0000668 if (R.getLookupName().getNameKind()
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000669 != DeclarationName::CXXConversionFunctionName ||
670 R.getLookupName().getCXXNameType()->isDependentType() ||
671 !isa<CXXRecordDecl>(DC))
672 return Found;
673
674 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000675 // A specialization of a conversion function template is not found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000676 // name lookup. Instead, any conversion function templates visible in the
677 // context of the use are considered. [...]
678 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCall5e1cdac2011-10-07 06:10:15 +0000679 if (!Record->isCompleteDefinition())
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000680 return Found;
681
682 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000683 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000684 UEnd = Unresolved->end(); U != UEnd; ++U) {
685 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
686 if (!ConvTemplate)
687 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000688
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000689 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000690 // add the conversion function template. When we deduce template
691 // arguments for specializations, we'll end up unifying the return
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000692 // type of the new declaration with the type of the function template.
693 if (R.isForRedeclaration()) {
694 R.addDecl(ConvTemplate);
695 Found = true;
696 continue;
697 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000698
Douglas Gregor48026d22010-01-11 18:40:55 +0000699 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000700 // [...] For each such operator, if argument deduction succeeds
701 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000702 // name lookup.
703 //
704 // When referencing a conversion function for any purpose other than
705 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000706 // result), perform template argument deduction and place the
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000707 // specialization into the result set. We do this to avoid forcing all
708 // callers to perform special deduction for conversion functions.
John McCall2a7fb272010-08-25 05:32:35 +0000709 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000710 FunctionDecl *Specialization = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000711
712 const FunctionProtoType *ConvProto
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000713 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
714 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3f477a12010-01-12 01:17:50 +0000715
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000716 // Compute the type of the function that we would expect the conversion
717 // function to have, if it were to match the name given.
718 // FIXME: Calling convention!
John McCalle23cf432010-12-14 08:05:40 +0000719 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
720 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
Sebastian Redl8b5b4092011-03-06 10:52:04 +0000721 EPI.ExceptionSpecType = EST_None;
John McCalle23cf432010-12-14 08:05:40 +0000722 EPI.NumExceptions = 0;
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000723 QualType ExpectedType
724 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
John McCalle23cf432010-12-14 08:05:40 +0000725 0, 0, EPI);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000726
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000727 // Perform template argument deduction against the type that we would
728 // expect the function to have.
729 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
730 Specialization, Info)
731 == Sema::TDK_Success) {
732 R.addDecl(Specialization);
733 Found = true;
Douglas Gregor48026d22010-01-11 18:40:55 +0000734 }
735 }
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000736
John McCallf36e02d2009-10-09 21:13:30 +0000737 return Found;
738}
739
John McCalld7be78a2009-11-10 07:01:13 +0000740// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000741static bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000742CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregor85910982010-02-12 05:48:04 +0000743 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000744
745 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
746
John McCalld7be78a2009-11-10 07:01:13 +0000747 // Perform direct name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +0000748 bool Found = LookupDirect(S, R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000749
John McCalld7be78a2009-11-10 07:01:13 +0000750 // Perform direct name lookup into the namespaces nominated by the
751 // using directives whose common ancestor is this namespace.
752 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
753 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000754
John McCalld7be78a2009-11-10 07:01:13 +0000755 for (; UI != UEnd; ++UI)
Douglas Gregor85910982010-02-12 05:48:04 +0000756 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000757 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000758
759 R.resolveKind();
760
761 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000762}
763
764static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000765 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000766 return Ctx->isFileContext();
767 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000768}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000769
Douglas Gregor711be1e2010-03-15 14:33:29 +0000770// Find the next outer declaration context from this scope. This
771// routine actually returns the semantic outer context, which may
772// differ from the lexical context (encoded directly in the Scope
773// stack) when we are parsing a member of a class template. In this
774// case, the second element of the pair will be true, to indicate that
775// name lookup should continue searching in this semantic context when
776// it leaves the current template parameter scope.
777static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
778 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
779 DeclContext *Lexical = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000780 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor711be1e2010-03-15 14:33:29 +0000781 OuterS = OuterS->getParent()) {
782 if (OuterS->getEntity()) {
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000783 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor711be1e2010-03-15 14:33:29 +0000784 break;
785 }
786 }
787
788 // C++ [temp.local]p8:
789 // In the definition of a member of a class template that appears
790 // outside of the namespace containing the class template
791 // definition, the name of a template-parameter hides the name of
792 // a member of this namespace.
793 //
794 // Example:
795 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000796 // namespace N {
797 // class C { };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000798 //
799 // template<class T> class B {
800 // void f(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000801 // };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000802 // }
803 //
804 // template<class C> void N::B<C>::f(C) {
805 // C b; // C is the template parameter, not N::C
806 // }
807 //
808 // In this example, the lexical context we return is the
809 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000810 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor711be1e2010-03-15 14:33:29 +0000811 !S->getParent()->isTemplateParamScope())
812 return std::make_pair(Lexical, false);
813
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000814 // Find the outermost template parameter scope.
Douglas Gregor711be1e2010-03-15 14:33:29 +0000815 // For the example, this is the scope for the template parameters of
816 // template<class C>.
817 Scope *OutermostTemplateScope = S->getParent();
818 while (OutermostTemplateScope->getParent() &&
819 OutermostTemplateScope->getParent()->isTemplateParamScope())
820 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000821
Douglas Gregor711be1e2010-03-15 14:33:29 +0000822 // Find the namespace context in which the original scope occurs. In
823 // the example, this is namespace N.
824 DeclContext *Semantic = DC;
825 while (!Semantic->isFileContext())
826 Semantic = Semantic->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000827
Douglas Gregor711be1e2010-03-15 14:33:29 +0000828 // Find the declaration context just outside of the template
829 // parameter scope. This is the context in which the template is
830 // being lexically declaration (a namespace context). In the
831 // example, this is the global scope.
832 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
833 Lexical->Encloses(Semantic))
834 return std::make_pair(Semantic, true);
835
836 return std::make_pair(Lexical, false);
Douglas Gregore942bbe2009-09-10 16:57:35 +0000837}
838
John McCalla24dc2e2009-11-17 02:14:36 +0000839bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCall1d7c5282009-12-18 10:40:03 +0000840 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000841
842 DeclarationName Name = R.getLookupName();
843
Douglas Gregora376d102010-07-02 21:50:04 +0000844 // If this is the name of an implicitly-declared special member function,
845 // go through the scope stack to implicitly declare
846 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
847 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
848 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
849 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
850 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000851
Douglas Gregora376d102010-07-02 21:50:04 +0000852 // Implicitly declare member functions with the name we're looking for, if in
853 // fact we are in a scope where it matters.
854
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000855 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000856 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000857 I = IdResolver.begin(Name),
858 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000859
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000860 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000861 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000862 // ...During unqualified name lookup (3.4.1), the names appear as if
863 // they were declared in the nearest enclosing namespace which contains
864 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000865 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000866 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000867 //
868 // For example:
869 // namespace A { int i; }
870 // void foo() {
871 // int i;
872 // {
873 // using namespace A;
874 // ++i; // finds local 'i', A::i appears at global scope
875 // }
876 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000877 //
Douglas Gregor711be1e2010-03-15 14:33:29 +0000878 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000879 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregord2235f62010-05-20 20:58:56 +0000880 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
881
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000882 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000883 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000884 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor55368912011-12-14 16:03:29 +0000885 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
John McCallf36e02d2009-10-09 21:13:30 +0000886 Found = true;
Douglas Gregor55368912011-12-14 16:03:29 +0000887 R.addDecl(ND);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000888 }
889 }
John McCallf36e02d2009-10-09 21:13:30 +0000890 if (Found) {
891 R.resolveKind();
Douglas Gregord2235f62010-05-20 20:58:56 +0000892 if (S->isClassScope())
893 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
894 R.setNamingClass(Record);
John McCallf36e02d2009-10-09 21:13:30 +0000895 return true;
896 }
897
Douglas Gregor711be1e2010-03-15 14:33:29 +0000898 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
899 S->getParent() && !S->getParent()->isTemplateParamScope()) {
900 // We've just searched the last template parameter scope and
901 // found nothing, so look into the the contexts between the
902 // lexical and semantic declaration contexts returned by
903 // findOuterContext(). This implements the name lookup behavior
904 // of C++ [temp.local]p8.
905 Ctx = OutsideOfTemplateParamDC;
906 OutsideOfTemplateParamDC = 0;
907 }
908
909 if (Ctx) {
910 DeclContext *OuterCtx;
911 bool SearchAfterTemplateScope;
912 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
913 if (SearchAfterTemplateScope)
914 OutsideOfTemplateParamDC = OuterCtx;
915
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000916 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-02-19 16:08:35 +0000917 // We do not directly look into transparent contexts, since
918 // those entities will be found in the nearest enclosing
919 // non-transparent context.
920 if (Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000921 continue;
Douglas Gregor36262b82010-02-19 16:08:35 +0000922
923 // We do not look directly into function or method contexts,
924 // since all of the local variables and parameters of the
925 // function/method are present within the Scope.
926 if (Ctx->isFunctionOrMethod()) {
927 // If we have an Objective-C instance method, look for ivars
928 // in the corresponding interface.
929 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
930 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
931 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
932 ObjCInterfaceDecl *ClassDeclared;
933 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000934 Name.getAsIdentifierInfo(),
Douglas Gregor36262b82010-02-19 16:08:35 +0000935 ClassDeclared)) {
Douglas Gregor55368912011-12-14 16:03:29 +0000936 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
937 R.addDecl(ND);
Douglas Gregor36262b82010-02-19 16:08:35 +0000938 R.resolveKind();
939 return true;
940 }
941 }
942 }
943 }
944
945 continue;
946 }
947
Douglas Gregore942bbe2009-09-10 16:57:35 +0000948 // Perform qualified name lookup into this context.
949 // FIXME: In some cases, we know that every name that could be found by
950 // this qualified name lookup will also be on the identifier chain. For
951 // example, inside a class without any base classes, we never need to
952 // perform qualified lookup because all of the members are on top of the
953 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000954 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +0000955 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +0000956 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000957 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000958 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000959
John McCalld7be78a2009-11-10 07:01:13 +0000960 // Stop if we ran out of scopes.
961 // FIXME: This really, really shouldn't be happening.
962 if (!S) return false;
963
Argyrios Kyrtzidis78f59112010-10-29 16:12:50 +0000964 // If we are looking for members, no need to look into global/namespace scope.
965 if (R.getLookupKind() == LookupMemberName)
966 return false;
967
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000968 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000969 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +0000970 //
Mike Stump390b4cc2009-05-16 07:39:55 +0000971 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
972 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000973
John McCalld7be78a2009-11-10 07:01:13 +0000974 UnqualUsingDirectiveSet UDirs;
975 UDirs.visitScopeChain(Initial, S);
976 UDirs.done();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000977
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000978 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000979 // Unqualified name lookup in C++ requires looking into scopes
980 // that aren't strictly lexical, and therefore we walk through the
981 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000982
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000983 for (; S; S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000984 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000985 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000986 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor55368912011-12-14 16:03:29 +0000987 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000988 // We found something. Look for anything else in our scope
989 // with this same name and in an acceptable identifier
990 // namespace, so that we can construct an overload set if we
991 // need to.
John McCallf36e02d2009-10-09 21:13:30 +0000992 Found = true;
Douglas Gregor55368912011-12-14 16:03:29 +0000993 R.addDecl(ND);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000994 }
995 }
996
Douglas Gregor00b4b032010-05-14 04:53:42 +0000997 if (Found && S->isTemplateParamScope()) {
John McCallf36e02d2009-10-09 21:13:30 +0000998 R.resolveKind();
999 return true;
1000 }
1001
Douglas Gregor00b4b032010-05-14 04:53:42 +00001002 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1003 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1004 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1005 // We've just searched the last template parameter scope and
1006 // found nothing, so look into the the contexts between the
1007 // lexical and semantic declaration contexts returned by
1008 // findOuterContext(). This implements the name lookup behavior
1009 // of C++ [temp.local]p8.
1010 Ctx = OutsideOfTemplateParamDC;
1011 OutsideOfTemplateParamDC = 0;
1012 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001013
Douglas Gregor00b4b032010-05-14 04:53:42 +00001014 if (Ctx) {
1015 DeclContext *OuterCtx;
1016 bool SearchAfterTemplateScope;
1017 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1018 if (SearchAfterTemplateScope)
1019 OutsideOfTemplateParamDC = OuterCtx;
1020
1021 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1022 // We do not directly look into transparent contexts, since
1023 // those entities will be found in the nearest enclosing
1024 // non-transparent context.
1025 if (Ctx->isTransparentContext())
1026 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001027
Douglas Gregor00b4b032010-05-14 04:53:42 +00001028 // If we have a context, and it's not a context stashed in the
1029 // template parameter scope for an out-of-line definition, also
1030 // look into that context.
1031 if (!(Found && S && S->isTemplateParamScope())) {
1032 assert(Ctx->isFileContext() &&
1033 "We should have been looking only at file context here already.");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001034
Douglas Gregor00b4b032010-05-14 04:53:42 +00001035 // Look into context considering using-directives.
1036 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1037 Found = true;
1038 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001039
Douglas Gregor00b4b032010-05-14 04:53:42 +00001040 if (Found) {
1041 R.resolveKind();
1042 return true;
1043 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001044
Douglas Gregor00b4b032010-05-14 04:53:42 +00001045 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1046 return false;
1047 }
1048 }
1049
Douglas Gregor1df0ee92010-02-05 07:07:10 +00001050 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +00001051 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001052 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001053
John McCallf36e02d2009-10-09 21:13:30 +00001054 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001055}
1056
Douglas Gregor55368912011-12-14 16:03:29 +00001057/// \brief Retrieve the visible declaration corresponding to D, if any.
1058///
1059/// This routine determines whether the declaration D is visible in the current
1060/// module, with the current imports. If not, it checks whether any
1061/// redeclaration of D is visible, and if so, returns that declaration.
1062///
1063/// \returns D, or a visible previous declaration of D, whichever is more recent
1064/// and visible. If no declaration of D is visible, returns null.
1065static NamedDecl *getVisibleDecl(NamedDecl *D) {
1066 if (LookupResult::isVisible(D))
1067 return D;
1068
Douglas Gregor0782ef22012-01-06 22:05:37 +00001069 for (Decl::redecl_iterator RD = D->redecls_begin(), RDEnd = D->redecls_end();
1070 RD != RDEnd; ++RD) {
1071 if (NamedDecl *ND = dyn_cast<NamedDecl>(*RD)) {
1072 if (LookupResult::isVisible(ND))
1073 return ND;
1074 }
Douglas Gregor55368912011-12-14 16:03:29 +00001075 }
1076
1077 return 0;
1078}
1079
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001080/// @brief Perform unqualified name lookup starting from a given
1081/// scope.
1082///
1083/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1084/// used to find names within the current scope. For example, 'x' in
1085/// @code
1086/// int x;
1087/// int f() {
1088/// return x; // unqualified name look finds 'x' in the global scope
1089/// }
1090/// @endcode
1091///
1092/// Different lookup criteria can find different names. For example, a
1093/// particular scope can have both a struct and a function of the same
1094/// name, and each can be found by certain lookup criteria. For more
1095/// information about lookup criteria, see the documentation for the
1096/// class LookupCriteria.
1097///
1098/// @param S The scope from which unqualified name lookup will
1099/// begin. If the lookup criteria permits, name lookup may also search
1100/// in the parent scopes.
1101///
1102/// @param Name The name of the entity that we are searching for.
1103///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001104/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001105/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001106/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001107///
1108/// @returns The result of name lookup, which includes zero or more
1109/// declarations and possibly additional information used to diagnose
1110/// ambiguities.
John McCalla24dc2e2009-11-17 02:14:36 +00001111bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1112 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +00001113 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001114
John McCalla24dc2e2009-11-17 02:14:36 +00001115 LookupNameKind NameKind = R.getLookupKind();
1116
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001117 if (!getLangOptions().CPlusPlus) {
1118 // Unqualified name lookup in C/Objective-C is purely lexical, so
1119 // search in the declarations attached to the name.
John McCall1d7c5282009-12-18 10:40:03 +00001120 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001121 // Find the nearest non-transparent declaration scope.
1122 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001123 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001124 static_cast<DeclContext *>(S->getEntity())
1125 ->isTransparentContext()))
1126 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001127 }
1128
John McCall1d7c5282009-12-18 10:40:03 +00001129 unsigned IDNS = R.getIdentifierNamespace();
1130
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001131 // Scan up the scope chain looking for a decl that matches this
1132 // identifier that is in the appropriate namespace. This search
1133 // should not take long, as shadowing of names is uncommon, and
1134 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001135 bool LeftStartingScope = false;
1136
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001137 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +00001138 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001139 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001140 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001141 if (NameKind == LookupRedeclarationWithLinkage) {
1142 // Determine whether this (or a previous) declaration is
1143 // out-of-scope.
John McCalld226f652010-08-21 09:40:31 +00001144 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001145 LeftStartingScope = true;
1146
1147 // If we found something outside of our starting scope that
1148 // does not have linkage, skip it.
1149 if (LeftStartingScope && !((*I)->hasLinkage()))
1150 continue;
1151 }
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001152 else if (NameKind == LookupObjCImplicitSelfParam &&
1153 !isa<ImplicitParamDecl>(*I))
1154 continue;
1155
Douglas Gregor10ce9322011-12-02 20:08:44 +00001156 // If this declaration is module-private and it came from an AST
1157 // file, we can't see it.
Douglas Gregor447af242012-01-05 01:11:47 +00001158 NamedDecl *D = R.isHiddenDeclarationVisible()? *I : getVisibleDecl(*I);
Douglas Gregor55368912011-12-14 16:03:29 +00001159 if (!D)
Douglas Gregor10ce9322011-12-02 20:08:44 +00001160 continue;
Douglas Gregor55368912011-12-14 16:03:29 +00001161
1162 R.addDecl(D);
John McCallf36e02d2009-10-09 21:13:30 +00001163
Douglas Gregor7a537402012-01-03 23:26:26 +00001164 // Check whether there are any other declarations with the same name
1165 // and in the same scope.
Douglas Gregorda795b42012-01-04 16:44:10 +00001166 if (I != IEnd) {
Douglas Gregor117c4562012-01-13 23:06:53 +00001167 // Find the scope in which this declaration was declared (if it
1168 // actually exists in a Scope).
1169 while (S && !S->isDeclScope(D))
1170 S = S->getParent();
1171
1172 // If the scope containing the declaration is the translation unit,
1173 // then we'll need to perform our checks based on the matching
1174 // DeclContexts rather than matching scopes.
1175 if (S && isNamespaceOrTranslationUnitScope(S))
1176 S = 0;
1177
1178 // Compute the DeclContext, if we need it.
1179 DeclContext *DC = 0;
1180 if (!S)
1181 DC = (*I)->getDeclContext()->getRedeclContext();
1182
Douglas Gregorda795b42012-01-04 16:44:10 +00001183 IdentifierResolver::iterator LastI = I;
1184 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor117c4562012-01-13 23:06:53 +00001185 if (S) {
1186 // Match based on scope.
1187 if (!S->isDeclScope(*LastI))
1188 break;
1189 } else {
1190 // Match based on DeclContext.
1191 DeclContext *LastDC
1192 = (*LastI)->getDeclContext()->getRedeclContext();
1193 if (!LastDC->Equals(DC))
1194 break;
1195 }
1196
1197 // If the declaration isn't in the right namespace, skip it.
Douglas Gregorda795b42012-01-04 16:44:10 +00001198 if (!(*LastI)->isInIdentifierNamespace(IDNS))
1199 continue;
Douglas Gregor117c4562012-01-13 23:06:53 +00001200
Douglas Gregor447af242012-01-05 01:11:47 +00001201 D = R.isHiddenDeclarationVisible()? *LastI : getVisibleDecl(*LastI);
Douglas Gregorda795b42012-01-04 16:44:10 +00001202 if (D)
1203 R.addDecl(D);
1204 }
Douglas Gregorf9201e02009-02-11 23:02:49 +00001205
Douglas Gregorda795b42012-01-04 16:44:10 +00001206 R.resolveKind();
Douglas Gregorf9201e02009-02-11 23:02:49 +00001207 }
John McCallf36e02d2009-10-09 21:13:30 +00001208 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +00001209 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001210 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001211 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +00001212 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +00001213 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001214 }
1215
1216 // If we didn't find a use of this identifier, and if the identifier
1217 // corresponds to a compiler builtin, create the decl object for the builtin
1218 // now, injecting it into translation unit scope, and return it.
Axel Naumann42151d52011-04-13 13:19:46 +00001219 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1220 return true;
Douglas Gregor3e41d602009-02-13 23:20:09 +00001221
Axel Naumannf8291a12011-02-24 16:47:47 +00001222 // If we didn't find a use of this identifier, the ExternalSource
1223 // may be able to handle the situation.
1224 // Note: some lookup failures are expected!
1225 // See e.g. R.isForRedeclaration().
1226 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001227}
1228
John McCall6e247262009-10-10 05:48:19 +00001229/// @brief Perform qualified name lookup in the namespaces nominated by
1230/// using directives by the given context.
1231///
1232/// C++98 [namespace.qual]p2:
1233/// Given X::m (where X is a user-declared namespace), or given ::m
1234/// (where X is the global namespace), let S be the set of all
1235/// declarations of m in X and in the transitive closure of all
1236/// namespaces nominated by using-directives in X and its used
1237/// namespaces, except that using-directives are ignored in any
1238/// namespace, including X, directly containing one or more
1239/// declarations of m. No namespace is searched more than once in
1240/// the lookup of a name. If S is the empty set, the program is
1241/// ill-formed. Otherwise, if S has exactly one member, or if the
1242/// context of the reference is a using-declaration
1243/// (namespace.udecl), S is the required set of declarations of
1244/// m. Otherwise if the use of m is not one that allows a unique
1245/// declaration to be chosen from S, the program is ill-formed.
1246/// C++98 [namespace.qual]p5:
1247/// During the lookup of a qualified namespace member name, if the
1248/// lookup finds more than one declaration of the member, and if one
1249/// declaration introduces a class name or enumeration name and the
1250/// other declarations either introduce the same object, the same
1251/// enumerator or a set of functions, the non-type name hides the
1252/// class or enumeration name if and only if the declarations are
1253/// from the same namespace; otherwise (the declarations are from
1254/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +00001255static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +00001256 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +00001257 assert(StartDC->isFileContext() && "start context is not a file context");
1258
1259 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1260 DeclContext::udir_iterator E = StartDC->using_directives_end();
1261
1262 if (I == E) return false;
1263
1264 // We have at least added all these contexts to the queue.
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001265 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6e247262009-10-10 05:48:19 +00001266 Visited.insert(StartDC);
1267
1268 // We have not yet looked into these namespaces, much less added
1269 // their "using-children" to the queue.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001270 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6e247262009-10-10 05:48:19 +00001271
1272 // We have already looked into the initial namespace; seed the queue
1273 // with its using-children.
1274 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001275 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001276 if (Visited.insert(ND))
John McCall6e247262009-10-10 05:48:19 +00001277 Queue.push_back(ND);
1278 }
1279
1280 // The easiest way to implement the restriction in [namespace.qual]p5
1281 // is to check whether any of the individual results found a tag
1282 // and, if so, to declare an ambiguity if the final result is not
1283 // a tag.
1284 bool FoundTag = false;
1285 bool FoundNonTag = false;
1286
John McCall7d384dd2009-11-18 07:57:50 +00001287 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001288
1289 bool Found = false;
1290 while (!Queue.empty()) {
1291 NamespaceDecl *ND = Queue.back();
1292 Queue.pop_back();
1293
1294 // We go through some convolutions here to avoid copying results
1295 // between LookupResults.
1296 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001297 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001298 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001299
1300 if (FoundDirect) {
1301 // First do any local hiding.
1302 DirectR.resolveKind();
1303
1304 // If the local result is a tag, remember that.
1305 if (DirectR.isSingleTagDecl())
1306 FoundTag = true;
1307 else
1308 FoundNonTag = true;
1309
1310 // Append the local results to the total results if necessary.
1311 if (UseLocal) {
1312 R.addAllDecls(LocalR);
1313 LocalR.clear();
1314 }
1315 }
1316
1317 // If we find names in this namespace, ignore its using directives.
1318 if (FoundDirect) {
1319 Found = true;
1320 continue;
1321 }
1322
1323 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1324 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001325 if (Visited.insert(Nom))
John McCall6e247262009-10-10 05:48:19 +00001326 Queue.push_back(Nom);
1327 }
1328 }
1329
1330 if (Found) {
1331 if (FoundTag && FoundNonTag)
1332 R.setAmbiguousQualifiedTagHiding();
1333 else
1334 R.resolveKind();
1335 }
1336
1337 return Found;
1338}
1339
Douglas Gregor8071e422010-08-15 06:18:01 +00001340/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001341static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor8071e422010-08-15 06:18:01 +00001342 CXXBasePath &Path,
1343 void *Name) {
1344 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001345
Douglas Gregor8071e422010-08-15 06:18:01 +00001346 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1347 Path.Decls = BaseRecord->lookup(N);
1348 return Path.Decls.first != Path.Decls.second;
1349}
1350
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001351/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001352/// static members, nested types, and enumerators.
1353template<typename InputIterator>
1354static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1355 Decl *D = (*First)->getUnderlyingDecl();
1356 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1357 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001358
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001359 if (isa<CXXMethodDecl>(D)) {
1360 // Determine whether all of the methods are static.
1361 bool AllMethodsAreStatic = true;
1362 for(; First != Last; ++First) {
1363 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001364
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001365 if (!isa<CXXMethodDecl>(D)) {
1366 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1367 break;
1368 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001369
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001370 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1371 AllMethodsAreStatic = false;
1372 break;
1373 }
1374 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001375
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001376 if (AllMethodsAreStatic)
1377 return true;
1378 }
1379
1380 return false;
1381}
1382
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001383/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001384///
1385/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1386/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001387/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001388///
1389/// Different lookup criteria can find different names. For example, a
1390/// particular scope can have both a struct and a function of the same
1391/// name, and each can be found by certain lookup criteria. For more
1392/// information about lookup criteria, see the documentation for the
1393/// class LookupCriteria.
1394///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001395/// \param R captures both the lookup criteria and any lookup results found.
1396///
1397/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001398/// search. If the lookup criteria permits, name lookup may also search
1399/// in the parent contexts or (for C++ classes) base classes.
1400///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001401/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001402/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001403///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001404/// \returns true if lookup succeeded, false if it failed.
1405bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1406 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001407 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001408
John McCalla24dc2e2009-11-17 02:14:36 +00001409 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001410 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001411
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001412 // Make sure that the declaration context is complete.
1413 assert((!isa<TagDecl>(LookupCtx) ||
1414 LookupCtx->isDependentContext() ||
John McCall5e1cdac2011-10-07 06:10:15 +00001415 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001416 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1417 ->isBeingDefined()) &&
1418 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001419
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001420 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001421 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001422 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001423 if (isa<CXXRecordDecl>(LookupCtx))
1424 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001425 return true;
1426 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001427
John McCall6e247262009-10-10 05:48:19 +00001428 // Don't descend into implied contexts for redeclarations.
1429 // C++98 [namespace.qual]p6:
1430 // In a declaration for a namespace member in which the
1431 // declarator-id is a qualified-id, given that the qualified-id
1432 // for the namespace member has the form
1433 // nested-name-specifier unqualified-id
1434 // the unqualified-id shall name a member of the namespace
1435 // designated by the nested-name-specifier.
1436 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001437 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001438 return false;
1439
John McCalla24dc2e2009-11-17 02:14:36 +00001440 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001441 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001442 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001443
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001444 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001445 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001446 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor025291b2010-07-01 00:21:21 +00001447 if (!LookupRec || !LookupRec->getDefinition())
John McCallf36e02d2009-10-09 21:13:30 +00001448 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001449
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001450 // If we're performing qualified name lookup into a dependent class,
1451 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001452 // dependent base classes, then we either have to delay lookup until
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001453 // template instantiation time (at which point all bases will be available)
1454 // or we have to fail.
1455 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1456 LookupRec->hasAnyDependentBases()) {
1457 R.setNotFoundInCurrentInstantiation();
1458 return false;
1459 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001460
Douglas Gregor7176fff2009-01-15 00:26:24 +00001461 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001462 CXXBasePaths Paths;
1463 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001464
1465 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001466 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001467 switch (R.getLookupKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001468 case LookupObjCImplicitSelfParam:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001469 case LookupOrdinaryName:
1470 case LookupMemberName:
1471 case LookupRedeclarationWithLinkage:
1472 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1473 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001474
Douglas Gregora8f32e02009-10-06 17:59:45 +00001475 case LookupTagName:
1476 BaseCallback = &CXXRecordDecl::FindTagMember;
1477 break;
John McCall9f54ad42009-12-10 09:41:52 +00001478
Douglas Gregor8071e422010-08-15 06:18:01 +00001479 case LookupAnyName:
1480 BaseCallback = &LookupAnyMember;
1481 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001482
John McCall9f54ad42009-12-10 09:41:52 +00001483 case LookupUsingDeclName:
1484 // This lookup is for redeclarations only.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001485
Douglas Gregora8f32e02009-10-06 17:59:45 +00001486 case LookupOperatorName:
1487 case LookupNamespaceName:
1488 case LookupObjCProtocolName:
Chris Lattner337e5502011-02-18 01:27:55 +00001489 case LookupLabel:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001490 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001491 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001492
Douglas Gregora8f32e02009-10-06 17:59:45 +00001493 case LookupNestedNameSpecifierName:
1494 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1495 break;
1496 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001497
John McCalla24dc2e2009-11-17 02:14:36 +00001498 if (!LookupRec->lookupInBases(BaseCallback,
1499 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001500 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001501
John McCall92f88312010-01-23 00:46:32 +00001502 R.setNamingClass(LookupRec);
1503
Douglas Gregor7176fff2009-01-15 00:26:24 +00001504 // C++ [class.member.lookup]p2:
1505 // [...] If the resulting set of declarations are not all from
1506 // sub-objects of the same type, or the set has a nonstatic member
1507 // and includes members from distinct sub-objects, there is an
1508 // ambiguity and the program is ill-formed. Otherwise that set is
1509 // the result of the lookup.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001510 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001511 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001512 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001513
Douglas Gregora8f32e02009-10-06 17:59:45 +00001514 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001515 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001516 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001517
John McCall46460a62010-01-20 21:53:11 +00001518 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1519 // across all paths.
1520 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001521
Douglas Gregor7176fff2009-01-15 00:26:24 +00001522 // Determine whether we're looking at a distinct sub-object or not.
1523 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001524 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001525 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1526 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001527 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001528 }
1529
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001530 if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001531 != Context.getCanonicalType(PathElement.Base->getType())) {
1532 // We found members of the given name in two subobjects of
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001533 // different types. If the declaration sets aren't the same, this
1534 // this lookup is ambiguous.
1535 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1536 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1537 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1538 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001539
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001540 while (FirstD != FirstPath->Decls.second &&
1541 CurrentD != Path->Decls.second) {
1542 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1543 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1544 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001545
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001546 ++FirstD;
1547 ++CurrentD;
1548 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001549
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001550 if (FirstD == FirstPath->Decls.second &&
1551 CurrentD == Path->Decls.second)
1552 continue;
1553 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001554
John McCallf36e02d2009-10-09 21:13:30 +00001555 R.setAmbiguousBaseSubobjectTypes(Paths);
1556 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001557 }
1558
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001559 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001560 // We have a different subobject of the same type.
1561
1562 // C++ [class.member.lookup]p5:
1563 // A static member, a nested type or an enumerator defined in
1564 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001565 // has more than one base class subobject of type T.
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001566 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
Douglas Gregor7176fff2009-01-15 00:26:24 +00001567 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001568
Douglas Gregor7176fff2009-01-15 00:26:24 +00001569 // We have found a nonstatic member name in multiple, distinct
1570 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001571 R.setAmbiguousBaseSubobjects(Paths);
1572 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001573 }
1574 }
1575
1576 // Lookup in a base class succeeded; return these results.
1577
John McCallf36e02d2009-10-09 21:13:30 +00001578 DeclContext::lookup_iterator I, E;
John McCall92f88312010-01-23 00:46:32 +00001579 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1580 NamedDecl *D = *I;
1581 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1582 D->getAccess());
1583 R.addDecl(D, AS);
1584 }
John McCallf36e02d2009-10-09 21:13:30 +00001585 R.resolveKind();
1586 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001587}
1588
1589/// @brief Performs name lookup for a name that was parsed in the
1590/// source code, and may contain a C++ scope specifier.
1591///
1592/// This routine is a convenience routine meant to be called from
1593/// contexts that receive a name and an optional C++ scope specifier
1594/// (e.g., "N::M::x"). It will then perform either qualified or
1595/// unqualified name lookup (with LookupQualifiedName or LookupName,
1596/// respectively) on the given name and return those results.
1597///
1598/// @param S The scope from which unqualified name lookup will
1599/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001600///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001601/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001602///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001603/// @param EnteringContext Indicates whether we are going to enter the
1604/// context of the scope-specifier SS (if present).
1605///
John McCallf36e02d2009-10-09 21:13:30 +00001606/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001607bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001608 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001609 if (SS && SS->isInvalid()) {
1610 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001611 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001612 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001613 }
Mike Stump1eb44332009-09-09 15:08:12 +00001614
Douglas Gregor495c35d2009-08-25 22:51:20 +00001615 if (SS && SS->isSet()) {
1616 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001617 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001618 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001619 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001620 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001621
John McCalla24dc2e2009-11-17 02:14:36 +00001622 R.setContextRange(SS->getRange());
John McCalla24dc2e2009-11-17 02:14:36 +00001623 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001624 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001625
Douglas Gregor495c35d2009-08-25 22:51:20 +00001626 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001627 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001628 // Name lookup can't find anything in this case.
Douglas Gregor3eafbb82011-10-24 22:24:50 +00001629 R.setNotFoundInCurrentInstantiation();
1630 R.setContextRange(SS->getRange());
John McCallf36e02d2009-10-09 21:13:30 +00001631 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001632 }
1633
Mike Stump1eb44332009-09-09 15:08:12 +00001634 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001635 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001636}
1637
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001638
Douglas Gregor7176fff2009-01-15 00:26:24 +00001639/// @brief Produce a diagnostic describing the ambiguity that resulted
1640/// from name lookup.
1641///
1642/// @param Result The ambiguous name lookup result.
Mike Stump1eb44332009-09-09 15:08:12 +00001643///
Douglas Gregor7176fff2009-01-15 00:26:24 +00001644/// @param Name The name of the entity that name lookup was
1645/// searching for.
1646///
1647/// @param NameLoc The location of the name within the source code.
1648///
1649/// @param LookupRange A source range that provides more
1650/// source-location information concerning the lookup itself. For
1651/// example, this range might highlight a nested-name-specifier that
1652/// precedes the name.
1653///
1654/// @returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001655bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001656 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1657
John McCalla24dc2e2009-11-17 02:14:36 +00001658 DeclarationName Name = Result.getLookupName();
1659 SourceLocation NameLoc = Result.getNameLoc();
1660 SourceRange LookupRange = Result.getContextRange();
1661
John McCall6e247262009-10-10 05:48:19 +00001662 switch (Result.getAmbiguityKind()) {
1663 case LookupResult::AmbiguousBaseSubobjects: {
1664 CXXBasePaths *Paths = Result.getBasePaths();
1665 QualType SubobjectType = Paths->front().back().Base->getType();
1666 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1667 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1668 << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001669
John McCall6e247262009-10-10 05:48:19 +00001670 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1671 while (isa<CXXMethodDecl>(*Found) &&
1672 cast<CXXMethodDecl>(*Found)->isStatic())
1673 ++Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001674
John McCall6e247262009-10-10 05:48:19 +00001675 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001676
John McCall6e247262009-10-10 05:48:19 +00001677 return true;
1678 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001679
John McCall6e247262009-10-10 05:48:19 +00001680 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001681 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1682 << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001683
John McCall6e247262009-10-10 05:48:19 +00001684 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001685 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001686 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1687 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001688 Path != PathEnd; ++Path) {
1689 Decl *D = *Path->Decls.first;
1690 if (DeclsPrinted.insert(D).second)
1691 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1692 }
1693
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001694 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001695 }
1696
John McCall6e247262009-10-10 05:48:19 +00001697 case LookupResult::AmbiguousTagHiding: {
1698 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001699
John McCall6e247262009-10-10 05:48:19 +00001700 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1701
1702 LookupResult::iterator DI, DE = Result.end();
1703 for (DI = Result.begin(); DI != DE; ++DI)
1704 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1705 TagDecls.insert(TD);
1706 Diag(TD->getLocation(), diag::note_hidden_tag);
1707 }
1708
1709 for (DI = Result.begin(); DI != DE; ++DI)
1710 if (!isa<TagDecl>(*DI))
1711 Diag((*DI)->getLocation(), diag::note_hiding_object);
1712
1713 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001714 LookupResult::Filter F = Result.makeFilter();
1715 while (F.hasNext()) {
1716 if (TagDecls.count(F.next()))
1717 F.erase();
1718 }
1719 F.done();
John McCall6e247262009-10-10 05:48:19 +00001720
1721 return true;
1722 }
1723
1724 case LookupResult::AmbiguousReference: {
1725 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001726
John McCall6e247262009-10-10 05:48:19 +00001727 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1728 for (; DI != DE; ++DI)
1729 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001730
John McCall6e247262009-10-10 05:48:19 +00001731 return true;
1732 }
1733 }
1734
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001735 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001736}
Douglas Gregorfa047642009-02-04 00:32:51 +00001737
John McCallc7e04da2010-05-28 18:45:08 +00001738namespace {
1739 struct AssociatedLookup {
1740 AssociatedLookup(Sema &S,
1741 Sema::AssociatedNamespaceSet &Namespaces,
1742 Sema::AssociatedClassSet &Classes)
1743 : S(S), Namespaces(Namespaces), Classes(Classes) {
1744 }
1745
1746 Sema &S;
1747 Sema::AssociatedNamespaceSet &Namespaces;
1748 Sema::AssociatedClassSet &Classes;
1749 };
1750}
1751
Mike Stump1eb44332009-09-09 15:08:12 +00001752static void
John McCallc7e04da2010-05-28 18:45:08 +00001753addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCall6ff07852009-08-07 22:18:02 +00001754
Douglas Gregor54022952010-04-30 07:08:38 +00001755static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1756 DeclContext *Ctx) {
1757 // Add the associated namespace for this class.
1758
1759 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1760 // be a locally scoped record.
1761
Sebastian Redl410c4f22010-08-31 20:53:31 +00001762 // We skip out of inline namespaces. The innermost non-inline namespace
1763 // contains all names of all its nested inline namespaces anyway, so we can
1764 // replace the entire inline namespace tree with its root.
1765 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1766 Ctx->isInlineNamespace())
Douglas Gregor54022952010-04-30 07:08:38 +00001767 Ctx = Ctx->getParent();
1768
John McCall6ff07852009-08-07 22:18:02 +00001769 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001770 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001771}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001772
Mike Stump1eb44332009-09-09 15:08:12 +00001773// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001774// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001775static void
John McCallc7e04da2010-05-28 18:45:08 +00001776addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1777 const TemplateArgument &Arg) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001778 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001779 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001780 switch (Arg.getKind()) {
1781 case TemplateArgument::Null:
1782 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001783
Douglas Gregor69be8d62009-07-08 07:51:57 +00001784 case TemplateArgument::Type:
1785 // [...] the namespaces and classes associated with the types of the
1786 // template arguments provided for template type parameters (excluding
1787 // template template parameters)
John McCallc7e04da2010-05-28 18:45:08 +00001788 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor69be8d62009-07-08 07:51:57 +00001789 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001790
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001791 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001792 case TemplateArgument::TemplateExpansion: {
Mike Stump1eb44332009-09-09 15:08:12 +00001793 // [...] the namespaces in which any template template arguments are
1794 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001795 // template template arguments are defined.
Douglas Gregora7fc9012011-01-05 18:58:31 +00001796 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump1eb44332009-09-09 15:08:12 +00001797 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001798 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001799 DeclContext *Ctx = ClassTemplate->getDeclContext();
1800 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001801 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001802 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001803 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001804 }
1805 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001806 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001807
Douglas Gregor788cd062009-11-11 01:00:40 +00001808 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001809 case TemplateArgument::Integral:
1810 case TemplateArgument::Expression:
Mike Stump1eb44332009-09-09 15:08:12 +00001811 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001812 // associated namespaces. ]
1813 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001814
Douglas Gregor69be8d62009-07-08 07:51:57 +00001815 case TemplateArgument::Pack:
1816 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1817 PEnd = Arg.pack_end();
1818 P != PEnd; ++P)
John McCallc7e04da2010-05-28 18:45:08 +00001819 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001820 break;
1821 }
1822}
1823
Douglas Gregorfa047642009-02-04 00:32:51 +00001824// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001825// argument-dependent lookup with an argument of class type
1826// (C++ [basic.lookup.koenig]p2).
1827static void
John McCallc7e04da2010-05-28 18:45:08 +00001828addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1829 CXXRecordDecl *Class) {
1830
1831 // Just silently ignore anything whose name is __va_list_tag.
1832 if (Class->getDeclName() == Result.S.VAListTagName)
1833 return;
1834
Douglas Gregorfa047642009-02-04 00:32:51 +00001835 // C++ [basic.lookup.koenig]p2:
1836 // [...]
1837 // -- If T is a class type (including unions), its associated
1838 // classes are: the class itself; the class of which it is a
1839 // member, if any; and its direct and indirect base
1840 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001841 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001842
1843 // Add the class of which it is a member, if any.
1844 DeclContext *Ctx = Class->getDeclContext();
1845 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001846 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001847 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001848 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001849
Douglas Gregorfa047642009-02-04 00:32:51 +00001850 // Add the class itself. If we've already seen this class, we don't
1851 // need to visit base classes.
John McCallc7e04da2010-05-28 18:45:08 +00001852 if (!Result.Classes.insert(Class))
Douglas Gregorfa047642009-02-04 00:32:51 +00001853 return;
1854
Mike Stump1eb44332009-09-09 15:08:12 +00001855 // -- If T is a template-id, its associated namespaces and classes are
1856 // the namespace in which the template is defined; for member
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001857 // templates, the member template's class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001858 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001859 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001860 // namespaces in which any template template arguments are defined; and
1861 // the classes in which any member templates used as template template
1862 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001863 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001864 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001865 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1866 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1867 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001868 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001869 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001870 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001871
Douglas Gregor69be8d62009-07-08 07:51:57 +00001872 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1873 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallc7e04da2010-05-28 18:45:08 +00001874 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001875 }
Mike Stump1eb44332009-09-09 15:08:12 +00001876
John McCall86ff3082010-02-04 22:26:26 +00001877 // Only recurse into base classes for complete types.
1878 if (!Class->hasDefinition()) {
1879 // FIXME: we might need to instantiate templates here
1880 return;
1881 }
1882
Douglas Gregorfa047642009-02-04 00:32:51 +00001883 // Add direct and indirect base classes along with their associated
1884 // namespaces.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001885 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregorfa047642009-02-04 00:32:51 +00001886 Bases.push_back(Class);
1887 while (!Bases.empty()) {
1888 // Pop this class off the stack.
1889 Class = Bases.back();
1890 Bases.pop_back();
1891
1892 // Visit the base classes.
1893 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1894 BaseEnd = Class->bases_end();
1895 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001896 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001897 // In dependent contexts, we do ADL twice, and the first time around,
1898 // the base type might be a dependent TemplateSpecializationType, or a
1899 // TemplateTypeParmType. If that happens, simply ignore it.
1900 // FIXME: If we want to support export, we probably need to add the
1901 // namespace of the template in a TemplateSpecializationType, or even
1902 // the classes and namespaces of known non-dependent arguments.
1903 if (!BaseType)
1904 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001905 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001906 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001907 // Find the associated namespace for this base class.
1908 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallc7e04da2010-05-28 18:45:08 +00001909 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001910
1911 // Make sure we visit the bases of this base class.
1912 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1913 Bases.push_back(BaseDecl);
1914 }
1915 }
1916 }
1917}
1918
1919// \brief Add the associated classes and namespaces for
1920// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001921// (C++ [basic.lookup.koenig]p2).
1922static void
John McCallc7e04da2010-05-28 18:45:08 +00001923addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001924 // C++ [basic.lookup.koenig]p2:
1925 //
1926 // For each argument type T in the function call, there is a set
1927 // of zero or more associated namespaces and a set of zero or more
1928 // associated classes to be considered. The sets of namespaces and
1929 // classes is determined entirely by the types of the function
1930 // arguments (and the namespace of any template template
1931 // argument). Typedef names and using-declarations used to specify
1932 // the types do not contribute to this set. The sets of namespaces
1933 // and classes are determined in the following way:
Douglas Gregorfa047642009-02-04 00:32:51 +00001934
Chris Lattner5f9e2722011-07-23 10:55:15 +00001935 SmallVector<const Type *, 16> Queue;
John McCallfa4edcf2010-05-28 06:08:54 +00001936 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1937
Douglas Gregorfa047642009-02-04 00:32:51 +00001938 while (true) {
John McCallfa4edcf2010-05-28 06:08:54 +00001939 switch (T->getTypeClass()) {
1940
1941#define TYPE(Class, Base)
1942#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1943#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1944#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1945#define ABSTRACT_TYPE(Class, Base)
1946#include "clang/AST/TypeNodes.def"
1947 // T is canonical. We can also ignore dependent types because
1948 // we don't need to do ADL at the definition point, but if we
1949 // wanted to implement template export (or if we find some other
1950 // use for associated classes and namespaces...) this would be
1951 // wrong.
Douglas Gregorfa047642009-02-04 00:32:51 +00001952 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00001953
John McCallfa4edcf2010-05-28 06:08:54 +00001954 // -- If T is a pointer to U or an array of U, its associated
1955 // namespaces and classes are those associated with U.
1956 case Type::Pointer:
1957 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1958 continue;
1959 case Type::ConstantArray:
1960 case Type::IncompleteArray:
1961 case Type::VariableArray:
1962 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1963 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001964
John McCallfa4edcf2010-05-28 06:08:54 +00001965 // -- If T is a fundamental type, its associated sets of
1966 // namespaces and classes are both empty.
1967 case Type::Builtin:
1968 break;
1969
1970 // -- If T is a class type (including unions), its associated
1971 // classes are: the class itself; the class of which it is a
1972 // member, if any; and its direct and indirect base
1973 // classes. Its associated namespaces are the namespaces in
1974 // which its associated classes are defined.
1975 case Type::Record: {
1976 CXXRecordDecl *Class
1977 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001978 addAssociatedClassesAndNamespaces(Result, Class);
John McCallfa4edcf2010-05-28 06:08:54 +00001979 break;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001980 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00001981
John McCallfa4edcf2010-05-28 06:08:54 +00001982 // -- If T is an enumeration type, its associated namespace is
1983 // the namespace in which it is defined. If it is class
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001984 // member, its associated class is the member's class; else
John McCallfa4edcf2010-05-28 06:08:54 +00001985 // it has no associated class.
1986 case Type::Enum: {
1987 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001988
John McCallfa4edcf2010-05-28 06:08:54 +00001989 DeclContext *Ctx = Enum->getDeclContext();
1990 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001991 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001992
John McCallfa4edcf2010-05-28 06:08:54 +00001993 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001994 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001995
John McCallfa4edcf2010-05-28 06:08:54 +00001996 break;
1997 }
1998
1999 // -- If T is a function type, its associated namespaces and
2000 // classes are those associated with the function parameter
2001 // types and those associated with the return type.
2002 case Type::FunctionProto: {
2003 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2004 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
2005 ArgEnd = Proto->arg_type_end();
2006 Arg != ArgEnd; ++Arg)
2007 Queue.push_back(Arg->getTypePtr());
2008 // fallthrough
2009 }
2010 case Type::FunctionNoProto: {
2011 const FunctionType *FnType = cast<FunctionType>(T);
2012 T = FnType->getResultType().getTypePtr();
2013 continue;
2014 }
2015
2016 // -- If T is a pointer to a member function of a class X, its
2017 // associated namespaces and classes are those associated
2018 // with the function parameter types and return type,
2019 // together with those associated with X.
2020 //
2021 // -- If T is a pointer to a data member of class X, its
2022 // associated namespaces and classes are those associated
2023 // with the member type together with those associated with
2024 // X.
2025 case Type::MemberPointer: {
2026 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2027
2028 // Queue up the class type into which this points.
2029 Queue.push_back(MemberPtr->getClass());
2030
2031 // And directly continue with the pointee type.
2032 T = MemberPtr->getPointeeType().getTypePtr();
2033 continue;
2034 }
2035
2036 // As an extension, treat this like a normal pointer.
2037 case Type::BlockPointer:
2038 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2039 continue;
2040
2041 // References aren't covered by the standard, but that's such an
2042 // obvious defect that we cover them anyway.
2043 case Type::LValueReference:
2044 case Type::RValueReference:
2045 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2046 continue;
2047
2048 // These are fundamental types.
2049 case Type::Vector:
2050 case Type::ExtVector:
2051 case Type::Complex:
2052 break;
2053
Douglas Gregorf25760e2011-04-12 01:02:45 +00002054 // If T is an Objective-C object or interface type, or a pointer to an
2055 // object or interface type, the associated namespace is the global
2056 // namespace.
John McCallfa4edcf2010-05-28 06:08:54 +00002057 case Type::ObjCObject:
2058 case Type::ObjCInterface:
2059 case Type::ObjCObjectPointer:
Douglas Gregorf25760e2011-04-12 01:02:45 +00002060 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCallfa4edcf2010-05-28 06:08:54 +00002061 break;
Eli Friedmanb001de72011-10-06 23:00:33 +00002062
2063 // Atomic types are just wrappers; use the associations of the
2064 // contained type.
2065 case Type::Atomic:
2066 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2067 continue;
John McCallfa4edcf2010-05-28 06:08:54 +00002068 }
2069
2070 if (Queue.empty()) break;
2071 T = Queue.back();
2072 Queue.pop_back();
Douglas Gregorfa047642009-02-04 00:32:51 +00002073 }
Douglas Gregorfa047642009-02-04 00:32:51 +00002074}
2075
2076/// \brief Find the associated classes and namespaces for
2077/// argument-dependent lookup for a call with the given set of
2078/// arguments.
2079///
2080/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00002081/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00002082/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00002083void
Douglas Gregorfa047642009-02-04 00:32:51 +00002084Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
2085 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00002086 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002087 AssociatedNamespaces.clear();
2088 AssociatedClasses.clear();
2089
John McCallc7e04da2010-05-28 18:45:08 +00002090 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
2091
Douglas Gregorfa047642009-02-04 00:32:51 +00002092 // C++ [basic.lookup.koenig]p2:
2093 // For each argument type T in the function call, there is a set
2094 // of zero or more associated namespaces and a set of zero or more
2095 // associated classes to be considered. The sets of namespaces and
2096 // classes is determined entirely by the types of the function
2097 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00002098 // argument).
Douglas Gregorfa047642009-02-04 00:32:51 +00002099 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
2100 Expr *Arg = Args[ArgIdx];
2101
2102 if (Arg->getType() != Context.OverloadTy) {
John McCallc7e04da2010-05-28 18:45:08 +00002103 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002104 continue;
2105 }
2106
2107 // [...] In addition, if the argument is the name or address of a
2108 // set of overloaded functions and/or function templates, its
2109 // associated classes and namespaces are the union of those
2110 // associated with each of the members of the set: the namespace
2111 // in which the function or function template is defined and the
2112 // classes and namespaces associated with its (non-dependent)
2113 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00002114 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00002115 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCall2de56d12010-08-25 11:45:40 +00002116 if (unaryOp->getOpcode() == UO_AddrOf)
John McCallba135432009-11-21 08:51:07 +00002117 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002118
John McCallc7e04da2010-05-28 18:45:08 +00002119 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2120 if (!ULE) continue;
John McCallba135432009-11-21 08:51:07 +00002121
John McCallc7e04da2010-05-28 18:45:08 +00002122 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2123 I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00002124 // Look through any using declarations to find the underlying function.
2125 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002126
Chandler Carruthbd647292009-12-29 06:17:27 +00002127 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2128 if (!FDecl)
2129 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002130
2131 // Add the classes and namespaces associated with the parameter
2132 // types and return type of this function.
John McCallc7e04da2010-05-28 18:45:08 +00002133 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002134 }
2135 }
2136}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002137
2138/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2139/// an acceptable non-member overloaded operator for a call whose
2140/// arguments have types T1 (and, if non-empty, T2). This routine
2141/// implements the check in C++ [over.match.oper]p3b2 concerning
2142/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00002143static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002144IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2145 QualType T1, QualType T2,
2146 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00002147 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2148 return true;
2149
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002150 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2151 return true;
2152
John McCall183700f2009-09-21 23:43:11 +00002153 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002154 if (Proto->getNumArgs() < 1)
2155 return false;
2156
2157 if (T1->isEnumeralType()) {
2158 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002159 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002160 return true;
2161 }
2162
2163 if (Proto->getNumArgs() < 2)
2164 return false;
2165
2166 if (!T2.isNull() && T2->isEnumeralType()) {
2167 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002168 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002169 return true;
2170 }
2171
2172 return false;
2173}
2174
John McCall7d384dd2009-11-18 07:57:50 +00002175NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002176 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00002177 LookupNameKind NameKind,
2178 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002179 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00002180 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00002181 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00002182}
2183
Douglas Gregor6e378de2009-04-23 23:18:26 +00002184/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002185ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002186 SourceLocation IdLoc,
2187 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002188 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002189 LookupObjCProtocolName, Redecl);
Douglas Gregor6e378de2009-04-23 23:18:26 +00002190 return cast_or_null<ObjCProtocolDecl>(D);
2191}
2192
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002193void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00002194 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00002195 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002196 // C++ [over.match.oper]p3:
2197 // -- The set of non-member candidates is the result of the
2198 // unqualified lookup of operator@ in the context of the
2199 // expression according to the usual rules for name lookup in
2200 // unqualified function calls (3.4.2) except that all member
2201 // functions are ignored. However, if no operand has a class
2202 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00002203 // that have a first parameter of type T1 or "reference to
2204 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002205 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00002206 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002207 // when T2 is an enumeration type, are candidate functions.
2208 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00002209 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2210 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002211
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002212 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2213
John McCallf36e02d2009-10-09 21:13:30 +00002214 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002215 return;
2216
2217 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2218 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002219 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2220 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002221 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002222 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00002223 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002224 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00002225 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00002226 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00002227 // later?
2228 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002229 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00002230 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002231 }
2232}
2233
Sean Huntc39b6bc2011-06-24 02:11:39 +00002234Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Sean Hunt308742c2011-06-04 04:32:43 +00002235 CXXSpecialMember SM,
2236 bool ConstArg,
2237 bool VolatileArg,
2238 bool RValueThis,
2239 bool ConstThis,
2240 bool VolatileThis) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002241 RD = RD->getDefinition();
2242 assert((RD && !RD->isBeingDefined()) &&
Sean Hunt308742c2011-06-04 04:32:43 +00002243 "doing special member lookup into record that isn't fully complete");
2244 if (RValueThis || ConstThis || VolatileThis)
2245 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2246 "constructors and destructors always have unqualified lvalue this");
2247 if (ConstArg || VolatileArg)
2248 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2249 "parameter-less special members can't have qualified arguments");
2250
2251 llvm::FoldingSetNodeID ID;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002252 ID.AddPointer(RD);
Sean Hunt308742c2011-06-04 04:32:43 +00002253 ID.AddInteger(SM);
2254 ID.AddInteger(ConstArg);
2255 ID.AddInteger(VolatileArg);
2256 ID.AddInteger(RValueThis);
2257 ID.AddInteger(ConstThis);
2258 ID.AddInteger(VolatileThis);
2259
2260 void *InsertPoint;
2261 SpecialMemberOverloadResult *Result =
2262 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2263
2264 // This was already cached
2265 if (Result)
2266 return Result;
2267
Sean Hunt30543582011-06-07 00:11:58 +00002268 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2269 Result = new (Result) SpecialMemberOverloadResult(ID);
Sean Hunt308742c2011-06-04 04:32:43 +00002270 SpecialMemberCache.InsertNode(Result, InsertPoint);
2271
2272 if (SM == CXXDestructor) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002273 if (!RD->hasDeclaredDestructor())
2274 DeclareImplicitDestructor(RD);
2275 CXXDestructorDecl *DD = RD->getDestructor();
Sean Hunt308742c2011-06-04 04:32:43 +00002276 assert(DD && "record without a destructor");
2277 Result->setMethod(DD);
Richard Smith7d5088a2012-02-18 02:02:13 +00002278 Result->setSuccess(!DD->isDeleted());
Sean Hunt308742c2011-06-04 04:32:43 +00002279 Result->setConstParamMatch(false);
2280 return Result;
2281 }
2282
Sean Huntb320e0c2011-06-10 03:50:41 +00002283 // Prepare for overload resolution. Here we construct a synthetic argument
2284 // if necessary and make sure that implicit functions are declared.
Sean Huntc39b6bc2011-06-24 02:11:39 +00002285 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Sean Huntb320e0c2011-06-10 03:50:41 +00002286 DeclarationName Name;
2287 Expr *Arg = 0;
2288 unsigned NumArgs;
2289
2290 if (SM == CXXDefaultConstructor) {
2291 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2292 NumArgs = 0;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002293 if (RD->needsImplicitDefaultConstructor())
2294 DeclareImplicitDefaultConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002295 } else {
2296 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2297 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002298 if (!RD->hasDeclaredCopyConstructor())
2299 DeclareImplicitCopyConstructor(RD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002300 if (getLangOptions().CPlusPlus0x && RD->needsImplicitMoveConstructor())
2301 DeclareImplicitMoveConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002302 } else {
2303 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002304 if (!RD->hasDeclaredCopyAssignment())
2305 DeclareImplicitCopyAssignment(RD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002306 if (getLangOptions().CPlusPlus0x && RD->needsImplicitMoveAssignment())
2307 DeclareImplicitMoveAssignment(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002308 }
2309
2310 QualType ArgType = CanTy;
2311 if (ConstArg)
2312 ArgType.addConst();
2313 if (VolatileArg)
2314 ArgType.addVolatile();
2315
2316 // This isn't /really/ specified by the standard, but it's implied
2317 // we should be working from an RValue in the case of move to ensure
2318 // that we prefer to bind to rvalue references, and an LValue in the
2319 // case of copy to ensure we don't bind to rvalue references.
2320 // Possibly an XValue is actually correct in the case of move, but
2321 // there is no semantic difference for class types in this restricted
2322 // case.
2323 ExprValueKind VK;
Sean Huntab183df2011-06-22 22:13:13 +00002324 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Sean Huntb320e0c2011-06-10 03:50:41 +00002325 VK = VK_LValue;
2326 else
2327 VK = VK_RValue;
2328
2329 NumArgs = 1;
2330 Arg = new (Context) OpaqueValueExpr(SourceLocation(), ArgType, VK);
2331 }
2332
2333 // Create the object argument
2334 QualType ThisTy = CanTy;
2335 if (ConstThis)
2336 ThisTy.addConst();
2337 if (VolatileThis)
2338 ThisTy.addVolatile();
Sean Hunt4cc12c62011-06-23 00:26:20 +00002339 Expr::Classification Classification =
Sean Huntb320e0c2011-06-10 03:50:41 +00002340 (new (Context) OpaqueValueExpr(SourceLocation(), ThisTy,
2341 RValueThis ? VK_RValue : VK_LValue))->
2342 Classify(Context);
2343
2344 // Now we perform lookup on the name we computed earlier and do overload
2345 // resolution. Lookup is only performed directly into the class since there
2346 // will always be a (possibly implicit) declaration to shadow any others.
2347 OverloadCandidateSet OCS((SourceLocation()));
2348 DeclContext::lookup_iterator I, E;
2349 Result->setConstParamMatch(false);
2350
Sean Huntc39b6bc2011-06-24 02:11:39 +00002351 llvm::tie(I, E) = RD->lookup(Name);
Sean Huntb320e0c2011-06-10 03:50:41 +00002352 assert((I != E) &&
2353 "lookup for a constructor or assignment operator was empty");
2354 for ( ; I != E; ++I) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002355 Decl *Cand = *I;
Sean Hunt4cc12c62011-06-23 00:26:20 +00002356
Sean Huntc39b6bc2011-06-24 02:11:39 +00002357 if (Cand->isInvalidDecl())
Sean Huntb320e0c2011-06-10 03:50:41 +00002358 continue;
2359
Sean Huntc39b6bc2011-06-24 02:11:39 +00002360 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2361 // FIXME: [namespace.udecl]p15 says that we should only consider a
2362 // using declaration here if it does not match a declaration in the
2363 // derived class. We do not implement this correctly in other cases
2364 // either.
2365 Cand = U->getTargetDecl();
2366
2367 if (Cand->isInvalidDecl())
2368 continue;
2369 }
2370
2371 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002372 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Sean Huntc39b6bc2011-06-24 02:11:39 +00002373 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Sean Hunt4cc12c62011-06-23 00:26:20 +00002374 Classification, &Arg, NumArgs, OCS, true);
2375 else
2376 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public), &Arg,
2377 NumArgs, OCS, true);
Sean Huntb320e0c2011-06-10 03:50:41 +00002378
2379 // Here we're looking for a const parameter to speed up creation of
2380 // implicit copy methods.
2381 if ((SM == CXXCopyAssignment && M->isCopyAssignmentOperator()) ||
2382 (SM == CXXCopyConstructor &&
2383 cast<CXXConstructorDecl>(M)->isCopyConstructor())) {
2384 QualType ArgType = M->getType()->getAs<FunctionProtoType>()->getArgType(0);
Sean Hunt661c67a2011-06-21 23:42:56 +00002385 if (!ArgType->isReferenceType() ||
2386 ArgType->getPointeeType().isConstQualified())
Sean Huntb320e0c2011-06-10 03:50:41 +00002387 Result->setConstParamMatch(true);
2388 }
Sean Hunt431a1cb2011-06-22 02:58:46 +00002389 } else if (FunctionTemplateDecl *Tmpl =
Sean Huntc39b6bc2011-06-24 02:11:39 +00002390 dyn_cast<FunctionTemplateDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002391 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2392 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Sean Huntc39b6bc2011-06-24 02:11:39 +00002393 RD, 0, ThisTy, Classification, &Arg, NumArgs,
Sean Hunt4cc12c62011-06-23 00:26:20 +00002394 OCS, true);
2395 else
2396 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
2397 0, &Arg, NumArgs, OCS, true);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002398 } else {
2399 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Sean Huntb320e0c2011-06-10 03:50:41 +00002400 }
2401 }
2402
2403 OverloadCandidateSet::iterator Best;
2404 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2405 case OR_Success:
2406 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2407 Result->setSuccess(true);
2408 break;
2409
2410 case OR_Deleted:
2411 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2412 Result->setSuccess(false);
2413 break;
2414
2415 case OR_Ambiguous:
2416 case OR_No_Viable_Function:
2417 Result->setMethod(0);
2418 Result->setSuccess(false);
2419 break;
2420 }
2421
2422 return Result;
2423}
2424
2425/// \brief Look up the default constructor for the given class.
2426CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Sean Huntc530d172011-06-10 04:44:37 +00002427 SpecialMemberOverloadResult *Result =
Sean Huntb320e0c2011-06-10 03:50:41 +00002428 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2429 false, false);
2430
2431 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Sean Hunt308742c2011-06-04 04:32:43 +00002432}
2433
Sean Hunt661c67a2011-06-21 23:42:56 +00002434/// \brief Look up the copying constructor for the given class.
2435CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
2436 unsigned Quals,
2437 bool *ConstParamMatch) {
Sean Huntc530d172011-06-10 04:44:37 +00002438 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2439 "non-const, non-volatile qualifiers for copy ctor arg");
2440 SpecialMemberOverloadResult *Result =
2441 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2442 Quals & Qualifiers::Volatile, false, false, false);
2443
2444 if (ConstParamMatch)
2445 *ConstParamMatch = Result->hasConstParamMatch();
2446
2447 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2448}
2449
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002450/// \brief Look up the moving constructor for the given class.
2451CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class) {
2452 SpecialMemberOverloadResult *Result =
2453 LookupSpecialMember(Class, CXXMoveConstructor, false,
2454 false, false, false, false);
2455
2456 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2457}
2458
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002459/// \brief Look up the constructors for the given class.
2460DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002461 // If the implicit constructors have not yet been declared, do so now.
Douglas Gregor18274032010-07-03 00:47:00 +00002462 if (CanDeclareSpecialMemberFunction(Context, Class)) {
Sean Huntcdee3fe2011-05-11 22:34:38 +00002463 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002464 DeclareImplicitDefaultConstructor(Class);
2465 if (!Class->hasDeclaredCopyConstructor())
2466 DeclareImplicitCopyConstructor(Class);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002467 if (getLangOptions().CPlusPlus0x && Class->needsImplicitMoveConstructor())
2468 DeclareImplicitMoveConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +00002469 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002470
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002471 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2472 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2473 return Class->lookup(Name);
2474}
2475
Sean Hunt661c67a2011-06-21 23:42:56 +00002476/// \brief Look up the copying assignment operator for the given class.
2477CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2478 unsigned Quals, bool RValueThis,
2479 unsigned ThisQuals,
2480 bool *ConstParamMatch) {
2481 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2482 "non-const, non-volatile qualifiers for copy assignment arg");
2483 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2484 "non-const, non-volatile qualifiers for copy assignment this");
2485 SpecialMemberOverloadResult *Result =
2486 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2487 Quals & Qualifiers::Volatile, RValueThis,
2488 ThisQuals & Qualifiers::Const,
2489 ThisQuals & Qualifiers::Volatile);
2490
2491 if (ConstParamMatch)
2492 *ConstParamMatch = Result->hasConstParamMatch();
2493
2494 return Result->getMethod();
2495}
2496
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002497/// \brief Look up the moving assignment operator for the given class.
2498CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
2499 bool RValueThis,
2500 unsigned ThisQuals) {
2501 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2502 "non-const, non-volatile qualifiers for copy assignment this");
2503 SpecialMemberOverloadResult *Result =
2504 LookupSpecialMember(Class, CXXMoveAssignment, false, false, RValueThis,
2505 ThisQuals & Qualifiers::Const,
2506 ThisQuals & Qualifiers::Volatile);
2507
2508 return Result->getMethod();
2509}
2510
Douglas Gregordb89f282010-07-01 22:47:18 +00002511/// \brief Look for the destructor of the given class.
2512///
Sean Huntc5c9b532011-06-03 21:10:40 +00002513/// During semantic analysis, this routine should be used in lieu of
2514/// CXXRecordDecl::getDestructor().
Douglas Gregordb89f282010-07-01 22:47:18 +00002515///
2516/// \returns The destructor for this class.
2517CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Sean Hunt308742c2011-06-04 04:32:43 +00002518 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2519 false, false, false,
2520 false, false)->getMethod());
Douglas Gregordb89f282010-07-01 22:47:18 +00002521}
2522
John McCall7edb5fd2010-01-26 07:16:45 +00002523void ADLResult::insert(NamedDecl *New) {
2524 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2525
2526 // If we haven't yet seen a decl for this key, or the last decl
2527 // was exactly this one, we're done.
2528 if (Old == 0 || Old == New) {
2529 Old = New;
2530 return;
2531 }
2532
2533 // Otherwise, decide which is a more recent redeclaration.
2534 FunctionDecl *OldFD, *NewFD;
2535 if (isa<FunctionTemplateDecl>(New)) {
2536 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2537 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2538 } else {
2539 OldFD = cast<FunctionDecl>(Old);
2540 NewFD = cast<FunctionDecl>(New);
2541 }
2542
2543 FunctionDecl *Cursor = NewFD;
2544 while (true) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002545 Cursor = Cursor->getPreviousDecl();
John McCall7edb5fd2010-01-26 07:16:45 +00002546
2547 // If we got to the end without finding OldFD, OldFD is the newer
2548 // declaration; leave things as they are.
2549 if (!Cursor) return;
2550
2551 // If we do find OldFD, then NewFD is newer.
2552 if (Cursor == OldFD) break;
2553
2554 // Otherwise, keep looking.
2555 }
2556
2557 Old = New;
2558}
2559
Sebastian Redl644be852009-10-23 19:23:15 +00002560void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002561 Expr **Args, unsigned NumArgs,
Richard Smithad762fc2011-04-14 22:09:26 +00002562 ADLResult &Result,
2563 bool StdNamespaceIsAssociated) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002564 // Find all of the associated namespaces and classes based on the
2565 // arguments we have.
2566 AssociatedNamespaceSet AssociatedNamespaces;
2567 AssociatedClassSet AssociatedClasses;
Mike Stump1eb44332009-09-09 15:08:12 +00002568 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCall6ff07852009-08-07 22:18:02 +00002569 AssociatedNamespaces,
2570 AssociatedClasses);
Richard Smithad762fc2011-04-14 22:09:26 +00002571 if (StdNamespaceIsAssociated && StdNamespace)
2572 AssociatedNamespaces.insert(getStdNamespace());
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002573
Sebastian Redl644be852009-10-23 19:23:15 +00002574 QualType T1, T2;
2575 if (Operator) {
2576 T1 = Args[0]->getType();
2577 if (NumArgs >= 2)
2578 T2 = Args[1]->getType();
2579 }
2580
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002581 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002582 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2583 // and let Y be the lookup set produced by argument dependent
2584 // lookup (defined as follows). If X contains [...] then Y is
2585 // empty. Otherwise Y is the set of declarations found in the
2586 // namespaces associated with the argument types as described
2587 // below. The set of declarations found by the lookup of the name
2588 // is the union of X and Y.
2589 //
2590 // Here, we compute Y and add its members to the overloaded
2591 // candidate set.
2592 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002593 NSEnd = AssociatedNamespaces.end();
2594 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002595 // When considering an associated namespace, the lookup is the
2596 // same as the lookup performed when the associated namespace is
2597 // used as a qualifier (3.4.3.2) except that:
2598 //
2599 // -- Any using-directives in the associated namespace are
2600 // ignored.
2601 //
John McCall6ff07852009-08-07 22:18:02 +00002602 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002603 // associated classes are visible within their respective
2604 // namespaces even if they are not visible during an ordinary
2605 // lookup (11.4).
2606 DeclContext::lookup_iterator I, E;
John McCall3f9a8a62009-08-11 06:59:38 +00002607 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall6e266892010-01-26 03:27:55 +00002608 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00002609 // If the only declaration here is an ordinary friend, consider
2610 // it only if it was declared in an associated classes.
2611 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00002612 DeclContext *LexDC = D->getLexicalDeclContext();
2613 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2614 continue;
2615 }
Mike Stump1eb44332009-09-09 15:08:12 +00002616
John McCalla113e722010-01-26 06:04:06 +00002617 if (isa<UsingShadowDecl>(D))
2618 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00002619
John McCalla113e722010-01-26 06:04:06 +00002620 if (isa<FunctionDecl>(D)) {
2621 if (Operator &&
2622 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2623 T1, T2, Context))
2624 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00002625 } else if (!isa<FunctionTemplateDecl>(D))
2626 continue;
2627
2628 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00002629 }
2630 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002631}
Douglas Gregor546be3c2009-12-30 17:04:44 +00002632
2633//----------------------------------------------------------------------------
2634// Search for all visible declarations.
2635//----------------------------------------------------------------------------
2636VisibleDeclConsumer::~VisibleDeclConsumer() { }
2637
2638namespace {
2639
2640class ShadowContextRAII;
2641
2642class VisibleDeclsRecord {
2643public:
2644 /// \brief An entry in the shadow map, which is optimized to store a
2645 /// single declaration (the common case) but can also store a list
2646 /// of declarations.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002647 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002648
2649private:
2650 /// \brief A mapping from declaration names to the declarations that have
2651 /// this name within a particular scope.
2652 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2653
2654 /// \brief A list of shadow maps, which is used to model name hiding.
2655 std::list<ShadowMap> ShadowMaps;
2656
2657 /// \brief The declaration contexts we have already visited.
2658 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2659
2660 friend class ShadowContextRAII;
2661
2662public:
2663 /// \brief Determine whether we have already visited this context
2664 /// (and, if not, note that we are going to visit that context now).
2665 bool visitedContext(DeclContext *Ctx) {
2666 return !VisitedContexts.insert(Ctx);
2667 }
2668
Douglas Gregor8071e422010-08-15 06:18:01 +00002669 bool alreadyVisitedContext(DeclContext *Ctx) {
2670 return VisitedContexts.count(Ctx);
2671 }
2672
Douglas Gregor546be3c2009-12-30 17:04:44 +00002673 /// \brief Determine whether the given declaration is hidden in the
2674 /// current scope.
2675 ///
2676 /// \returns the declaration that hides the given declaration, or
2677 /// NULL if no such declaration exists.
2678 NamedDecl *checkHidden(NamedDecl *ND);
2679
2680 /// \brief Add a declaration to the current shadow map.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002681 void add(NamedDecl *ND) {
2682 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2683 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002684};
2685
2686/// \brief RAII object that records when we've entered a shadow context.
2687class ShadowContextRAII {
2688 VisibleDeclsRecord &Visible;
2689
2690 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2691
2692public:
2693 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2694 Visible.ShadowMaps.push_back(ShadowMap());
2695 }
2696
2697 ~ShadowContextRAII() {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002698 Visible.ShadowMaps.pop_back();
2699 }
2700};
2701
2702} // end anonymous namespace
2703
Douglas Gregor546be3c2009-12-30 17:04:44 +00002704NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002705 // Look through using declarations.
2706 ND = ND->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002707
Douglas Gregor546be3c2009-12-30 17:04:44 +00002708 unsigned IDNS = ND->getIdentifierNamespace();
2709 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2710 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2711 SM != SMEnd; ++SM) {
2712 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2713 if (Pos == SM->end())
2714 continue;
2715
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002716 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00002717 IEnd = Pos->second.end();
2718 I != IEnd; ++I) {
2719 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002720 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002721 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor546be3c2009-12-30 17:04:44 +00002722 Decl::IDNS_ObjCProtocol)))
2723 continue;
2724
2725 // Protocols are in distinct namespaces from everything else.
2726 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2727 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2728 (*I)->getIdentifierNamespace() != IDNS)
2729 continue;
2730
Douglas Gregor0cc84042010-01-14 15:47:35 +00002731 // Functions and function templates in the same scope overload
2732 // rather than hide. FIXME: Look for hiding based on function
2733 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002734 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002735 ND->isFunctionOrFunctionTemplate() &&
2736 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002737 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002738
Douglas Gregor546be3c2009-12-30 17:04:44 +00002739 // We've found a declaration that hides this one.
2740 return *I;
2741 }
2742 }
2743
2744 return 0;
2745}
2746
2747static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2748 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002749 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002750 VisibleDeclConsumer &Consumer,
2751 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00002752 if (!Ctx)
2753 return;
2754
Douglas Gregor546be3c2009-12-30 17:04:44 +00002755 // Make sure we don't visit the same context twice.
2756 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2757 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002758
Douglas Gregor4923aa22010-07-02 20:37:36 +00002759 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2760 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2761
Douglas Gregor546be3c2009-12-30 17:04:44 +00002762 // Enumerate all of the results in this context.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00002763 llvm::SmallVector<DeclContext *, 2> Contexts;
2764 Ctx->collectAllContexts(Contexts);
2765 for (unsigned I = 0, N = Contexts.size(); I != N; ++I) {
2766 DeclContext *CurCtx = Contexts[I];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002767 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00002768 DEnd = CurCtx->decls_end();
2769 D != DEnd; ++D) {
Douglas Gregor70c23352010-12-09 21:44:02 +00002770 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) {
Douglas Gregor55368912011-12-14 16:03:29 +00002771 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00002772 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002773 Visited.add(ND);
2774 }
Douglas Gregor70c23352010-12-09 21:44:02 +00002775 }
Douglas Gregord98abd82011-02-16 01:39:26 +00002776
Sebastian Redl410c4f22010-08-31 20:53:31 +00002777 // Visit transparent contexts and inline namespaces inside this context.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002778 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
Sebastian Redl410c4f22010-08-31 20:53:31 +00002779 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Douglas Gregor0cc84042010-01-14 15:47:35 +00002780 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002781 Consumer, Visited);
2782 }
2783 }
2784 }
2785
2786 // Traverse using directives for qualified name lookup.
2787 if (QualifiedNameLookup) {
2788 ShadowContextRAII Shadow(Visited);
2789 DeclContext::udir_iterator I, E;
2790 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002791 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002792 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002793 }
2794 }
2795
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002796 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002797 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00002798 if (!Record->hasDefinition())
2799 return;
2800
Douglas Gregor546be3c2009-12-30 17:04:44 +00002801 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2802 BEnd = Record->bases_end();
2803 B != BEnd; ++B) {
2804 QualType BaseType = B->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002805
Douglas Gregor546be3c2009-12-30 17:04:44 +00002806 // Don't look into dependent bases, because name lookup can't look
2807 // there anyway.
2808 if (BaseType->isDependentType())
2809 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002810
Douglas Gregor546be3c2009-12-30 17:04:44 +00002811 const RecordType *Record = BaseType->getAs<RecordType>();
2812 if (!Record)
2813 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002814
Douglas Gregor546be3c2009-12-30 17:04:44 +00002815 // FIXME: It would be nice to be able to determine whether referencing
2816 // a particular member would be ambiguous. For example, given
2817 //
2818 // struct A { int member; };
2819 // struct B { int member; };
2820 // struct C : A, B { };
2821 //
2822 // void f(C *c) { c->### }
2823 //
2824 // accessing 'member' would result in an ambiguity. However, we
2825 // could be smart enough to qualify the member with the base
2826 // class, e.g.,
2827 //
2828 // c->B::member
2829 //
2830 // or
2831 //
2832 // c->A::member
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002833
Douglas Gregor546be3c2009-12-30 17:04:44 +00002834 // Find results in this base class (and its bases).
2835 ShadowContextRAII Shadow(Visited);
2836 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002837 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002838 }
2839 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002840
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002841 // Traverse the contexts of Objective-C classes.
2842 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2843 // Traverse categories.
2844 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2845 Category; Category = Category->getNextClassCategory()) {
2846 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002847 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002848 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002849 }
2850
2851 // Traverse protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00002852 for (ObjCInterfaceDecl::all_protocol_iterator
2853 I = IFace->all_referenced_protocol_begin(),
2854 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002855 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002856 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002857 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002858 }
2859
2860 // Traverse the superclass.
2861 if (IFace->getSuperClass()) {
2862 ShadowContextRAII Shadow(Visited);
2863 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002864 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002865 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002866
Douglas Gregorc220a182010-04-19 18:02:19 +00002867 // If there is an implementation, traverse it. We do this to find
2868 // synthesized ivars.
2869 if (IFace->getImplementation()) {
2870 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002871 LookupVisibleDecls(IFace->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00002872 QualifiedNameLookup, true, Consumer, Visited);
2873 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002874 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2875 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2876 E = Protocol->protocol_end(); I != E; ++I) {
2877 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002878 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002879 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002880 }
2881 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2882 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2883 E = Category->protocol_end(); I != E; ++I) {
2884 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002885 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002886 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002887 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002888
Douglas Gregorc220a182010-04-19 18:02:19 +00002889 // If there is an implementation, traverse it.
2890 if (Category->getImplementation()) {
2891 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002892 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00002893 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002894 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002895 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002896}
2897
2898static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2899 UnqualUsingDirectiveSet &UDirs,
2900 VisibleDeclConsumer &Consumer,
2901 VisibleDeclsRecord &Visited) {
2902 if (!S)
2903 return;
2904
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002905 if (!S->getEntity() ||
2906 (!S->getParent() &&
Douglas Gregor8071e422010-08-15 06:18:01 +00002907 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor539c5c32010-01-07 00:31:29 +00002908 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2909 // Walk through the declarations in this Scope.
2910 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2911 D != DEnd; ++D) {
John McCalld226f652010-08-21 09:40:31 +00002912 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor55368912011-12-14 16:03:29 +00002913 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00002914 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002915 Visited.add(ND);
2916 }
2917 }
2918 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002919
Douglas Gregor711be1e2010-03-15 14:33:29 +00002920 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00002921 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00002922 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002923 // Look into this scope's declaration context, along with any of its
2924 // parent lookup contexts (e.g., enclosing classes), up to the point
2925 // where we hit the context stored in the next outer scope.
2926 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00002927 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002928
Douglas Gregordbdf5e72010-03-15 15:26:48 +00002929 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002930 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002931 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2932 if (Method->isInstanceMethod()) {
2933 // For instance methods, look for ivars in the method's interface.
2934 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2935 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregorca45da02010-11-02 20:36:02 +00002936 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002937 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Fariborz Jahanian8697d302011-08-31 22:24:06 +00002938 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorca45da02010-11-02 20:36:02 +00002939 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002940 }
2941
2942 // We've already performed all of the name lookup that we need
2943 // to for Objective-C methods; the next context will be the
2944 // outer scope.
2945 break;
2946 }
2947
Douglas Gregor546be3c2009-12-30 17:04:44 +00002948 if (Ctx->isFunctionOrMethod())
2949 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002950
2951 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002952 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002953 }
2954 } else if (!S->getParent()) {
2955 // Look into the translation unit scope. We walk through the translation
2956 // unit's declaration context, because the Scope itself won't have all of
2957 // the declarations if we loaded a precompiled header.
2958 // FIXME: We would like the translation unit's Scope object to point to the
2959 // translation unit, so we don't need this special "if" branch. However,
2960 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002961 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002962 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00002963 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002964 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002965 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002966 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002967 }
2968
Douglas Gregor546be3c2009-12-30 17:04:44 +00002969 if (Entity) {
2970 // Lookup visible declarations in any namespaces found by using
2971 // directives.
2972 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2973 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2974 for (; UI != UEnd; ++UI)
2975 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002976 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002977 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002978 }
2979
2980 // Lookup names in the parent scope.
2981 ShadowContextRAII Shadow(Visited);
2982 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2983}
2984
2985void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00002986 VisibleDeclConsumer &Consumer,
2987 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002988 // Determine the set of using directives available during
2989 // unqualified name lookup.
2990 Scope *Initial = S;
2991 UnqualUsingDirectiveSet UDirs;
2992 if (getLangOptions().CPlusPlus) {
2993 // Find the first namespace or translation-unit scope.
2994 while (S && !isNamespaceOrTranslationUnitScope(S))
2995 S = S->getParent();
2996
2997 UDirs.visitScopeChain(Initial, S);
2998 }
2999 UDirs.done();
3000
3001 // Look for visible declarations.
3002 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3003 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003004 if (!IncludeGlobalScope)
3005 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003006 ShadowContextRAII Shadow(Visited);
3007 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3008}
3009
3010void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00003011 VisibleDeclConsumer &Consumer,
3012 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003013 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3014 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003015 if (!IncludeGlobalScope)
3016 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003017 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003018 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003019 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003020}
3021
Chris Lattner4ae493c2011-02-18 02:08:43 +00003022/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara67843042011-03-05 18:21:20 +00003023/// If GnuLabelLoc is a valid source location, then this is a definition
3024/// of an __label__ label name, otherwise it is a normal label definition
3025/// or use.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003026LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara67843042011-03-05 18:21:20 +00003027 SourceLocation GnuLabelLoc) {
Chris Lattner337e5502011-02-18 01:27:55 +00003028 // Do a lookup to see if we have a label with this name already.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003029 NamedDecl *Res = 0;
Abramo Bagnara67843042011-03-05 18:21:20 +00003030
3031 if (GnuLabelLoc.isValid()) {
3032 // Local label definitions always shadow existing labels.
3033 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3034 Scope *S = CurScope;
3035 PushOnScopeChains(Res, S, true);
3036 return cast<LabelDecl>(Res);
3037 }
3038
3039 // Not a GNU local label.
3040 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3041 // If we found a label, check to see if it is in the same context as us.
3042 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattner337e5502011-02-18 01:27:55 +00003043 if (Res && Res->getDeclContext() != CurContext)
3044 Res = 0;
Chris Lattner337e5502011-02-18 01:27:55 +00003045 if (Res == 0) {
3046 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara67843042011-03-05 18:21:20 +00003047 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3048 Scope *S = CurScope->getFnParent();
Chris Lattnerfebb5b82011-02-18 21:16:39 +00003049 assert(S && "Not in a function?");
3050 PushOnScopeChains(Res, S, true);
Chris Lattner337e5502011-02-18 01:27:55 +00003051 }
Chris Lattner337e5502011-02-18 01:27:55 +00003052 return cast<LabelDecl>(Res);
3053}
3054
3055//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003056// Typo correction
Chris Lattner337e5502011-02-18 01:27:55 +00003057//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003058
3059namespace {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003060
3061typedef llvm::StringMap<TypoCorrection, llvm::BumpPtrAllocator> TypoResultsMap;
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003062typedef std::map<unsigned, TypoResultsMap *> TypoEditDistanceMap;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003063
3064static const unsigned MaxTypoDistanceResultSets = 5;
3065
Douglas Gregor546be3c2009-12-30 17:04:44 +00003066class TypoCorrectionConsumer : public VisibleDeclConsumer {
3067 /// \brief The name written that is a typo in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003068 StringRef Typo;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003069
3070 /// \brief The results found that have the smallest edit distance
3071 /// found (so far) with the typo name.
Douglas Gregore24b5752010-10-14 20:34:08 +00003072 ///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003073 /// The pointer value being set to the current DeclContext indicates
3074 /// whether there is a keyword with this name.
3075 TypoEditDistanceMap BestResults;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003076
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003077 Sema &SemaRef;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003078
Douglas Gregor546be3c2009-12-30 17:04:44 +00003079public:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003080 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003081 : Typo(Typo->getName()),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003082 SemaRef(SemaRef) { }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003083
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003084 ~TypoCorrectionConsumer() {
3085 for (TypoEditDistanceMap::iterator I = BestResults.begin(),
3086 IEnd = BestResults.end();
3087 I != IEnd;
3088 ++I)
3089 delete I->second;
3090 }
3091
Erik Verbruggend1205962011-10-06 07:27:49 +00003092 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3093 bool InBaseClass);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003094 void FoundName(StringRef Name);
3095 void addKeywordResult(StringRef Keyword);
3096 void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003097 NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003098 void addCorrection(TypoCorrection Correction);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003099
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003100 typedef TypoResultsMap::iterator result_iterator;
3101 typedef TypoEditDistanceMap::iterator distance_iterator;
3102 distance_iterator begin() { return BestResults.begin(); }
3103 distance_iterator end() { return BestResults.end(); }
3104 void erase(distance_iterator I) { BestResults.erase(I); }
Douglas Gregore24b5752010-10-14 20:34:08 +00003105 unsigned size() const { return BestResults.size(); }
3106 bool empty() const { return BestResults.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003107
Chris Lattner5f9e2722011-07-23 10:55:15 +00003108 TypoCorrection &operator[](StringRef Name) {
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003109 return (*BestResults.begin()->second)[Name];
Douglas Gregor7b824e82010-10-15 13:35:25 +00003110 }
3111
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003112 unsigned getBestEditDistance(bool Normalized) {
3113 if (BestResults.empty())
3114 return (std::numeric_limits<unsigned>::max)();
3115
3116 unsigned BestED = BestResults.begin()->first;
3117 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003118 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003119};
3120
3121}
3122
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003123void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggend1205962011-10-06 07:27:49 +00003124 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003125 // Don't consider hidden names for typo correction.
3126 if (Hiding)
3127 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003128
Douglas Gregor546be3c2009-12-30 17:04:44 +00003129 // Only consider entities with identifiers for names, ignoring
3130 // special names (constructors, overloaded operators, selectors,
3131 // etc.).
3132 IdentifierInfo *Name = ND->getIdentifier();
3133 if (!Name)
3134 return;
3135
Douglas Gregor95f42922010-10-14 22:11:03 +00003136 FoundName(Name->getName());
3137}
3138
Chris Lattner5f9e2722011-07-23 10:55:15 +00003139void TypoCorrectionConsumer::FoundName(StringRef Name) {
Douglas Gregor362a8f22010-10-19 19:39:10 +00003140 // Use a simple length-based heuristic to determine the minimum possible
3141 // edit distance. If the minimum isn't good enough, bail out early.
3142 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003143 if (MinED && Typo.size() / MinED < 3)
Douglas Gregor362a8f22010-10-19 19:39:10 +00003144 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003145
Douglas Gregora1194772010-10-19 22:14:33 +00003146 // Compute an upper bound on the allowable edit distance, so that the
3147 // edit-distance algorithm can short-circuit.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003148 unsigned UpperBound = (Typo.size() + 2) / 3;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003149
Douglas Gregor546be3c2009-12-30 17:04:44 +00003150 // Compute the edit distance between the typo and the name of this
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003151 // entity, and add the identifier to the list of results.
3152 addName(Name, NULL, Typo.edit_distance(Name, true, UpperBound));
Douglas Gregor546be3c2009-12-30 17:04:44 +00003153}
3154
Chris Lattner5f9e2722011-07-23 10:55:15 +00003155void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003156 // Compute the edit distance between the typo and this keyword,
3157 // and add the keyword to the list of results.
3158 addName(Keyword, NULL, Typo.edit_distance(Keyword), NULL, true);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003159}
3160
Chris Lattner5f9e2722011-07-23 10:55:15 +00003161void TypoCorrectionConsumer::addName(StringRef Name,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003162 NamedDecl *ND,
3163 unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003164 NestedNameSpecifier *NNS,
3165 bool isKeyword) {
3166 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
3167 if (isKeyword) TC.makeKeyword();
3168 addCorrection(TC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003169}
3170
3171void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003172 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003173 TypoResultsMap *& Map = BestResults[Correction.getEditDistance(false)];
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003174 if (!Map)
3175 Map = new TypoResultsMap;
Chandler Carruth55620532011-06-28 22:48:40 +00003176
3177 TypoCorrection &CurrentCorrection = (*Map)[Name];
3178 if (!CurrentCorrection ||
3179 // FIXME: The following should be rolled up into an operator< on
3180 // TypoCorrection with a more principled definition.
3181 CurrentCorrection.isKeyword() < Correction.isKeyword() ||
3182 Correction.getAsString(SemaRef.getLangOptions()) <
3183 CurrentCorrection.getAsString(SemaRef.getLangOptions()))
3184 CurrentCorrection = Correction;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003185
3186 while (BestResults.size() > MaxTypoDistanceResultSets) {
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003187 TypoEditDistanceMap::iterator Last = BestResults.end();
3188 --Last;
3189 delete Last->second;
3190 BestResults.erase(Last);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003191 }
3192}
3193
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003194// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3195// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3196// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3197static void getNestedNameSpecifierIdentifiers(
3198 NestedNameSpecifier *NNS,
3199 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3200 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3201 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3202 else
3203 Identifiers.clear();
3204
3205 const IdentifierInfo *II = NULL;
3206
3207 switch (NNS->getKind()) {
3208 case NestedNameSpecifier::Identifier:
3209 II = NNS->getAsIdentifier();
3210 break;
3211
3212 case NestedNameSpecifier::Namespace:
3213 if (NNS->getAsNamespace()->isAnonymousNamespace())
3214 return;
3215 II = NNS->getAsNamespace()->getIdentifier();
3216 break;
3217
3218 case NestedNameSpecifier::NamespaceAlias:
3219 II = NNS->getAsNamespaceAlias()->getIdentifier();
3220 break;
3221
3222 case NestedNameSpecifier::TypeSpecWithTemplate:
3223 case NestedNameSpecifier::TypeSpec:
3224 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3225 break;
3226
3227 case NestedNameSpecifier::Global:
3228 return;
3229 }
3230
3231 if (II)
3232 Identifiers.push_back(II);
3233}
3234
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003235namespace {
3236
3237class SpecifierInfo {
3238 public:
3239 DeclContext* DeclCtx;
3240 NestedNameSpecifier* NameSpecifier;
3241 unsigned EditDistance;
3242
3243 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3244 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3245};
3246
Chris Lattner5f9e2722011-07-23 10:55:15 +00003247typedef SmallVector<DeclContext*, 4> DeclContextList;
3248typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003249
3250class NamespaceSpecifierSet {
3251 ASTContext &Context;
3252 DeclContextList CurContextChain;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003253 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3254 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003255 bool isSorted;
3256
3257 SpecifierInfoList Specifiers;
3258 llvm::SmallSetVector<unsigned, 4> Distances;
3259 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3260
3261 /// \brief Helper for building the list of DeclContexts between the current
3262 /// context and the top of the translation unit
3263 static DeclContextList BuildContextChain(DeclContext *Start);
3264
3265 void SortNamespaces();
3266
3267 public:
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003268 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3269 CXXScopeSpec *CurScopeSpec)
Benjamin Kramerc5bb9d42011-07-05 09:46:31 +00003270 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003271 isSorted(true) {
3272 if (CurScopeSpec && CurScopeSpec->getScopeRep())
3273 getNestedNameSpecifierIdentifiers(CurScopeSpec->getScopeRep(),
3274 CurNameSpecifierIdentifiers);
3275 // Build the list of identifiers that would be used for an absolute
3276 // (from the global context) NestedNameSpecifier refering to the current
3277 // context.
3278 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3279 CEnd = CurContextChain.rend();
3280 C != CEnd; ++C) {
3281 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3282 CurContextIdentifiers.push_back(ND->getIdentifier());
3283 }
3284 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003285
3286 /// \brief Add the namespace to the set, computing the corresponding
3287 /// NestedNameSpecifier and its distance in the process.
3288 void AddNamespace(NamespaceDecl *ND);
3289
3290 typedef SpecifierInfoList::iterator iterator;
3291 iterator begin() {
3292 if (!isSorted) SortNamespaces();
3293 return Specifiers.begin();
3294 }
3295 iterator end() { return Specifiers.end(); }
3296};
3297
3298}
3299
3300DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003301 assert(Start && "Bulding a context chain from a null context");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003302 DeclContextList Chain;
3303 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3304 DC = DC->getLookupParent()) {
3305 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3306 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3307 !(ND && ND->isAnonymousNamespace()))
3308 Chain.push_back(DC->getPrimaryContext());
3309 }
3310 return Chain;
3311}
3312
3313void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003314 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003315 sortedDistances.append(Distances.begin(), Distances.end());
3316
3317 if (sortedDistances.size() > 1)
3318 std::sort(sortedDistances.begin(), sortedDistances.end());
3319
3320 Specifiers.clear();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003321 for (SmallVector<unsigned, 4>::iterator DI = sortedDistances.begin(),
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003322 DIEnd = sortedDistances.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003323 DI != DIEnd; ++DI) {
3324 SpecifierInfoList &SpecList = DistanceMap[*DI];
3325 Specifiers.append(SpecList.begin(), SpecList.end());
3326 }
3327
3328 isSorted = true;
3329}
3330
3331void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003332 DeclContext *Ctx = cast<DeclContext>(ND);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003333 NestedNameSpecifier *NNS = NULL;
3334 unsigned NumSpecifiers = 0;
3335 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003336 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003337
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003338 // Eliminate common elements from the two DeclContext chains.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003339 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3340 CEnd = CurContextChain.rend();
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003341 C != CEnd && !NamespaceDeclChain.empty() &&
3342 NamespaceDeclChain.back() == *C; ++C) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003343 NamespaceDeclChain.pop_back();
3344 }
3345
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003346 // Add an explicit leading '::' specifier if needed.
3347 if (NamespaceDecl *ND =
Kaelyn Uhrain3ad02aa2012-02-15 22:59:03 +00003348 NamespaceDeclChain.empty() ? NULL :
3349 dyn_cast_or_null<NamespaceDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003350 IdentifierInfo *Name = ND->getIdentifier();
3351 if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3352 Name) != CurContextIdentifiers.end() ||
3353 std::find(CurNameSpecifierIdentifiers.begin(),
3354 CurNameSpecifierIdentifiers.end(),
3355 Name) != CurNameSpecifierIdentifiers.end()) {
3356 NamespaceDeclChain = FullNamespaceDeclChain;
3357 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3358 }
3359 }
3360
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003361 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3362 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3363 CEnd = NamespaceDeclChain.rend();
3364 C != CEnd; ++C) {
3365 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3366 if (ND) {
3367 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3368 ++NumSpecifiers;
3369 }
3370 }
3371
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003372 // If the built NestedNameSpecifier would be replacing an existing
3373 // NestedNameSpecifier, use the number of component identifiers that
3374 // would need to be changed as the edit distance instead of the number
3375 // of components in the built NestedNameSpecifier.
3376 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3377 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3378 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3379 NumSpecifiers = llvm::ComputeEditDistance(
3380 llvm::ArrayRef<const IdentifierInfo*>(CurNameSpecifierIdentifiers),
3381 llvm::ArrayRef<const IdentifierInfo*>(NewNameSpecifierIdentifiers));
3382 }
3383
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003384 isSorted = false;
3385 Distances.insert(NumSpecifiers);
3386 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
Douglas Gregoraaf87162010-04-14 20:04:41 +00003387}
3388
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003389/// \brief Perform name lookup for a possible result for typo correction.
3390static void LookupPotentialTypoResult(Sema &SemaRef,
3391 LookupResult &Res,
3392 IdentifierInfo *Name,
3393 Scope *S, CXXScopeSpec *SS,
3394 DeclContext *MemberContext,
3395 bool EnteringContext,
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003396 bool isObjCIvarLookup) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003397 Res.suppressDiagnostics();
3398 Res.clear();
3399 Res.setLookupName(Name);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003400 if (MemberContext) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003401 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003402 if (isObjCIvarLookup) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003403 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3404 Res.addDecl(Ivar);
3405 Res.resolveKind();
3406 return;
3407 }
3408 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003409
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003410 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3411 Res.addDecl(Prop);
3412 Res.resolveKind();
3413 return;
3414 }
3415 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003416
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003417 SemaRef.LookupQualifiedName(Res, MemberContext);
3418 return;
3419 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003420
3421 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003422 EnteringContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003423
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003424 // Fake ivar lookup; this should really be part of
3425 // LookupParsedName.
3426 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3427 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003428 (Res.empty() ||
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003429 (Res.isSingleResult() &&
3430 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003431 if (ObjCIvarDecl *IV
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003432 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3433 Res.addDecl(IV);
3434 Res.resolveKind();
3435 }
3436 }
3437 }
3438}
3439
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003440/// \brief Add keywords to the consumer as possible typo corrections.
3441static void AddKeywordsToConsumer(Sema &SemaRef,
3442 TypoCorrectionConsumer &Consumer,
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003443 Scope *S, CorrectionCandidateCallback &CCC) {
3444 if (CCC.WantObjCSuper)
3445 Consumer.addKeywordResult("super");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003446
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003447 if (CCC.WantTypeSpecifiers) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003448 // Add type-specifier keywords to the set of results.
3449 const char *CTypeSpecs[] = {
3450 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor07f4a062011-07-01 21:27:45 +00003451 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003452 "_Complex", "_Imaginary",
3453 // storage-specifiers as well
3454 "extern", "inline", "static", "typedef"
3455 };
3456
3457 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3458 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3459 Consumer.addKeywordResult(CTypeSpecs[I]);
3460
3461 if (SemaRef.getLangOptions().C99)
3462 Consumer.addKeywordResult("restrict");
3463 if (SemaRef.getLangOptions().Bool || SemaRef.getLangOptions().CPlusPlus)
3464 Consumer.addKeywordResult("bool");
Douglas Gregor07f4a062011-07-01 21:27:45 +00003465 else if (SemaRef.getLangOptions().C99)
3466 Consumer.addKeywordResult("_Bool");
3467
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003468 if (SemaRef.getLangOptions().CPlusPlus) {
3469 Consumer.addKeywordResult("class");
3470 Consumer.addKeywordResult("typename");
3471 Consumer.addKeywordResult("wchar_t");
3472
3473 if (SemaRef.getLangOptions().CPlusPlus0x) {
3474 Consumer.addKeywordResult("char16_t");
3475 Consumer.addKeywordResult("char32_t");
3476 Consumer.addKeywordResult("constexpr");
3477 Consumer.addKeywordResult("decltype");
3478 Consumer.addKeywordResult("thread_local");
3479 }
3480 }
3481
3482 if (SemaRef.getLangOptions().GNUMode)
3483 Consumer.addKeywordResult("typeof");
3484 }
3485
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003486 if (CCC.WantCXXNamedCasts && SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003487 Consumer.addKeywordResult("const_cast");
3488 Consumer.addKeywordResult("dynamic_cast");
3489 Consumer.addKeywordResult("reinterpret_cast");
3490 Consumer.addKeywordResult("static_cast");
3491 }
3492
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003493 if (CCC.WantExpressionKeywords) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003494 Consumer.addKeywordResult("sizeof");
3495 if (SemaRef.getLangOptions().Bool || SemaRef.getLangOptions().CPlusPlus) {
3496 Consumer.addKeywordResult("false");
3497 Consumer.addKeywordResult("true");
3498 }
3499
3500 if (SemaRef.getLangOptions().CPlusPlus) {
3501 const char *CXXExprs[] = {
3502 "delete", "new", "operator", "throw", "typeid"
3503 };
3504 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3505 for (unsigned I = 0; I != NumCXXExprs; ++I)
3506 Consumer.addKeywordResult(CXXExprs[I]);
3507
3508 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3509 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3510 Consumer.addKeywordResult("this");
3511
3512 if (SemaRef.getLangOptions().CPlusPlus0x) {
3513 Consumer.addKeywordResult("alignof");
3514 Consumer.addKeywordResult("nullptr");
3515 }
3516 }
3517 }
3518
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003519 if (CCC.WantRemainingKeywords) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003520 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3521 // Statements.
3522 const char *CStmts[] = {
3523 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3524 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3525 for (unsigned I = 0; I != NumCStmts; ++I)
3526 Consumer.addKeywordResult(CStmts[I]);
3527
3528 if (SemaRef.getLangOptions().CPlusPlus) {
3529 Consumer.addKeywordResult("catch");
3530 Consumer.addKeywordResult("try");
3531 }
3532
3533 if (S && S->getBreakParent())
3534 Consumer.addKeywordResult("break");
3535
3536 if (S && S->getContinueParent())
3537 Consumer.addKeywordResult("continue");
3538
3539 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3540 Consumer.addKeywordResult("case");
3541 Consumer.addKeywordResult("default");
3542 }
3543 } else {
3544 if (SemaRef.getLangOptions().CPlusPlus) {
3545 Consumer.addKeywordResult("namespace");
3546 Consumer.addKeywordResult("template");
3547 }
3548
3549 if (S && S->isClassScope()) {
3550 Consumer.addKeywordResult("explicit");
3551 Consumer.addKeywordResult("friend");
3552 Consumer.addKeywordResult("mutable");
3553 Consumer.addKeywordResult("private");
3554 Consumer.addKeywordResult("protected");
3555 Consumer.addKeywordResult("public");
3556 Consumer.addKeywordResult("virtual");
3557 }
3558 }
3559
3560 if (SemaRef.getLangOptions().CPlusPlus) {
3561 Consumer.addKeywordResult("using");
3562
3563 if (SemaRef.getLangOptions().CPlusPlus0x)
3564 Consumer.addKeywordResult("static_assert");
3565 }
3566 }
3567}
3568
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003569static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3570 TypoCorrection &Candidate) {
3571 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3572 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3573}
3574
Douglas Gregor546be3c2009-12-30 17:04:44 +00003575/// \brief Try to "correct" a typo in the source code by finding
3576/// visible declarations whose names are similar to the name that was
3577/// present in the source code.
3578///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003579/// \param TypoName the \c DeclarationNameInfo structure that contains
3580/// the name that was present in the source code along with its location.
3581///
3582/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003583///
3584/// \param S the scope in which name lookup occurs.
3585///
3586/// \param SS the nested-name-specifier that precedes the name we're
3587/// looking for, if present.
3588///
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003589/// \param CCC A CorrectionCandidateCallback object that provides further
3590/// validation of typo correction candidates. It also provides flags for
3591/// determining the set of keywords permitted.
3592///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003593/// \param MemberContext if non-NULL, the context in which to look for
3594/// a member access expression.
3595///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003596/// \param EnteringContext whether we're entering the context described by
Douglas Gregorbb092ba2009-12-31 05:20:13 +00003597/// the nested-name-specifier SS.
3598///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003599/// \param OPT when non-NULL, the search for visible declarations will
3600/// also walk the protocols in the qualified interfaces of \p OPT.
3601///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003602/// \returns a \c TypoCorrection containing the corrected name if the typo
3603/// along with information such as the \c NamedDecl where the corrected name
3604/// was declared, and any additional \c NestedNameSpecifier needed to access
3605/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3606TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3607 Sema::LookupNameKind LookupKind,
3608 Scope *S, CXXScopeSpec *SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00003609 CorrectionCandidateCallback &CCC,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003610 DeclContext *MemberContext,
3611 bool EnteringContext,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003612 const ObjCObjectPointerType *OPT) {
Douglas Gregora0068fc2010-07-09 17:35:33 +00003613 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003614 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003615
Francois Pichet4d604d62011-12-03 15:55:29 +00003616 // In Microsoft mode, don't perform typo correction in a template member
3617 // function dependent context because it interferes with the "lookup into
3618 // dependent bases of class templates" feature.
3619 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
3620 isa<CXXMethodDecl>(CurContext))
3621 return TypoCorrection();
3622
Douglas Gregor546be3c2009-12-30 17:04:44 +00003623 // We only attempt to correct typos for identifiers.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003624 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003625 if (!Typo)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003626 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003627
3628 // If the scope specifier itself was invalid, don't try to correct
3629 // typos.
3630 if (SS && SS->isInvalid())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003631 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003632
3633 // Never try to correct typos during template deduction or
3634 // instantiation.
3635 if (!ActiveTemplateInstantiations.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003636 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003637
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003638 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003639
3640 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003641
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003642 // If a callback object considers an empty typo correction candidate to be
3643 // viable, assume it does not do any actual validation of the candidates.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003644 TypoCorrection EmptyCorrection;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003645 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003646
Douglas Gregoraaf87162010-04-14 20:04:41 +00003647 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003648 bool IsUnqualifiedLookup = false;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003649 DeclContext *QualifiedDC = MemberContext;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003650 if (MemberContext) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003651 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003652
3653 // Look in qualified interfaces.
3654 if (OPT) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003655 for (ObjCObjectPointerType::qual_iterator
3656 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003657 I != E; ++I)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003658 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003659 }
3660 } else if (SS && SS->isSet()) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003661 QualifiedDC = computeDeclContext(*SS, EnteringContext);
3662 if (!QualifiedDC)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003663 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003664
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003665 // Provide a stop gap for files that are just seriously broken. Trying
3666 // to correct all typos can turn into a HUGE performance penalty, causing
3667 // some files to take minutes to get rejected by the parser.
3668 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003669 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003670 ++TyposCorrected;
3671
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003672 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003673 } else {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003674 IsUnqualifiedLookup = true;
3675 UnqualifiedTyposCorrectedMap::iterator Cached
3676 = UnqualifiedTyposCorrected.find(Typo);
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003677 if (Cached != UnqualifiedTyposCorrected.end()) {
3678 // Add the cached value, unless it's a keyword or fails validation. In the
3679 // keyword case, we'll end up adding the keyword below.
3680 if (Cached->second) {
3681 if (!Cached->second.isKeyword() &&
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003682 isCandidateViable(CCC, Cached->second))
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003683 Consumer.addCorrection(Cached->second);
3684 } else {
3685 // Only honor no-correction cache hits when a callback that will validate
3686 // correction candidates is not being used.
3687 if (!ValidatingCallback)
3688 return TypoCorrection();
3689 }
3690 }
3691 if (Cached == UnqualifiedTyposCorrected.end()) {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003692 // Provide a stop gap for files that are just seriously broken. Trying
3693 // to correct all typos can turn into a HUGE performance penalty, causing
3694 // some files to take minutes to get rejected by the parser.
3695 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003696 return TypoCorrection();
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003697 }
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003698 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003699
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003700 if (IsUnqualifiedLookup || (QualifiedDC && QualifiedDC->isNamespace())) {
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003701 // For unqualified lookup, look through all of the names that we have
3702 // seen in this translation unit.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003703 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003704 for (IdentifierTable::iterator I = Context.Idents.begin(),
3705 IEnd = Context.Idents.end();
3706 I != IEnd; ++I)
3707 Consumer.FoundName(I->getKey());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003708
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003709 // Walk through identifiers in external identifier sources.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003710 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003711 if (IdentifierInfoLookup *External
3712 = Context.Idents.getExternalIdentifierLookup()) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00003713 OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003714 do {
3715 StringRef Name = Iter->Next();
3716 if (Name.empty())
3717 break;
Douglas Gregor95f42922010-10-14 22:11:03 +00003718
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003719 Consumer.FoundName(Name);
3720 } while (true);
Douglas Gregor95f42922010-10-14 22:11:03 +00003721 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003722 }
3723
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00003724 AddKeywordsToConsumer(*this, Consumer, S, CCC);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003725
Douglas Gregoraaf87162010-04-14 20:04:41 +00003726 // If we haven't found anything, we're done.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003727 if (Consumer.empty()) {
3728 // If this was an unqualified lookup, note that no correction was found.
3729 if (IsUnqualifiedLookup)
3730 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003731
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003732 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003733 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003734
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003735 // Make sure that the user typed at least 3 characters for each correction
Douglas Gregore24b5752010-10-14 20:34:08 +00003736 // made. Otherwise, we don't even both looking at the results.
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003737 unsigned ED = Consumer.getBestEditDistance(true);
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003738 if (ED > 0 && Typo->getName().size() / ED < 3) {
3739 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregor157a3ff2010-10-27 14:20:34 +00003740 if (IsUnqualifiedLookup)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003741 (void)UnqualifiedTyposCorrected[Typo];
3742
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003743 return TypoCorrection();
3744 }
3745
3746 // Build the NestedNameSpecifiers for the KnownNamespaces
3747 if (getLangOptions().CPlusPlus) {
3748 // Load any externally-known namespaces.
3749 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003750 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003751 LoadedExternalKnownNamespaces = true;
3752 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
3753 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
3754 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
3755 }
3756
3757 for (llvm::DenseMap<NamespaceDecl*, bool>::iterator
3758 KNI = KnownNamespaces.begin(),
3759 KNIEnd = KnownNamespaces.end();
3760 KNI != KNIEnd; ++KNI)
3761 Namespaces.AddNamespace(KNI->first);
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003762 }
Douglas Gregore24b5752010-10-14 20:34:08 +00003763
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003764 // Weed out any names that could not be found by name lookup or, if a
3765 // CorrectionCandidateCallback object was provided, failed validation.
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003766 llvm::SmallVector<TypoCorrection, 16> QualifiedResults;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003767 LookupResult TmpRes(*this, TypoName, LookupKind);
3768 TmpRes.suppressDiagnostics();
3769 while (!Consumer.empty()) {
3770 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3771 unsigned ED = DI->first;
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003772 for (TypoCorrectionConsumer::result_iterator I = DI->second->begin(),
3773 IEnd = DI->second->end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003774 I != IEnd; /* Increment in loop. */) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003775 // If the item already has been looked up or is a keyword, keep it.
3776 // If a validator callback object was given, drop the correction
3777 // unless it passes validation.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003778 if (I->second.isResolved()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003779 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003780 ++I;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003781 if (!isCandidateViable(CCC, Prev->second))
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003782 DI->second->erase(Prev);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003783 continue;
Douglas Gregore24b5752010-10-14 20:34:08 +00003784 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003785
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003786 // Perform name lookup on this name.
3787 IdentifierInfo *Name = I->second.getCorrectionAsIdentifierInfo();
3788 LookupPotentialTypoResult(*this, TmpRes, Name, S, SS, MemberContext,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00003789 EnteringContext, CCC.IsObjCIvarLookup);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003790
3791 switch (TmpRes.getResultKind()) {
3792 case LookupResult::NotFound:
3793 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00003794 case LookupResult::FoundUnresolvedValue:
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003795 QualifiedResults.push_back(I->second);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003796 // We didn't find this name in our scope, or didn't like what we found;
3797 // ignore it.
3798 {
3799 TypoCorrectionConsumer::result_iterator Next = I;
3800 ++Next;
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003801 DI->second->erase(I);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003802 I = Next;
3803 }
3804 break;
3805
3806 case LookupResult::Ambiguous:
3807 // We don't deal with ambiguities.
3808 return TypoCorrection();
3809
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003810 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003811 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003812 // Store all of the Decls for overloaded symbols
3813 for (LookupResult::iterator TRD = TmpRes.begin(),
3814 TRDEnd = TmpRes.end();
3815 TRD != TRDEnd; ++TRD)
3816 I->second.addCorrectionDecl(*TRD);
3817 ++I;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003818 if (!isCandidateViable(CCC, Prev->second))
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003819 DI->second->erase(Prev);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003820 break;
3821 }
3822
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003823 case LookupResult::Found: {
3824 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003825 I->second.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
3826 ++I;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003827 if (!isCandidateViable(CCC, Prev->second))
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003828 DI->second->erase(Prev);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003829 break;
3830 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003831
3832 }
Douglas Gregore24b5752010-10-14 20:34:08 +00003833 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003834
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003835 if (DI->second->empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003836 Consumer.erase(DI);
3837 else if (!getLangOptions().CPlusPlus || QualifiedResults.empty() || !ED)
3838 // If there are results in the closest possible bucket, stop
3839 break;
3840
3841 // Only perform the qualified lookups for C++
3842 if (getLangOptions().CPlusPlus) {
3843 TmpRes.suppressDiagnostics();
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003844 for (llvm::SmallVector<TypoCorrection,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003845 16>::iterator QRI = QualifiedResults.begin(),
3846 QRIEnd = QualifiedResults.end();
3847 QRI != QRIEnd; ++QRI) {
3848 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
3849 NIEnd = Namespaces.end();
3850 NI != NIEnd; ++NI) {
3851 DeclContext *Ctx = NI->DeclCtx;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003852
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003853 // FIXME: Stop searching once the namespaces are too far away to create
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003854 // acceptable corrections for this identifier (since the namespaces
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003855 // are sorted in ascending order by edit distance).
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003856
3857 TmpRes.clear();
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003858 TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003859 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
3860
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003861 // Any corrections added below will be validated in subsequent
3862 // iterations of the main while() loop over the Consumer's contents.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003863 switch (TmpRes.getResultKind()) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003864 case LookupResult::Found: {
3865 TypoCorrection TC(*QRI);
3866 TC.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
3867 TC.setCorrectionSpecifier(NI->NameSpecifier);
3868 TC.setQualifierDistance(NI->EditDistance);
3869 Consumer.addCorrection(TC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003870 break;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003871 }
3872 case LookupResult::FoundOverloaded: {
3873 TypoCorrection TC(*QRI);
3874 TC.setCorrectionSpecifier(NI->NameSpecifier);
3875 TC.setQualifierDistance(NI->EditDistance);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003876 for (LookupResult::iterator TRD = TmpRes.begin(),
3877 TRDEnd = TmpRes.end();
3878 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003879 TC.addCorrectionDecl(*TRD);
3880 Consumer.addCorrection(TC);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003881 break;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003882 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003883 case LookupResult::NotFound:
3884 case LookupResult::NotFoundInCurrentInstantiation:
3885 case LookupResult::Ambiguous:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00003886 case LookupResult::FoundUnresolvedValue:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003887 break;
3888 }
3889 }
3890 }
3891 }
3892
3893 QualifiedResults.clear();
3894 }
3895
3896 // No corrections remain...
3897 if (Consumer.empty()) return TypoCorrection();
3898
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003899 TypoResultsMap &BestResults = *Consumer.begin()->second;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003900 ED = TypoCorrection::NormalizeEditDistance(Consumer.begin()->first);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003901
3902 if (ED > 0 && Typo->getName().size() / ED < 3) {
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003903 // If this was an unqualified lookup and we believe the callback
3904 // object wouldn't have filtered out possible corrections, note
3905 // that no correction was found.
3906 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003907 (void)UnqualifiedTyposCorrected[Typo];
3908
3909 return TypoCorrection();
3910 }
3911
Douglas Gregore24b5752010-10-14 20:34:08 +00003912 // If only a single name remains, return that result.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003913 if (BestResults.size() == 1) {
3914 const llvm::StringMapEntry<TypoCorrection> &Correction = *(BestResults.begin());
3915 const TypoCorrection &Result = Correction.second;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003916
Douglas Gregor53e4b552010-10-26 17:18:00 +00003917 // Don't correct to a keyword that's the same as the typo; the keyword
3918 // wasn't actually in scope.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003919 if (ED == 0 && Result.isKeyword()) return TypoCorrection();
3920
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003921 // Record the correction for unqualified lookup.
3922 if (IsUnqualifiedLookup)
3923 UnqualifiedTyposCorrected[Typo] = Result;
3924
3925 return Result;
3926 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003927 else if (BestResults.size() > 1
3928 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
3929 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
3930 // some instances of CTC_Unknown, while WantRemainingKeywords is true
3931 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00003932 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003933 && BestResults["super"].isKeyword()) {
3934 // Prefer 'super' when we're completing in a message-receiver
3935 // context.
3936
3937 // Don't correct to a keyword that's the same as the typo; the keyword
3938 // wasn't actually in scope.
3939 if (ED == 0) return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003940
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003941 // Record the correction for unqualified lookup.
3942 if (IsUnqualifiedLookup)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003943 UnqualifiedTyposCorrected[Typo] = BestResults["super"];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003944
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003945 return BestResults["super"];
Douglas Gregor7b824e82010-10-15 13:35:25 +00003946 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003947
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003948 // If this was an unqualified lookup and we believe the callback object did
3949 // not filter out possible corrections, note that no correction was found.
3950 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003951 (void)UnqualifiedTyposCorrected[Typo];
3952
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003953 return TypoCorrection();
3954}
3955
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003956void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
3957 if (!CDecl) return;
3958
3959 if (isKeyword())
3960 CorrectionDecls.clear();
3961
3962 CorrectionDecls.push_back(CDecl);
3963
3964 if (!CorrectionName)
3965 CorrectionName = CDecl->getDeclName();
3966}
3967
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003968std::string TypoCorrection::getAsString(const LangOptions &LO) const {
3969 if (CorrectionNameSpec) {
3970 std::string tmpBuffer;
3971 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
3972 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
3973 return PrefixOStream.str() + CorrectionName.getAsString();
3974 }
3975
3976 return CorrectionName.getAsString();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003977}