blob: d3a31ede670fd39f5d7ccff24ade8d219f65f851 [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"
John McCall50df6ae2010-08-25 07:03:20 +000034#include "llvm/ADT/DenseSet.h"
Douglas Gregora1f21142012-02-01 17:04:21 +000035#include "llvm/ADT/SetVector.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000036#include "llvm/ADT/STLExtras.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000037#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregore24b5752010-10-14 20:34:08 +000038#include "llvm/ADT/StringMap.h"
Chris Lattnerb5f65472011-07-18 01:54:02 +000039#include "llvm/ADT/TinyPtrVector.h"
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +000040#include "llvm/ADT/edit_distance.h"
John McCall6e247262009-10-10 05:48:19 +000041#include "llvm/Support/ErrorHandling.h"
Douglas Gregore24b5752010-10-14 20:34:08 +000042#include <limits>
Douglas Gregor546be3c2009-12-30 17:04:44 +000043#include <list>
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +000044#include <set>
Douglas Gregor2a3009a2009-02-03 19:21:40 +000045#include <vector>
46#include <iterator>
47#include <utility>
48#include <algorithm>
Douglas Gregord8bba9c2011-06-28 16:20:02 +000049#include <map>
Douglas Gregoreb11cd02009-01-14 22:20:51 +000050
51using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000052using namespace sema;
Douglas Gregoreb11cd02009-01-14 22:20:51 +000053
John McCalld7be78a2009-11-10 07:01:13 +000054namespace {
55 class UnqualUsingEntry {
56 const DeclContext *Nominated;
57 const DeclContext *CommonAncestor;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000058
John McCalld7be78a2009-11-10 07:01:13 +000059 public:
60 UnqualUsingEntry(const DeclContext *Nominated,
61 const DeclContext *CommonAncestor)
62 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
63 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000064
John McCalld7be78a2009-11-10 07:01:13 +000065 const DeclContext *getCommonAncestor() const {
66 return CommonAncestor;
67 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000068
John McCalld7be78a2009-11-10 07:01:13 +000069 const DeclContext *getNominatedNamespace() const {
70 return Nominated;
71 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000072
John McCalld7be78a2009-11-10 07:01:13 +000073 // Sort by the pointer value of the common ancestor.
74 struct Comparator {
75 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
76 return L.getCommonAncestor() < R.getCommonAncestor();
77 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000078
John McCalld7be78a2009-11-10 07:01:13 +000079 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
80 return E.getCommonAncestor() < DC;
81 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000082
John McCalld7be78a2009-11-10 07:01:13 +000083 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
84 return DC < E.getCommonAncestor();
85 }
86 };
87 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +000088
John McCalld7be78a2009-11-10 07:01:13 +000089 /// A collection of using directives, as used by C++ unqualified
90 /// lookup.
91 class UnqualUsingDirectiveSet {
Chris Lattner5f9e2722011-07-23 10:55:15 +000092 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000093
John McCalld7be78a2009-11-10 07:01:13 +000094 ListTy list;
95 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000096
John McCalld7be78a2009-11-10 07:01:13 +000097 public:
98 UnqualUsingDirectiveSet() {}
Douglas Gregor2a3009a2009-02-03 19:21:40 +000099
John McCalld7be78a2009-11-10 07:01:13 +0000100 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000101 // C++ [namespace.udir]p1:
John McCalld7be78a2009-11-10 07:01:13 +0000102 // During unqualified name lookup, the names appear as if they
103 // were declared in the nearest enclosing namespace which contains
104 // both the using-directive and the nominated namespace.
105 DeclContext *InnermostFileDC
106 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
107 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000108
John McCalld7be78a2009-11-10 07:01:13 +0000109 for (; S; S = S->getParent()) {
John McCalld7be78a2009-11-10 07:01:13 +0000110 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
111 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
112 visit(Ctx, EffectiveDC);
113 } else {
114 Scope::udir_iterator I = S->using_directives_begin(),
115 End = S->using_directives_end();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000116
John McCalld7be78a2009-11-10 07:01:13 +0000117 for (; I != End; ++I)
John McCalld226f652010-08-21 09:40:31 +0000118 visit(*I, InnermostFileDC);
John McCalld7be78a2009-11-10 07:01:13 +0000119 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000120 }
121 }
John McCalld7be78a2009-11-10 07:01:13 +0000122
123 // Visits a context and collect all of its using directives
124 // recursively. Treats all using directives as if they were
125 // declared in the context.
126 //
127 // A given context is only every visited once, so it is important
128 // that contexts be visited from the inside out in order to get
129 // the effective DCs right.
130 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
131 if (!visited.insert(DC))
132 return;
133
134 addUsingDirectives(DC, EffectiveDC);
135 }
136
137 // Visits a using directive and collects all of its using
138 // directives recursively. Treats all using directives as if they
139 // were declared in the effective DC.
140 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
141 DeclContext *NS = UD->getNominatedNamespace();
142 if (!visited.insert(NS))
143 return;
144
145 addUsingDirective(UD, EffectiveDC);
146 addUsingDirectives(NS, EffectiveDC);
147 }
148
149 // Adds all the using directives in a context (and those nominated
150 // by its using directives, transitively) as if they appeared in
151 // the given effective context.
152 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000153 SmallVector<DeclContext*,4> queue;
John McCalld7be78a2009-11-10 07:01:13 +0000154 while (true) {
155 DeclContext::udir_iterator I, End;
156 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
157 UsingDirectiveDecl *UD = *I;
158 DeclContext *NS = UD->getNominatedNamespace();
159 if (visited.insert(NS)) {
160 addUsingDirective(UD, EffectiveDC);
161 queue.push_back(NS);
162 }
163 }
164
165 if (queue.empty())
166 return;
167
168 DC = queue.back();
169 queue.pop_back();
170 }
171 }
172
173 // Add a using directive as if it had been declared in the given
174 // context. This helps implement C++ [namespace.udir]p3:
175 // The using-directive is transitive: if a scope contains a
176 // using-directive that nominates a second namespace that itself
177 // contains using-directives, the effect is as if the
178 // using-directives from the second namespace also appeared in
179 // the first.
180 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
181 // Find the common ancestor between the effective context and
182 // the nominated namespace.
183 DeclContext *Common = UD->getNominatedNamespace();
184 while (!Common->Encloses(EffectiveDC))
185 Common = Common->getParent();
John McCall12ea5782009-11-10 09:20:04 +0000186 Common = Common->getPrimaryContext();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000187
John McCalld7be78a2009-11-10 07:01:13 +0000188 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
189 }
190
191 void done() {
192 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
193 }
194
John McCalld7be78a2009-11-10 07:01:13 +0000195 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000196
John McCalld7be78a2009-11-10 07:01:13 +0000197 const_iterator begin() const { return list.begin(); }
198 const_iterator end() const { return list.end(); }
199
200 std::pair<const_iterator,const_iterator>
201 getNamespacesFor(DeclContext *DC) const {
John McCall12ea5782009-11-10 09:20:04 +0000202 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCalld7be78a2009-11-10 07:01:13 +0000203 UnqualUsingEntry::Comparator());
204 }
205 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000206}
207
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000208// Retrieve the set of identifier namespaces that correspond to a
209// specific kind of name lookup.
John McCall1d7c5282009-12-18 10:40:03 +0000210static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
211 bool CPlusPlus,
212 bool Redeclaration) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000213 unsigned IDNS = 0;
214 switch (NameKind) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +0000215 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000216 case Sema::LookupOrdinaryName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000217 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000218 IDNS = Decl::IDNS_Ordinary;
John McCall1d7c5282009-12-18 10:40:03 +0000219 if (CPlusPlus) {
John McCall0d6b1642010-04-23 18:46:30 +0000220 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattner337e5502011-02-18 01:27:55 +0000221 if (Redeclaration)
222 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCall1d7c5282009-12-18 10:40:03 +0000223 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000224 break;
225
John McCall76d32642010-04-24 01:30:58 +0000226 case Sema::LookupOperatorName:
227 // Operator lookup is its own crazy thing; it is not the same
228 // as (e.g.) looking up an operator name for redeclaration.
229 assert(!Redeclaration && "cannot do redeclaration operator lookup");
230 IDNS = Decl::IDNS_NonMemberOperator;
231 break;
232
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000233 case Sema::LookupTagName:
John McCall0d6b1642010-04-23 18:46:30 +0000234 if (CPlusPlus) {
235 IDNS = Decl::IDNS_Type;
236
237 // When looking for a redeclaration of a tag name, we add:
238 // 1) TagFriend to find undeclared friend decls
239 // 2) Namespace because they can't "overload" with tag decls.
240 // 3) Tag because it includes class templates, which can't
241 // "overload" with tag decls.
242 if (Redeclaration)
243 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
244 } else {
245 IDNS = Decl::IDNS_Tag;
246 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000247 break;
Chris Lattner337e5502011-02-18 01:27:55 +0000248 case Sema::LookupLabel:
249 IDNS = Decl::IDNS_Label;
250 break;
251
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000252 case Sema::LookupMemberName:
253 IDNS = Decl::IDNS_Member;
254 if (CPlusPlus)
Mike Stump1eb44332009-09-09 15:08:12 +0000255 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000256 break;
257
258 case Sema::LookupNestedNameSpecifierName:
John McCall0d6b1642010-04-23 18:46:30 +0000259 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
260 break;
261
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000262 case Sema::LookupNamespaceName:
John McCall0d6b1642010-04-23 18:46:30 +0000263 IDNS = Decl::IDNS_Namespace;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000264 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000265
John McCall9f54ad42009-12-10 09:41:52 +0000266 case Sema::LookupUsingDeclName:
267 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
268 | Decl::IDNS_Member | Decl::IDNS_Using;
269 break;
270
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000271 case Sema::LookupObjCProtocolName:
272 IDNS = Decl::IDNS_ObjCProtocol;
273 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000274
Douglas Gregor8071e422010-08-15 06:18:01 +0000275 case Sema::LookupAnyName:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000276 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor8071e422010-08-15 06:18:01 +0000277 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
278 | Decl::IDNS_Type;
279 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000280 }
281 return IDNS;
282}
283
John McCall1d7c5282009-12-18 10:40:03 +0000284void LookupResult::configure() {
Chris Lattner337e5502011-02-18 01:27:55 +0000285 IDNS = getIDNS(LookupKind, SemaRef.getLangOptions().CPlusPlus,
John McCall1d7c5282009-12-18 10:40:03 +0000286 isForRedeclaration());
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000287
288 // If we're looking for one of the allocation or deallocation
289 // operators, make sure that the implicitly-declared new and delete
290 // operators can be found.
291 if (!isForRedeclaration()) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000292 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000293 case OO_New:
294 case OO_Delete:
295 case OO_Array_New:
296 case OO_Array_Delete:
297 SemaRef.DeclareGlobalNewDelete();
298 break;
299
300 default:
301 break;
302 }
303 }
John McCall1d7c5282009-12-18 10:40:03 +0000304}
305
John McCall2a7fb272010-08-25 05:32:35 +0000306void LookupResult::sanity() const {
307 assert(ResultKind != NotFound || Decls.size() == 0);
308 assert(ResultKind != Found || Decls.size() == 1);
309 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
310 (Decls.size() == 1 &&
311 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
312 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
313 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorf17b58c2010-10-22 22:08:47 +0000314 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
315 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall2a7fb272010-08-25 05:32:35 +0000316 assert((Paths != NULL) == (ResultKind == Ambiguous &&
317 (Ambiguity == AmbiguousBaseSubobjectTypes ||
318 Ambiguity == AmbiguousBaseSubobjects)));
319}
John McCall2a7fb272010-08-25 05:32:35 +0000320
John McCallf36e02d2009-10-09 21:13:30 +0000321// Necessary because CXXBasePaths is not complete in Sema.h
John McCall7d384dd2009-11-18 07:57:50 +0000322void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCallf36e02d2009-10-09 21:13:30 +0000323 delete Paths;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000324}
325
Douglas Gregor55368912011-12-14 16:03:29 +0000326static NamedDecl *getVisibleDecl(NamedDecl *D);
327
328NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
329 return getVisibleDecl(D);
330}
331
John McCall7453ed42009-11-22 00:44:51 +0000332/// Resolves the result kind of this lookup.
John McCall7d384dd2009-11-18 07:57:50 +0000333void LookupResult::resolveKind() {
John McCallf36e02d2009-10-09 21:13:30 +0000334 unsigned N = Decls.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000335
John McCallf36e02d2009-10-09 21:13:30 +0000336 // Fast case: no possible ambiguity.
John McCall68263142009-11-18 22:49:29 +0000337 if (N == 0) {
John McCalldc5c7862010-01-15 21:27:01 +0000338 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall68263142009-11-18 22:49:29 +0000339 return;
340 }
341
John McCall7453ed42009-11-22 00:44:51 +0000342 // If there's a single decl, we need to examine it to decide what
343 // kind of lookup this is.
John McCall7ba107a2009-11-18 02:36:19 +0000344 if (N == 1) {
Douglas Gregor2b147f02010-04-25 21:15:30 +0000345 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
346 if (isa<FunctionTemplateDecl>(D))
John McCall7453ed42009-11-22 00:44:51 +0000347 ResultKind = FoundOverloaded;
Douglas Gregor2b147f02010-04-25 21:15:30 +0000348 else if (isa<UnresolvedUsingValueDecl>(D))
John McCall7ba107a2009-11-18 02:36:19 +0000349 ResultKind = FoundUnresolvedValue;
350 return;
351 }
John McCallf36e02d2009-10-09 21:13:30 +0000352
John McCall6e247262009-10-10 05:48:19 +0000353 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000354 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000355
John McCallf36e02d2009-10-09 21:13:30 +0000356 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000357 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000358
John McCallf36e02d2009-10-09 21:13:30 +0000359 bool Ambiguous = false;
360 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000361 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000362
363 unsigned UniqueTagIndex = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000364
John McCallf36e02d2009-10-09 21:13:30 +0000365 unsigned I = 0;
366 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000367 NamedDecl *D = Decls[I]->getUnderlyingDecl();
368 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000369
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000370 // Redeclarations of types via typedef can occur both within a scope
371 // and, through using declarations and directives, across scopes. There is
372 // no ambiguity if they all refer to the same type, so unique based on the
373 // canonical type.
374 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
375 if (!TD->getDeclContext()->isRecord()) {
376 QualType T = SemaRef.Context.getTypeDeclType(TD);
377 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
378 // The type is not unique; pull something off the back and continue
379 // at this index.
380 Decls[I] = Decls[--N];
381 continue;
382 }
383 }
384 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000385
John McCall314be4e2009-11-17 07:50:12 +0000386 if (!Unique.insert(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000387 // If it's not unique, pull something off the back (and
388 // continue at this index).
389 Decls[I] = Decls[--N];
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000390 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000391 }
392
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000393 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000394
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000395 if (isa<UnresolvedUsingValueDecl>(D)) {
396 HasUnresolved = true;
397 } else if (isa<TagDecl>(D)) {
398 if (HasTag)
399 Ambiguous = true;
400 UniqueTagIndex = I;
401 HasTag = true;
402 } else if (isa<FunctionTemplateDecl>(D)) {
403 HasFunction = true;
404 HasFunctionTemplate = true;
405 } else if (isa<FunctionDecl>(D)) {
406 HasFunction = true;
407 } else {
408 if (HasNonFunction)
409 Ambiguous = true;
410 HasNonFunction = true;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000411 }
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000412 I++;
Mike Stump1eb44332009-09-09 15:08:12 +0000413 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000414
John McCallf36e02d2009-10-09 21:13:30 +0000415 // C++ [basic.scope.hiding]p2:
416 // A class name or enumeration name can be hidden by the name of
417 // an object, function, or enumerator declared in the same
418 // scope. If a class or enumeration name and an object, function,
419 // or enumerator are declared in the same scope (in any order)
420 // with the same name, the class or enumeration name is hidden
421 // wherever the object, function, or enumerator name is visible.
422 // But it's still an error if there are distinct tag types found,
423 // even if they're not visible. (ref?)
John McCallfda8e122009-12-03 00:58:24 +0000424 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregor77a1a882010-10-23 16:06:17 +0000425 (HasFunction || HasNonFunction || HasUnresolved)) {
426 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
427 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
428 Decls[UniqueTagIndex] = Decls[--N];
429 else
430 Ambiguous = true;
431 }
Anders Carlsson8b50d012009-06-26 03:37:05 +0000432
John McCallf36e02d2009-10-09 21:13:30 +0000433 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000434
John McCallfda8e122009-12-03 00:58:24 +0000435 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000436 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000437
John McCallf36e02d2009-10-09 21:13:30 +0000438 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000439 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000440 else if (HasUnresolved)
441 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000442 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000443 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000444 else
John McCalla24dc2e2009-11-17 02:14:36 +0000445 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000446}
447
John McCall7d384dd2009-11-18 07:57:50 +0000448void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall6b2accb2010-02-10 09:31:12 +0000449 CXXBasePaths::const_paths_iterator I, E;
John McCallf36e02d2009-10-09 21:13:30 +0000450 DeclContext::lookup_iterator DI, DE;
451 for (I = P.begin(), E = P.end(); I != E; ++I)
452 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
453 addDecl(*DI);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000454}
455
John McCall7d384dd2009-11-18 07:57:50 +0000456void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000457 Paths = new CXXBasePaths;
458 Paths->swap(P);
459 addDeclsFromBasePaths(*Paths);
460 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000461 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000462}
463
John McCall7d384dd2009-11-18 07:57:50 +0000464void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000465 Paths = new CXXBasePaths;
466 Paths->swap(P);
467 addDeclsFromBasePaths(*Paths);
468 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000469 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000470}
471
Chris Lattner5f9e2722011-07-23 10:55:15 +0000472void LookupResult::print(raw_ostream &Out) {
John McCallf36e02d2009-10-09 21:13:30 +0000473 Out << Decls.size() << " result(s)";
474 if (isAmbiguous()) Out << ", ambiguous";
475 if (Paths) Out << ", base paths present";
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000476
John McCallf36e02d2009-10-09 21:13:30 +0000477 for (iterator I = begin(), E = end(); I != E; ++I) {
478 Out << "\n";
479 (*I)->print(Out, 2);
480 }
481}
482
Douglas Gregor85910982010-02-12 05:48:04 +0000483/// \brief Lookup a builtin function, when name lookup would otherwise
484/// fail.
485static bool LookupBuiltin(Sema &S, LookupResult &R) {
486 Sema::LookupNameKind NameKind = R.getLookupKind();
487
488 // If we didn't find a use of this identifier, and if the identifier
489 // corresponds to a compiler builtin, create the decl object for the builtin
490 // now, injecting it into translation unit scope, and return it.
491 if (NameKind == Sema::LookupOrdinaryName ||
492 NameKind == Sema::LookupRedeclarationWithLinkage) {
493 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
494 if (II) {
495 // If this is a builtin on this (or all) targets, create the decl.
496 if (unsigned BuiltinID = II->getBuiltinID()) {
497 // In C++, we don't have any predefined library functions like
498 // 'malloc'. Instead, we'll just error.
499 if (S.getLangOptions().CPlusPlus &&
500 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
501 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000502
503 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
504 BuiltinID, S.TUScope,
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000505 R.isForRedeclaration(),
506 R.getNameLoc())) {
Douglas Gregor85910982010-02-12 05:48:04 +0000507 R.addDecl(D);
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000508 return true;
509 }
510
511 if (R.isForRedeclaration()) {
512 // If we're redeclaring this function anyway, forget that
513 // this was a builtin at all.
514 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
515 }
516
517 return false;
Douglas Gregor85910982010-02-12 05:48:04 +0000518 }
519 }
520 }
521
522 return false;
523}
524
Douglas Gregor4923aa22010-07-02 20:37:36 +0000525/// \brief Determine whether we can declare a special member function within
526/// the class at this point.
527static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
528 const CXXRecordDecl *Class) {
John McCallb3b50a82010-08-11 23:52:36 +0000529 // Don't do it if the class is invalid.
530 if (Class->isInvalidDecl())
531 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000532
Douglas Gregor4923aa22010-07-02 20:37:36 +0000533 // We need to have a definition for the class.
534 if (!Class->getDefinition() || Class->isDependentContext())
535 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000536
Douglas Gregor4923aa22010-07-02 20:37:36 +0000537 // We can't be in the middle of defining the class.
538 if (const RecordType *RecordTy
539 = Context.getTypeDeclType(Class)->getAs<RecordType>())
540 return !RecordTy->isBeingDefined();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000541
Douglas Gregor4923aa22010-07-02 20:37:36 +0000542 return false;
543}
544
545void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregor22584312010-07-02 23:41:54 +0000546 if (!CanDeclareSpecialMemberFunction(Context, Class))
547 return;
Douglas Gregor18274032010-07-03 00:47:00 +0000548
549 // If the default constructor has not yet been declared, do so now.
Sean Huntcdee3fe2011-05-11 22:34:38 +0000550 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +0000551 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000552
Douglas Gregor22584312010-07-02 23:41:54 +0000553 // If the copy constructor has not yet been declared, do so now.
554 if (!Class->hasDeclaredCopyConstructor())
555 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000556
Douglas Gregora376d102010-07-02 21:50:04 +0000557 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000558 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +0000559 DeclareImplicitCopyAssignment(Class);
560
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000561 if (getLangOptions().CPlusPlus0x) {
562 // If the move constructor has not yet been declared, do so now.
563 if (Class->needsImplicitMoveConstructor())
564 DeclareImplicitMoveConstructor(Class); // might not actually do it
565
566 // If the move assignment operator has not yet been declared, do so now.
567 if (Class->needsImplicitMoveAssignment())
568 DeclareImplicitMoveAssignment(Class); // might not actually do it
569 }
570
Douglas Gregor4923aa22010-07-02 20:37:36 +0000571 // If the destructor has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000572 if (!Class->hasDeclaredDestructor())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000573 DeclareImplicitDestructor(Class);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000574}
575
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000576/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregora376d102010-07-02 21:50:04 +0000577/// special member function.
578static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
579 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000580 case DeclarationName::CXXConstructorName:
Douglas Gregora376d102010-07-02 21:50:04 +0000581 case DeclarationName::CXXDestructorName:
582 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000583
Douglas Gregora376d102010-07-02 21:50:04 +0000584 case DeclarationName::CXXOperatorName:
585 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000586
Douglas Gregora376d102010-07-02 21:50:04 +0000587 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000588 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000589 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000590
Douglas Gregora376d102010-07-02 21:50:04 +0000591 return false;
592}
593
594/// \brief If there are any implicit member functions with the given name
595/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000596static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregora376d102010-07-02 21:50:04 +0000597 DeclarationName Name,
598 const DeclContext *DC) {
599 if (!DC)
600 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000601
Douglas Gregora376d102010-07-02 21:50:04 +0000602 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000603 case DeclarationName::CXXConstructorName:
604 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor18274032010-07-03 00:47:00 +0000605 if (Record->getDefinition() &&
606 CanDeclareSpecialMemberFunction(S.Context, Record)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000607 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Sean Huntcdee3fe2011-05-11 22:34:38 +0000608 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000609 S.DeclareImplicitDefaultConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +0000610 if (!Record->hasDeclaredCopyConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000611 S.DeclareImplicitCopyConstructor(Class);
612 if (S.getLangOptions().CPlusPlus0x &&
613 Record->needsImplicitMoveConstructor())
614 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +0000615 }
Douglas Gregor22584312010-07-02 23:41:54 +0000616 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000617
Douglas Gregora376d102010-07-02 21:50:04 +0000618 case DeclarationName::CXXDestructorName:
619 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
620 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
621 CanDeclareSpecialMemberFunction(S.Context, Record))
622 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregora376d102010-07-02 21:50:04 +0000623 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000624
Douglas Gregora376d102010-07-02 21:50:04 +0000625 case DeclarationName::CXXOperatorName:
626 if (Name.getCXXOverloadedOperator() != OO_Equal)
627 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000628
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000629 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
630 if (Record->getDefinition() &&
631 CanDeclareSpecialMemberFunction(S.Context, Record)) {
632 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
633 if (!Record->hasDeclaredCopyAssignment())
634 S.DeclareImplicitCopyAssignment(Class);
635 if (S.getLangOptions().CPlusPlus0x &&
636 Record->needsImplicitMoveAssignment())
637 S.DeclareImplicitMoveAssignment(Class);
638 }
639 }
Douglas Gregora376d102010-07-02 21:50:04 +0000640 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000641
Douglas Gregora376d102010-07-02 21:50:04 +0000642 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000643 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000644 }
645}
Douglas Gregor4923aa22010-07-02 20:37:36 +0000646
John McCallf36e02d2009-10-09 21:13:30 +0000647// Adds all qualifying matches for a name within a decl context to the
648// given lookup result. Returns true if any matches were found.
Douglas Gregor85910982010-02-12 05:48:04 +0000649static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000650 bool Found = false;
651
Douglas Gregor4923aa22010-07-02 20:37:36 +0000652 // Lazily declare C++ special member functions.
Douglas Gregora376d102010-07-02 21:50:04 +0000653 if (S.getLangOptions().CPlusPlus)
654 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000655
Douglas Gregor4923aa22010-07-02 20:37:36 +0000656 // Perform lookup into this declaration context.
John McCalld7be78a2009-11-10 07:01:13 +0000657 DeclContext::lookup_const_iterator I, E;
Douglas Gregor48026d22010-01-11 18:40:55 +0000658 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall46460a62010-01-20 21:53:11 +0000659 NamedDecl *D = *I;
Douglas Gregor55368912011-12-14 16:03:29 +0000660 if ((D = R.getAcceptableDecl(D))) {
John McCall46460a62010-01-20 21:53:11 +0000661 R.addDecl(D);
Douglas Gregor48026d22010-01-11 18:40:55 +0000662 Found = true;
663 }
664 }
John McCallf36e02d2009-10-09 21:13:30 +0000665
Douglas Gregor85910982010-02-12 05:48:04 +0000666 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
667 return true;
668
Douglas Gregor48026d22010-01-11 18:40:55 +0000669 if (R.getLookupName().getNameKind()
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000670 != DeclarationName::CXXConversionFunctionName ||
671 R.getLookupName().getCXXNameType()->isDependentType() ||
672 !isa<CXXRecordDecl>(DC))
673 return Found;
674
675 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000676 // A specialization of a conversion function template is not found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000677 // name lookup. Instead, any conversion function templates visible in the
678 // context of the use are considered. [...]
679 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCall5e1cdac2011-10-07 06:10:15 +0000680 if (!Record->isCompleteDefinition())
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000681 return Found;
682
683 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000684 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000685 UEnd = Unresolved->end(); U != UEnd; ++U) {
686 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
687 if (!ConvTemplate)
688 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000689
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000690 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000691 // add the conversion function template. When we deduce template
692 // arguments for specializations, we'll end up unifying the return
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000693 // type of the new declaration with the type of the function template.
694 if (R.isForRedeclaration()) {
695 R.addDecl(ConvTemplate);
696 Found = true;
697 continue;
698 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000699
Douglas Gregor48026d22010-01-11 18:40:55 +0000700 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000701 // [...] For each such operator, if argument deduction succeeds
702 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000703 // name lookup.
704 //
705 // When referencing a conversion function for any purpose other than
706 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000707 // result), perform template argument deduction and place the
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000708 // specialization into the result set. We do this to avoid forcing all
709 // callers to perform special deduction for conversion functions.
John McCall2a7fb272010-08-25 05:32:35 +0000710 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000711 FunctionDecl *Specialization = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000712
713 const FunctionProtoType *ConvProto
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000714 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
715 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3f477a12010-01-12 01:17:50 +0000716
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000717 // Compute the type of the function that we would expect the conversion
718 // function to have, if it were to match the name given.
719 // FIXME: Calling convention!
John McCalle23cf432010-12-14 08:05:40 +0000720 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
721 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
Sebastian Redl8b5b4092011-03-06 10:52:04 +0000722 EPI.ExceptionSpecType = EST_None;
John McCalle23cf432010-12-14 08:05:40 +0000723 EPI.NumExceptions = 0;
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000724 QualType ExpectedType
725 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
John McCalle23cf432010-12-14 08:05:40 +0000726 0, 0, EPI);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000727
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000728 // Perform template argument deduction against the type that we would
729 // expect the function to have.
730 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
731 Specialization, Info)
732 == Sema::TDK_Success) {
733 R.addDecl(Specialization);
734 Found = true;
Douglas Gregor48026d22010-01-11 18:40:55 +0000735 }
736 }
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000737
John McCallf36e02d2009-10-09 21:13:30 +0000738 return Found;
739}
740
John McCalld7be78a2009-11-10 07:01:13 +0000741// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000742static bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000743CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregor85910982010-02-12 05:48:04 +0000744 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000745
746 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
747
John McCalld7be78a2009-11-10 07:01:13 +0000748 // Perform direct name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +0000749 bool Found = LookupDirect(S, R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000750
John McCalld7be78a2009-11-10 07:01:13 +0000751 // Perform direct name lookup into the namespaces nominated by the
752 // using directives whose common ancestor is this namespace.
753 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
754 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000755
John McCalld7be78a2009-11-10 07:01:13 +0000756 for (; UI != UEnd; ++UI)
Douglas Gregor85910982010-02-12 05:48:04 +0000757 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000758 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000759
760 R.resolveKind();
761
762 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000763}
764
765static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000766 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000767 return Ctx->isFileContext();
768 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000769}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000770
Douglas Gregor711be1e2010-03-15 14:33:29 +0000771// Find the next outer declaration context from this scope. This
772// routine actually returns the semantic outer context, which may
773// differ from the lexical context (encoded directly in the Scope
774// stack) when we are parsing a member of a class template. In this
775// case, the second element of the pair will be true, to indicate that
776// name lookup should continue searching in this semantic context when
777// it leaves the current template parameter scope.
778static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
779 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
780 DeclContext *Lexical = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000781 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor711be1e2010-03-15 14:33:29 +0000782 OuterS = OuterS->getParent()) {
783 if (OuterS->getEntity()) {
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000784 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor711be1e2010-03-15 14:33:29 +0000785 break;
786 }
787 }
788
789 // C++ [temp.local]p8:
790 // In the definition of a member of a class template that appears
791 // outside of the namespace containing the class template
792 // definition, the name of a template-parameter hides the name of
793 // a member of this namespace.
794 //
795 // Example:
796 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000797 // namespace N {
798 // class C { };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000799 //
800 // template<class T> class B {
801 // void f(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000802 // };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000803 // }
804 //
805 // template<class C> void N::B<C>::f(C) {
806 // C b; // C is the template parameter, not N::C
807 // }
808 //
809 // In this example, the lexical context we return is the
810 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000811 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor711be1e2010-03-15 14:33:29 +0000812 !S->getParent()->isTemplateParamScope())
813 return std::make_pair(Lexical, false);
814
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000815 // Find the outermost template parameter scope.
Douglas Gregor711be1e2010-03-15 14:33:29 +0000816 // For the example, this is the scope for the template parameters of
817 // template<class C>.
818 Scope *OutermostTemplateScope = S->getParent();
819 while (OutermostTemplateScope->getParent() &&
820 OutermostTemplateScope->getParent()->isTemplateParamScope())
821 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000822
Douglas Gregor711be1e2010-03-15 14:33:29 +0000823 // Find the namespace context in which the original scope occurs. In
824 // the example, this is namespace N.
825 DeclContext *Semantic = DC;
826 while (!Semantic->isFileContext())
827 Semantic = Semantic->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000828
Douglas Gregor711be1e2010-03-15 14:33:29 +0000829 // Find the declaration context just outside of the template
830 // parameter scope. This is the context in which the template is
831 // being lexically declaration (a namespace context). In the
832 // example, this is the global scope.
833 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
834 Lexical->Encloses(Semantic))
835 return std::make_pair(Semantic, true);
836
837 return std::make_pair(Lexical, false);
Douglas Gregore942bbe2009-09-10 16:57:35 +0000838}
839
John McCalla24dc2e2009-11-17 02:14:36 +0000840bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCall1d7c5282009-12-18 10:40:03 +0000841 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000842
843 DeclarationName Name = R.getLookupName();
844
Douglas Gregora376d102010-07-02 21:50:04 +0000845 // If this is the name of an implicitly-declared special member function,
846 // go through the scope stack to implicitly declare
847 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
848 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
849 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
850 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
851 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000852
Douglas Gregora376d102010-07-02 21:50:04 +0000853 // Implicitly declare member functions with the name we're looking for, if in
854 // fact we are in a scope where it matters.
855
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000856 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000857 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000858 I = IdResolver.begin(Name),
859 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000860
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000861 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000862 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000863 // ...During unqualified name lookup (3.4.1), the names appear as if
864 // they were declared in the nearest enclosing namespace which contains
865 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000866 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000867 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000868 //
869 // For example:
870 // namespace A { int i; }
871 // void foo() {
872 // int i;
873 // {
874 // using namespace A;
875 // ++i; // finds local 'i', A::i appears at global scope
876 // }
877 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000878 //
Douglas Gregor711be1e2010-03-15 14:33:29 +0000879 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000880 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregord2235f62010-05-20 20:58:56 +0000881 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
882
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000883 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000884 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000885 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor55368912011-12-14 16:03:29 +0000886 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
John McCallf36e02d2009-10-09 21:13:30 +0000887 Found = true;
Douglas Gregor55368912011-12-14 16:03:29 +0000888 R.addDecl(ND);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000889 }
890 }
John McCallf36e02d2009-10-09 21:13:30 +0000891 if (Found) {
892 R.resolveKind();
Douglas Gregord2235f62010-05-20 20:58:56 +0000893 if (S->isClassScope())
894 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
895 R.setNamingClass(Record);
John McCallf36e02d2009-10-09 21:13:30 +0000896 return true;
897 }
898
Douglas Gregor711be1e2010-03-15 14:33:29 +0000899 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
900 S->getParent() && !S->getParent()->isTemplateParamScope()) {
901 // We've just searched the last template parameter scope and
902 // found nothing, so look into the the contexts between the
903 // lexical and semantic declaration contexts returned by
904 // findOuterContext(). This implements the name lookup behavior
905 // of C++ [temp.local]p8.
906 Ctx = OutsideOfTemplateParamDC;
907 OutsideOfTemplateParamDC = 0;
908 }
909
910 if (Ctx) {
911 DeclContext *OuterCtx;
912 bool SearchAfterTemplateScope;
913 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
914 if (SearchAfterTemplateScope)
915 OutsideOfTemplateParamDC = OuterCtx;
916
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000917 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-02-19 16:08:35 +0000918 // We do not directly look into transparent contexts, since
919 // those entities will be found in the nearest enclosing
920 // non-transparent context.
921 if (Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000922 continue;
Douglas Gregor36262b82010-02-19 16:08:35 +0000923
924 // We do not look directly into function or method contexts,
925 // since all of the local variables and parameters of the
926 // function/method are present within the Scope.
927 if (Ctx->isFunctionOrMethod()) {
928 // If we have an Objective-C instance method, look for ivars
929 // in the corresponding interface.
930 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
931 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
932 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
933 ObjCInterfaceDecl *ClassDeclared;
934 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000935 Name.getAsIdentifierInfo(),
Douglas Gregor36262b82010-02-19 16:08:35 +0000936 ClassDeclared)) {
Douglas Gregor55368912011-12-14 16:03:29 +0000937 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
938 R.addDecl(ND);
Douglas Gregor36262b82010-02-19 16:08:35 +0000939 R.resolveKind();
940 return true;
941 }
942 }
943 }
944 }
945
946 continue;
947 }
948
Douglas Gregore942bbe2009-09-10 16:57:35 +0000949 // Perform qualified name lookup into this context.
950 // FIXME: In some cases, we know that every name that could be found by
951 // this qualified name lookup will also be on the identifier chain. For
952 // example, inside a class without any base classes, we never need to
953 // perform qualified lookup because all of the members are on top of the
954 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000955 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +0000956 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +0000957 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000958 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000959 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000960
John McCalld7be78a2009-11-10 07:01:13 +0000961 // Stop if we ran out of scopes.
962 // FIXME: This really, really shouldn't be happening.
963 if (!S) return false;
964
Argyrios Kyrtzidis78f59112010-10-29 16:12:50 +0000965 // If we are looking for members, no need to look into global/namespace scope.
966 if (R.getLookupKind() == LookupMemberName)
967 return false;
968
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000969 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000970 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +0000971 //
Mike Stump390b4cc2009-05-16 07:39:55 +0000972 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
973 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000974
John McCalld7be78a2009-11-10 07:01:13 +0000975 UnqualUsingDirectiveSet UDirs;
976 UDirs.visitScopeChain(Initial, S);
977 UDirs.done();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000978
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000979 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000980 // Unqualified name lookup in C++ requires looking into scopes
981 // that aren't strictly lexical, and therefore we walk through the
982 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000983
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000984 for (; S; S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000985 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000986 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000987 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor55368912011-12-14 16:03:29 +0000988 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000989 // We found something. Look for anything else in our scope
990 // with this same name and in an acceptable identifier
991 // namespace, so that we can construct an overload set if we
992 // need to.
John McCallf36e02d2009-10-09 21:13:30 +0000993 Found = true;
Douglas Gregor55368912011-12-14 16:03:29 +0000994 R.addDecl(ND);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000995 }
996 }
997
Douglas Gregor00b4b032010-05-14 04:53:42 +0000998 if (Found && S->isTemplateParamScope()) {
John McCallf36e02d2009-10-09 21:13:30 +0000999 R.resolveKind();
1000 return true;
1001 }
1002
Douglas Gregor00b4b032010-05-14 04:53:42 +00001003 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1004 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1005 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1006 // We've just searched the last template parameter scope and
1007 // found nothing, so look into the the contexts between the
1008 // lexical and semantic declaration contexts returned by
1009 // findOuterContext(). This implements the name lookup behavior
1010 // of C++ [temp.local]p8.
1011 Ctx = OutsideOfTemplateParamDC;
1012 OutsideOfTemplateParamDC = 0;
1013 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001014
Douglas Gregor00b4b032010-05-14 04:53:42 +00001015 if (Ctx) {
1016 DeclContext *OuterCtx;
1017 bool SearchAfterTemplateScope;
1018 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1019 if (SearchAfterTemplateScope)
1020 OutsideOfTemplateParamDC = OuterCtx;
1021
1022 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1023 // We do not directly look into transparent contexts, since
1024 // those entities will be found in the nearest enclosing
1025 // non-transparent context.
1026 if (Ctx->isTransparentContext())
1027 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001028
Douglas Gregor00b4b032010-05-14 04:53:42 +00001029 // If we have a context, and it's not a context stashed in the
1030 // template parameter scope for an out-of-line definition, also
1031 // look into that context.
1032 if (!(Found && S && S->isTemplateParamScope())) {
1033 assert(Ctx->isFileContext() &&
1034 "We should have been looking only at file context here already.");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001035
Douglas Gregor00b4b032010-05-14 04:53:42 +00001036 // Look into context considering using-directives.
1037 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1038 Found = true;
1039 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001040
Douglas Gregor00b4b032010-05-14 04:53:42 +00001041 if (Found) {
1042 R.resolveKind();
1043 return true;
1044 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001045
Douglas Gregor00b4b032010-05-14 04:53:42 +00001046 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1047 return false;
1048 }
1049 }
1050
Douglas Gregor1df0ee92010-02-05 07:07:10 +00001051 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +00001052 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001053 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001054
John McCallf36e02d2009-10-09 21:13:30 +00001055 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001056}
1057
Douglas Gregor55368912011-12-14 16:03:29 +00001058/// \brief Retrieve the visible declaration corresponding to D, if any.
1059///
1060/// This routine determines whether the declaration D is visible in the current
1061/// module, with the current imports. If not, it checks whether any
1062/// redeclaration of D is visible, and if so, returns that declaration.
1063///
1064/// \returns D, or a visible previous declaration of D, whichever is more recent
1065/// and visible. If no declaration of D is visible, returns null.
1066static NamedDecl *getVisibleDecl(NamedDecl *D) {
1067 if (LookupResult::isVisible(D))
1068 return D;
1069
Douglas Gregor0782ef22012-01-06 22:05:37 +00001070 for (Decl::redecl_iterator RD = D->redecls_begin(), RDEnd = D->redecls_end();
1071 RD != RDEnd; ++RD) {
1072 if (NamedDecl *ND = dyn_cast<NamedDecl>(*RD)) {
1073 if (LookupResult::isVisible(ND))
1074 return ND;
1075 }
Douglas Gregor55368912011-12-14 16:03:29 +00001076 }
1077
1078 return 0;
1079}
1080
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001081/// @brief Perform unqualified name lookup starting from a given
1082/// scope.
1083///
1084/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1085/// used to find names within the current scope. For example, 'x' in
1086/// @code
1087/// int x;
1088/// int f() {
1089/// return x; // unqualified name look finds 'x' in the global scope
1090/// }
1091/// @endcode
1092///
1093/// Different lookup criteria can find different names. For example, a
1094/// particular scope can have both a struct and a function of the same
1095/// name, and each can be found by certain lookup criteria. For more
1096/// information about lookup criteria, see the documentation for the
1097/// class LookupCriteria.
1098///
1099/// @param S The scope from which unqualified name lookup will
1100/// begin. If the lookup criteria permits, name lookup may also search
1101/// in the parent scopes.
1102///
1103/// @param Name The name of the entity that we are searching for.
1104///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001105/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001106/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001107/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001108///
1109/// @returns The result of name lookup, which includes zero or more
1110/// declarations and possibly additional information used to diagnose
1111/// ambiguities.
John McCalla24dc2e2009-11-17 02:14:36 +00001112bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1113 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +00001114 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001115
John McCalla24dc2e2009-11-17 02:14:36 +00001116 LookupNameKind NameKind = R.getLookupKind();
1117
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001118 if (!getLangOptions().CPlusPlus) {
1119 // Unqualified name lookup in C/Objective-C is purely lexical, so
1120 // search in the declarations attached to the name.
John McCall1d7c5282009-12-18 10:40:03 +00001121 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001122 // Find the nearest non-transparent declaration scope.
1123 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001124 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001125 static_cast<DeclContext *>(S->getEntity())
1126 ->isTransparentContext()))
1127 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001128 }
1129
John McCall1d7c5282009-12-18 10:40:03 +00001130 unsigned IDNS = R.getIdentifierNamespace();
1131
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001132 // Scan up the scope chain looking for a decl that matches this
1133 // identifier that is in the appropriate namespace. This search
1134 // should not take long, as shadowing of names is uncommon, and
1135 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001136 bool LeftStartingScope = false;
1137
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001138 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +00001139 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001140 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001141 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001142 if (NameKind == LookupRedeclarationWithLinkage) {
1143 // Determine whether this (or a previous) declaration is
1144 // out-of-scope.
John McCalld226f652010-08-21 09:40:31 +00001145 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001146 LeftStartingScope = true;
1147
1148 // If we found something outside of our starting scope that
1149 // does not have linkage, skip it.
1150 if (LeftStartingScope && !((*I)->hasLinkage()))
1151 continue;
1152 }
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001153 else if (NameKind == LookupObjCImplicitSelfParam &&
1154 !isa<ImplicitParamDecl>(*I))
1155 continue;
1156
Douglas Gregor10ce9322011-12-02 20:08:44 +00001157 // If this declaration is module-private and it came from an AST
1158 // file, we can't see it.
Douglas Gregor447af242012-01-05 01:11:47 +00001159 NamedDecl *D = R.isHiddenDeclarationVisible()? *I : getVisibleDecl(*I);
Douglas Gregor55368912011-12-14 16:03:29 +00001160 if (!D)
Douglas Gregor10ce9322011-12-02 20:08:44 +00001161 continue;
Douglas Gregor55368912011-12-14 16:03:29 +00001162
1163 R.addDecl(D);
John McCallf36e02d2009-10-09 21:13:30 +00001164
Douglas Gregor7a537402012-01-03 23:26:26 +00001165 // Check whether there are any other declarations with the same name
1166 // and in the same scope.
Douglas Gregorda795b42012-01-04 16:44:10 +00001167 if (I != IEnd) {
Douglas Gregor117c4562012-01-13 23:06:53 +00001168 // Find the scope in which this declaration was declared (if it
1169 // actually exists in a Scope).
1170 while (S && !S->isDeclScope(D))
1171 S = S->getParent();
1172
1173 // If the scope containing the declaration is the translation unit,
1174 // then we'll need to perform our checks based on the matching
1175 // DeclContexts rather than matching scopes.
1176 if (S && isNamespaceOrTranslationUnitScope(S))
1177 S = 0;
1178
1179 // Compute the DeclContext, if we need it.
1180 DeclContext *DC = 0;
1181 if (!S)
1182 DC = (*I)->getDeclContext()->getRedeclContext();
1183
Douglas Gregorda795b42012-01-04 16:44:10 +00001184 IdentifierResolver::iterator LastI = I;
1185 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor117c4562012-01-13 23:06:53 +00001186 if (S) {
1187 // Match based on scope.
1188 if (!S->isDeclScope(*LastI))
1189 break;
1190 } else {
1191 // Match based on DeclContext.
1192 DeclContext *LastDC
1193 = (*LastI)->getDeclContext()->getRedeclContext();
1194 if (!LastDC->Equals(DC))
1195 break;
1196 }
1197
1198 // If the declaration isn't in the right namespace, skip it.
Douglas Gregorda795b42012-01-04 16:44:10 +00001199 if (!(*LastI)->isInIdentifierNamespace(IDNS))
1200 continue;
Douglas Gregor117c4562012-01-13 23:06:53 +00001201
Douglas Gregor447af242012-01-05 01:11:47 +00001202 D = R.isHiddenDeclarationVisible()? *LastI : getVisibleDecl(*LastI);
Douglas Gregorda795b42012-01-04 16:44:10 +00001203 if (D)
1204 R.addDecl(D);
1205 }
Douglas Gregorf9201e02009-02-11 23:02:49 +00001206
Douglas Gregorda795b42012-01-04 16:44:10 +00001207 R.resolveKind();
Douglas Gregorf9201e02009-02-11 23:02:49 +00001208 }
John McCallf36e02d2009-10-09 21:13:30 +00001209 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +00001210 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001211 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001212 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +00001213 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +00001214 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001215 }
1216
1217 // If we didn't find a use of this identifier, and if the identifier
1218 // corresponds to a compiler builtin, create the decl object for the builtin
1219 // now, injecting it into translation unit scope, and return it.
Axel Naumann42151d52011-04-13 13:19:46 +00001220 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1221 return true;
Douglas Gregor3e41d602009-02-13 23:20:09 +00001222
Axel Naumannf8291a12011-02-24 16:47:47 +00001223 // If we didn't find a use of this identifier, the ExternalSource
1224 // may be able to handle the situation.
1225 // Note: some lookup failures are expected!
1226 // See e.g. R.isForRedeclaration().
1227 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001228}
1229
John McCall6e247262009-10-10 05:48:19 +00001230/// @brief Perform qualified name lookup in the namespaces nominated by
1231/// using directives by the given context.
1232///
1233/// C++98 [namespace.qual]p2:
1234/// Given X::m (where X is a user-declared namespace), or given ::m
1235/// (where X is the global namespace), let S be the set of all
1236/// declarations of m in X and in the transitive closure of all
1237/// namespaces nominated by using-directives in X and its used
1238/// namespaces, except that using-directives are ignored in any
1239/// namespace, including X, directly containing one or more
1240/// declarations of m. No namespace is searched more than once in
1241/// the lookup of a name. If S is the empty set, the program is
1242/// ill-formed. Otherwise, if S has exactly one member, or if the
1243/// context of the reference is a using-declaration
1244/// (namespace.udecl), S is the required set of declarations of
1245/// m. Otherwise if the use of m is not one that allows a unique
1246/// declaration to be chosen from S, the program is ill-formed.
1247/// C++98 [namespace.qual]p5:
1248/// During the lookup of a qualified namespace member name, if the
1249/// lookup finds more than one declaration of the member, and if one
1250/// declaration introduces a class name or enumeration name and the
1251/// other declarations either introduce the same object, the same
1252/// enumerator or a set of functions, the non-type name hides the
1253/// class or enumeration name if and only if the declarations are
1254/// from the same namespace; otherwise (the declarations are from
1255/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +00001256static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +00001257 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +00001258 assert(StartDC->isFileContext() && "start context is not a file context");
1259
1260 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1261 DeclContext::udir_iterator E = StartDC->using_directives_end();
1262
1263 if (I == E) return false;
1264
1265 // We have at least added all these contexts to the queue.
1266 llvm::DenseSet<DeclContext*> Visited;
1267 Visited.insert(StartDC);
1268
1269 // We have not yet looked into these namespaces, much less added
1270 // their "using-children" to the queue.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001271 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6e247262009-10-10 05:48:19 +00001272
1273 // We have already looked into the initial namespace; seed the queue
1274 // with its using-children.
1275 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001276 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6e247262009-10-10 05:48:19 +00001277 if (Visited.insert(ND).second)
1278 Queue.push_back(ND);
1279 }
1280
1281 // The easiest way to implement the restriction in [namespace.qual]p5
1282 // is to check whether any of the individual results found a tag
1283 // and, if so, to declare an ambiguity if the final result is not
1284 // a tag.
1285 bool FoundTag = false;
1286 bool FoundNonTag = false;
1287
John McCall7d384dd2009-11-18 07:57:50 +00001288 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001289
1290 bool Found = false;
1291 while (!Queue.empty()) {
1292 NamespaceDecl *ND = Queue.back();
1293 Queue.pop_back();
1294
1295 // We go through some convolutions here to avoid copying results
1296 // between LookupResults.
1297 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001298 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001299 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001300
1301 if (FoundDirect) {
1302 // First do any local hiding.
1303 DirectR.resolveKind();
1304
1305 // If the local result is a tag, remember that.
1306 if (DirectR.isSingleTagDecl())
1307 FoundTag = true;
1308 else
1309 FoundNonTag = true;
1310
1311 // Append the local results to the total results if necessary.
1312 if (UseLocal) {
1313 R.addAllDecls(LocalR);
1314 LocalR.clear();
1315 }
1316 }
1317
1318 // If we find names in this namespace, ignore its using directives.
1319 if (FoundDirect) {
1320 Found = true;
1321 continue;
1322 }
1323
1324 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1325 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1326 if (Visited.insert(Nom).second)
1327 Queue.push_back(Nom);
1328 }
1329 }
1330
1331 if (Found) {
1332 if (FoundTag && FoundNonTag)
1333 R.setAmbiguousQualifiedTagHiding();
1334 else
1335 R.resolveKind();
1336 }
1337
1338 return Found;
1339}
1340
Douglas Gregor8071e422010-08-15 06:18:01 +00001341/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001342static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor8071e422010-08-15 06:18:01 +00001343 CXXBasePath &Path,
1344 void *Name) {
1345 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001346
Douglas Gregor8071e422010-08-15 06:18:01 +00001347 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1348 Path.Decls = BaseRecord->lookup(N);
1349 return Path.Decls.first != Path.Decls.second;
1350}
1351
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001352/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001353/// static members, nested types, and enumerators.
1354template<typename InputIterator>
1355static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1356 Decl *D = (*First)->getUnderlyingDecl();
1357 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1358 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001359
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001360 if (isa<CXXMethodDecl>(D)) {
1361 // Determine whether all of the methods are static.
1362 bool AllMethodsAreStatic = true;
1363 for(; First != Last; ++First) {
1364 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001365
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001366 if (!isa<CXXMethodDecl>(D)) {
1367 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1368 break;
1369 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001370
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001371 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1372 AllMethodsAreStatic = false;
1373 break;
1374 }
1375 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001376
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001377 if (AllMethodsAreStatic)
1378 return true;
1379 }
1380
1381 return false;
1382}
1383
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001384/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001385///
1386/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1387/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001388/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001389///
1390/// Different lookup criteria can find different names. For example, a
1391/// particular scope can have both a struct and a function of the same
1392/// name, and each can be found by certain lookup criteria. For more
1393/// information about lookup criteria, see the documentation for the
1394/// class LookupCriteria.
1395///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001396/// \param R captures both the lookup criteria and any lookup results found.
1397///
1398/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001399/// search. If the lookup criteria permits, name lookup may also search
1400/// in the parent contexts or (for C++ classes) base classes.
1401///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001402/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001403/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001404///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001405/// \returns true if lookup succeeded, false if it failed.
1406bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1407 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001408 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001409
John McCalla24dc2e2009-11-17 02:14:36 +00001410 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001411 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001412
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001413 // Make sure that the declaration context is complete.
1414 assert((!isa<TagDecl>(LookupCtx) ||
1415 LookupCtx->isDependentContext() ||
John McCall5e1cdac2011-10-07 06:10:15 +00001416 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001417 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1418 ->isBeingDefined()) &&
1419 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001420
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001421 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001422 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001423 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001424 if (isa<CXXRecordDecl>(LookupCtx))
1425 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001426 return true;
1427 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001428
John McCall6e247262009-10-10 05:48:19 +00001429 // Don't descend into implied contexts for redeclarations.
1430 // C++98 [namespace.qual]p6:
1431 // In a declaration for a namespace member in which the
1432 // declarator-id is a qualified-id, given that the qualified-id
1433 // for the namespace member has the form
1434 // nested-name-specifier unqualified-id
1435 // the unqualified-id shall name a member of the namespace
1436 // designated by the nested-name-specifier.
1437 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001438 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001439 return false;
1440
John McCalla24dc2e2009-11-17 02:14:36 +00001441 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001442 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001443 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001444
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001445 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001446 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001447 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor025291b2010-07-01 00:21:21 +00001448 if (!LookupRec || !LookupRec->getDefinition())
John McCallf36e02d2009-10-09 21:13:30 +00001449 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001450
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001451 // If we're performing qualified name lookup into a dependent class,
1452 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001453 // dependent base classes, then we either have to delay lookup until
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001454 // template instantiation time (at which point all bases will be available)
1455 // or we have to fail.
1456 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1457 LookupRec->hasAnyDependentBases()) {
1458 R.setNotFoundInCurrentInstantiation();
1459 return false;
1460 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001461
Douglas Gregor7176fff2009-01-15 00:26:24 +00001462 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001463 CXXBasePaths Paths;
1464 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001465
1466 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001467 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001468 switch (R.getLookupKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001469 case LookupObjCImplicitSelfParam:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001470 case LookupOrdinaryName:
1471 case LookupMemberName:
1472 case LookupRedeclarationWithLinkage:
1473 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1474 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001475
Douglas Gregora8f32e02009-10-06 17:59:45 +00001476 case LookupTagName:
1477 BaseCallback = &CXXRecordDecl::FindTagMember;
1478 break;
John McCall9f54ad42009-12-10 09:41:52 +00001479
Douglas Gregor8071e422010-08-15 06:18:01 +00001480 case LookupAnyName:
1481 BaseCallback = &LookupAnyMember;
1482 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001483
John McCall9f54ad42009-12-10 09:41:52 +00001484 case LookupUsingDeclName:
1485 // This lookup is for redeclarations only.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001486
Douglas Gregora8f32e02009-10-06 17:59:45 +00001487 case LookupOperatorName:
1488 case LookupNamespaceName:
1489 case LookupObjCProtocolName:
Chris Lattner337e5502011-02-18 01:27:55 +00001490 case LookupLabel:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001491 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001492 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001493
Douglas Gregora8f32e02009-10-06 17:59:45 +00001494 case LookupNestedNameSpecifierName:
1495 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1496 break;
1497 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001498
John McCalla24dc2e2009-11-17 02:14:36 +00001499 if (!LookupRec->lookupInBases(BaseCallback,
1500 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001501 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001502
John McCall92f88312010-01-23 00:46:32 +00001503 R.setNamingClass(LookupRec);
1504
Douglas Gregor7176fff2009-01-15 00:26:24 +00001505 // C++ [class.member.lookup]p2:
1506 // [...] If the resulting set of declarations are not all from
1507 // sub-objects of the same type, or the set has a nonstatic member
1508 // and includes members from distinct sub-objects, there is an
1509 // ambiguity and the program is ill-formed. Otherwise that set is
1510 // the result of the lookup.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001511 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001512 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001513 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001514
Douglas Gregora8f32e02009-10-06 17:59:45 +00001515 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001516 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001517 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001518
John McCall46460a62010-01-20 21:53:11 +00001519 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1520 // across all paths.
1521 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001522
Douglas Gregor7176fff2009-01-15 00:26:24 +00001523 // Determine whether we're looking at a distinct sub-object or not.
1524 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001525 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001526 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1527 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001528 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001529 }
1530
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001531 if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001532 != Context.getCanonicalType(PathElement.Base->getType())) {
1533 // We found members of the given name in two subobjects of
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001534 // different types. If the declaration sets aren't the same, this
1535 // this lookup is ambiguous.
1536 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1537 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1538 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1539 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001540
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001541 while (FirstD != FirstPath->Decls.second &&
1542 CurrentD != Path->Decls.second) {
1543 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1544 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1545 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001546
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001547 ++FirstD;
1548 ++CurrentD;
1549 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001550
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001551 if (FirstD == FirstPath->Decls.second &&
1552 CurrentD == Path->Decls.second)
1553 continue;
1554 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001555
John McCallf36e02d2009-10-09 21:13:30 +00001556 R.setAmbiguousBaseSubobjectTypes(Paths);
1557 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001558 }
1559
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001560 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001561 // We have a different subobject of the same type.
1562
1563 // C++ [class.member.lookup]p5:
1564 // A static member, a nested type or an enumerator defined in
1565 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001566 // has more than one base class subobject of type T.
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001567 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
Douglas Gregor7176fff2009-01-15 00:26:24 +00001568 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001569
Douglas Gregor7176fff2009-01-15 00:26:24 +00001570 // We have found a nonstatic member name in multiple, distinct
1571 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001572 R.setAmbiguousBaseSubobjects(Paths);
1573 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001574 }
1575 }
1576
1577 // Lookup in a base class succeeded; return these results.
1578
John McCallf36e02d2009-10-09 21:13:30 +00001579 DeclContext::lookup_iterator I, E;
John McCall92f88312010-01-23 00:46:32 +00001580 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1581 NamedDecl *D = *I;
1582 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1583 D->getAccess());
1584 R.addDecl(D, AS);
1585 }
John McCallf36e02d2009-10-09 21:13:30 +00001586 R.resolveKind();
1587 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001588}
1589
1590/// @brief Performs name lookup for a name that was parsed in the
1591/// source code, and may contain a C++ scope specifier.
1592///
1593/// This routine is a convenience routine meant to be called from
1594/// contexts that receive a name and an optional C++ scope specifier
1595/// (e.g., "N::M::x"). It will then perform either qualified or
1596/// unqualified name lookup (with LookupQualifiedName or LookupName,
1597/// respectively) on the given name and return those results.
1598///
1599/// @param S The scope from which unqualified name lookup will
1600/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001601///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001602/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001603///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001604/// @param EnteringContext Indicates whether we are going to enter the
1605/// context of the scope-specifier SS (if present).
1606///
John McCallf36e02d2009-10-09 21:13:30 +00001607/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001608bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001609 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001610 if (SS && SS->isInvalid()) {
1611 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001612 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001613 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001614 }
Mike Stump1eb44332009-09-09 15:08:12 +00001615
Douglas Gregor495c35d2009-08-25 22:51:20 +00001616 if (SS && SS->isSet()) {
1617 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001618 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001619 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001620 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001621 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001622
John McCalla24dc2e2009-11-17 02:14:36 +00001623 R.setContextRange(SS->getRange());
John McCalla24dc2e2009-11-17 02:14:36 +00001624 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001625 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001626
Douglas Gregor495c35d2009-08-25 22:51:20 +00001627 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001628 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001629 // Name lookup can't find anything in this case.
Douglas Gregor3eafbb82011-10-24 22:24:50 +00001630 R.setNotFoundInCurrentInstantiation();
1631 R.setContextRange(SS->getRange());
John McCallf36e02d2009-10-09 21:13:30 +00001632 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001633 }
1634
Mike Stump1eb44332009-09-09 15:08:12 +00001635 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001636 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001637}
1638
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001639
Douglas Gregor7176fff2009-01-15 00:26:24 +00001640/// @brief Produce a diagnostic describing the ambiguity that resulted
1641/// from name lookup.
1642///
1643/// @param Result The ambiguous name lookup result.
Mike Stump1eb44332009-09-09 15:08:12 +00001644///
Douglas Gregor7176fff2009-01-15 00:26:24 +00001645/// @param Name The name of the entity that name lookup was
1646/// searching for.
1647///
1648/// @param NameLoc The location of the name within the source code.
1649///
1650/// @param LookupRange A source range that provides more
1651/// source-location information concerning the lookup itself. For
1652/// example, this range might highlight a nested-name-specifier that
1653/// precedes the name.
1654///
1655/// @returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001656bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001657 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1658
John McCalla24dc2e2009-11-17 02:14:36 +00001659 DeclarationName Name = Result.getLookupName();
1660 SourceLocation NameLoc = Result.getNameLoc();
1661 SourceRange LookupRange = Result.getContextRange();
1662
John McCall6e247262009-10-10 05:48:19 +00001663 switch (Result.getAmbiguityKind()) {
1664 case LookupResult::AmbiguousBaseSubobjects: {
1665 CXXBasePaths *Paths = Result.getBasePaths();
1666 QualType SubobjectType = Paths->front().back().Base->getType();
1667 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1668 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1669 << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001670
John McCall6e247262009-10-10 05:48:19 +00001671 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1672 while (isa<CXXMethodDecl>(*Found) &&
1673 cast<CXXMethodDecl>(*Found)->isStatic())
1674 ++Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001675
John McCall6e247262009-10-10 05:48:19 +00001676 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001677
John McCall6e247262009-10-10 05:48:19 +00001678 return true;
1679 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001680
John McCall6e247262009-10-10 05:48:19 +00001681 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001682 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1683 << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001684
John McCall6e247262009-10-10 05:48:19 +00001685 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001686 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001687 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1688 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001689 Path != PathEnd; ++Path) {
1690 Decl *D = *Path->Decls.first;
1691 if (DeclsPrinted.insert(D).second)
1692 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1693 }
1694
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001695 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001696 }
1697
John McCall6e247262009-10-10 05:48:19 +00001698 case LookupResult::AmbiguousTagHiding: {
1699 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001700
John McCall6e247262009-10-10 05:48:19 +00001701 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1702
1703 LookupResult::iterator DI, DE = Result.end();
1704 for (DI = Result.begin(); DI != DE; ++DI)
1705 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1706 TagDecls.insert(TD);
1707 Diag(TD->getLocation(), diag::note_hidden_tag);
1708 }
1709
1710 for (DI = Result.begin(); DI != DE; ++DI)
1711 if (!isa<TagDecl>(*DI))
1712 Diag((*DI)->getLocation(), diag::note_hiding_object);
1713
1714 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001715 LookupResult::Filter F = Result.makeFilter();
1716 while (F.hasNext()) {
1717 if (TagDecls.count(F.next()))
1718 F.erase();
1719 }
1720 F.done();
John McCall6e247262009-10-10 05:48:19 +00001721
1722 return true;
1723 }
1724
1725 case LookupResult::AmbiguousReference: {
1726 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001727
John McCall6e247262009-10-10 05:48:19 +00001728 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1729 for (; DI != DE; ++DI)
1730 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001731
John McCall6e247262009-10-10 05:48:19 +00001732 return true;
1733 }
1734 }
1735
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001736 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001737}
Douglas Gregorfa047642009-02-04 00:32:51 +00001738
John McCallc7e04da2010-05-28 18:45:08 +00001739namespace {
1740 struct AssociatedLookup {
1741 AssociatedLookup(Sema &S,
1742 Sema::AssociatedNamespaceSet &Namespaces,
1743 Sema::AssociatedClassSet &Classes)
1744 : S(S), Namespaces(Namespaces), Classes(Classes) {
1745 }
1746
1747 Sema &S;
1748 Sema::AssociatedNamespaceSet &Namespaces;
1749 Sema::AssociatedClassSet &Classes;
1750 };
1751}
1752
Mike Stump1eb44332009-09-09 15:08:12 +00001753static void
John McCallc7e04da2010-05-28 18:45:08 +00001754addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCall6ff07852009-08-07 22:18:02 +00001755
Douglas Gregor54022952010-04-30 07:08:38 +00001756static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1757 DeclContext *Ctx) {
1758 // Add the associated namespace for this class.
1759
1760 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1761 // be a locally scoped record.
1762
Sebastian Redl410c4f22010-08-31 20:53:31 +00001763 // We skip out of inline namespaces. The innermost non-inline namespace
1764 // contains all names of all its nested inline namespaces anyway, so we can
1765 // replace the entire inline namespace tree with its root.
1766 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1767 Ctx->isInlineNamespace())
Douglas Gregor54022952010-04-30 07:08:38 +00001768 Ctx = Ctx->getParent();
1769
John McCall6ff07852009-08-07 22:18:02 +00001770 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001771 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001772}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001773
Mike Stump1eb44332009-09-09 15:08:12 +00001774// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001775// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001776static void
John McCallc7e04da2010-05-28 18:45:08 +00001777addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1778 const TemplateArgument &Arg) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001779 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001780 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001781 switch (Arg.getKind()) {
1782 case TemplateArgument::Null:
1783 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001784
Douglas Gregor69be8d62009-07-08 07:51:57 +00001785 case TemplateArgument::Type:
1786 // [...] the namespaces and classes associated with the types of the
1787 // template arguments provided for template type parameters (excluding
1788 // template template parameters)
John McCallc7e04da2010-05-28 18:45:08 +00001789 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor69be8d62009-07-08 07:51:57 +00001790 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001791
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001792 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001793 case TemplateArgument::TemplateExpansion: {
Mike Stump1eb44332009-09-09 15:08:12 +00001794 // [...] the namespaces in which any template template arguments are
1795 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001796 // template template arguments are defined.
Douglas Gregora7fc9012011-01-05 18:58:31 +00001797 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump1eb44332009-09-09 15:08:12 +00001798 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001799 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001800 DeclContext *Ctx = ClassTemplate->getDeclContext();
1801 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001802 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001803 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001804 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001805 }
1806 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001807 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001808
Douglas Gregor788cd062009-11-11 01:00:40 +00001809 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001810 case TemplateArgument::Integral:
1811 case TemplateArgument::Expression:
Mike Stump1eb44332009-09-09 15:08:12 +00001812 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001813 // associated namespaces. ]
1814 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001815
Douglas Gregor69be8d62009-07-08 07:51:57 +00001816 case TemplateArgument::Pack:
1817 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1818 PEnd = Arg.pack_end();
1819 P != PEnd; ++P)
John McCallc7e04da2010-05-28 18:45:08 +00001820 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001821 break;
1822 }
1823}
1824
Douglas Gregorfa047642009-02-04 00:32:51 +00001825// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001826// argument-dependent lookup with an argument of class type
1827// (C++ [basic.lookup.koenig]p2).
1828static void
John McCallc7e04da2010-05-28 18:45:08 +00001829addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1830 CXXRecordDecl *Class) {
1831
1832 // Just silently ignore anything whose name is __va_list_tag.
1833 if (Class->getDeclName() == Result.S.VAListTagName)
1834 return;
1835
Douglas Gregorfa047642009-02-04 00:32:51 +00001836 // C++ [basic.lookup.koenig]p2:
1837 // [...]
1838 // -- If T is a class type (including unions), its associated
1839 // classes are: the class itself; the class of which it is a
1840 // member, if any; and its direct and indirect base
1841 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001842 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001843
1844 // Add the class of which it is a member, if any.
1845 DeclContext *Ctx = Class->getDeclContext();
1846 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001847 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001848 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001849 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001850
Douglas Gregorfa047642009-02-04 00:32:51 +00001851 // Add the class itself. If we've already seen this class, we don't
1852 // need to visit base classes.
John McCallc7e04da2010-05-28 18:45:08 +00001853 if (!Result.Classes.insert(Class))
Douglas Gregorfa047642009-02-04 00:32:51 +00001854 return;
1855
Mike Stump1eb44332009-09-09 15:08:12 +00001856 // -- If T is a template-id, its associated namespaces and classes are
1857 // the namespace in which the template is defined; for member
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001858 // templates, the member template's class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001859 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001860 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001861 // namespaces in which any template template arguments are defined; and
1862 // the classes in which any member templates used as template template
1863 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001864 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001865 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001866 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1867 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1868 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001869 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001870 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001871 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001872
Douglas Gregor69be8d62009-07-08 07:51:57 +00001873 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1874 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallc7e04da2010-05-28 18:45:08 +00001875 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001876 }
Mike Stump1eb44332009-09-09 15:08:12 +00001877
John McCall86ff3082010-02-04 22:26:26 +00001878 // Only recurse into base classes for complete types.
1879 if (!Class->hasDefinition()) {
1880 // FIXME: we might need to instantiate templates here
1881 return;
1882 }
1883
Douglas Gregorfa047642009-02-04 00:32:51 +00001884 // Add direct and indirect base classes along with their associated
1885 // namespaces.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001886 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregorfa047642009-02-04 00:32:51 +00001887 Bases.push_back(Class);
1888 while (!Bases.empty()) {
1889 // Pop this class off the stack.
1890 Class = Bases.back();
1891 Bases.pop_back();
1892
1893 // Visit the base classes.
1894 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1895 BaseEnd = Class->bases_end();
1896 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001897 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001898 // In dependent contexts, we do ADL twice, and the first time around,
1899 // the base type might be a dependent TemplateSpecializationType, or a
1900 // TemplateTypeParmType. If that happens, simply ignore it.
1901 // FIXME: If we want to support export, we probably need to add the
1902 // namespace of the template in a TemplateSpecializationType, or even
1903 // the classes and namespaces of known non-dependent arguments.
1904 if (!BaseType)
1905 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001906 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001907 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001908 // Find the associated namespace for this base class.
1909 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallc7e04da2010-05-28 18:45:08 +00001910 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001911
1912 // Make sure we visit the bases of this base class.
1913 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1914 Bases.push_back(BaseDecl);
1915 }
1916 }
1917 }
1918}
1919
1920// \brief Add the associated classes and namespaces for
1921// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001922// (C++ [basic.lookup.koenig]p2).
1923static void
John McCallc7e04da2010-05-28 18:45:08 +00001924addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001925 // C++ [basic.lookup.koenig]p2:
1926 //
1927 // For each argument type T in the function call, there is a set
1928 // of zero or more associated namespaces and a set of zero or more
1929 // associated classes to be considered. The sets of namespaces and
1930 // classes is determined entirely by the types of the function
1931 // arguments (and the namespace of any template template
1932 // argument). Typedef names and using-declarations used to specify
1933 // the types do not contribute to this set. The sets of namespaces
1934 // and classes are determined in the following way:
Douglas Gregorfa047642009-02-04 00:32:51 +00001935
Chris Lattner5f9e2722011-07-23 10:55:15 +00001936 SmallVector<const Type *, 16> Queue;
John McCallfa4edcf2010-05-28 06:08:54 +00001937 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1938
Douglas Gregorfa047642009-02-04 00:32:51 +00001939 while (true) {
John McCallfa4edcf2010-05-28 06:08:54 +00001940 switch (T->getTypeClass()) {
1941
1942#define TYPE(Class, Base)
1943#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1944#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1945#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1946#define ABSTRACT_TYPE(Class, Base)
1947#include "clang/AST/TypeNodes.def"
1948 // T is canonical. We can also ignore dependent types because
1949 // we don't need to do ADL at the definition point, but if we
1950 // wanted to implement template export (or if we find some other
1951 // use for associated classes and namespaces...) this would be
1952 // wrong.
Douglas Gregorfa047642009-02-04 00:32:51 +00001953 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00001954
John McCallfa4edcf2010-05-28 06:08:54 +00001955 // -- If T is a pointer to U or an array of U, its associated
1956 // namespaces and classes are those associated with U.
1957 case Type::Pointer:
1958 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1959 continue;
1960 case Type::ConstantArray:
1961 case Type::IncompleteArray:
1962 case Type::VariableArray:
1963 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1964 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001965
John McCallfa4edcf2010-05-28 06:08:54 +00001966 // -- If T is a fundamental type, its associated sets of
1967 // namespaces and classes are both empty.
1968 case Type::Builtin:
1969 break;
1970
1971 // -- If T is a class type (including unions), its associated
1972 // classes are: the class itself; the class of which it is a
1973 // member, if any; and its direct and indirect base
1974 // classes. Its associated namespaces are the namespaces in
1975 // which its associated classes are defined.
1976 case Type::Record: {
1977 CXXRecordDecl *Class
1978 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001979 addAssociatedClassesAndNamespaces(Result, Class);
John McCallfa4edcf2010-05-28 06:08:54 +00001980 break;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001981 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00001982
John McCallfa4edcf2010-05-28 06:08:54 +00001983 // -- If T is an enumeration type, its associated namespace is
1984 // the namespace in which it is defined. If it is class
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001985 // member, its associated class is the member's class; else
John McCallfa4edcf2010-05-28 06:08:54 +00001986 // it has no associated class.
1987 case Type::Enum: {
1988 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001989
John McCallfa4edcf2010-05-28 06:08:54 +00001990 DeclContext *Ctx = Enum->getDeclContext();
1991 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001992 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001993
John McCallfa4edcf2010-05-28 06:08:54 +00001994 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001995 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001996
John McCallfa4edcf2010-05-28 06:08:54 +00001997 break;
1998 }
1999
2000 // -- If T is a function type, its associated namespaces and
2001 // classes are those associated with the function parameter
2002 // types and those associated with the return type.
2003 case Type::FunctionProto: {
2004 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2005 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
2006 ArgEnd = Proto->arg_type_end();
2007 Arg != ArgEnd; ++Arg)
2008 Queue.push_back(Arg->getTypePtr());
2009 // fallthrough
2010 }
2011 case Type::FunctionNoProto: {
2012 const FunctionType *FnType = cast<FunctionType>(T);
2013 T = FnType->getResultType().getTypePtr();
2014 continue;
2015 }
2016
2017 // -- If T is a pointer to a member function of a class X, its
2018 // associated namespaces and classes are those associated
2019 // with the function parameter types and return type,
2020 // together with those associated with X.
2021 //
2022 // -- If T is a pointer to a data member of class X, its
2023 // associated namespaces and classes are those associated
2024 // with the member type together with those associated with
2025 // X.
2026 case Type::MemberPointer: {
2027 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2028
2029 // Queue up the class type into which this points.
2030 Queue.push_back(MemberPtr->getClass());
2031
2032 // And directly continue with the pointee type.
2033 T = MemberPtr->getPointeeType().getTypePtr();
2034 continue;
2035 }
2036
2037 // As an extension, treat this like a normal pointer.
2038 case Type::BlockPointer:
2039 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2040 continue;
2041
2042 // References aren't covered by the standard, but that's such an
2043 // obvious defect that we cover them anyway.
2044 case Type::LValueReference:
2045 case Type::RValueReference:
2046 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2047 continue;
2048
2049 // These are fundamental types.
2050 case Type::Vector:
2051 case Type::ExtVector:
2052 case Type::Complex:
2053 break;
2054
Douglas Gregorf25760e2011-04-12 01:02:45 +00002055 // If T is an Objective-C object or interface type, or a pointer to an
2056 // object or interface type, the associated namespace is the global
2057 // namespace.
John McCallfa4edcf2010-05-28 06:08:54 +00002058 case Type::ObjCObject:
2059 case Type::ObjCInterface:
2060 case Type::ObjCObjectPointer:
Douglas Gregorf25760e2011-04-12 01:02:45 +00002061 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCallfa4edcf2010-05-28 06:08:54 +00002062 break;
Eli Friedmanb001de72011-10-06 23:00:33 +00002063
2064 // Atomic types are just wrappers; use the associations of the
2065 // contained type.
2066 case Type::Atomic:
2067 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2068 continue;
John McCallfa4edcf2010-05-28 06:08:54 +00002069 }
2070
2071 if (Queue.empty()) break;
2072 T = Queue.back();
2073 Queue.pop_back();
Douglas Gregorfa047642009-02-04 00:32:51 +00002074 }
Douglas Gregorfa047642009-02-04 00:32:51 +00002075}
2076
2077/// \brief Find the associated classes and namespaces for
2078/// argument-dependent lookup for a call with the given set of
2079/// arguments.
2080///
2081/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00002082/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00002083/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00002084void
Douglas Gregorfa047642009-02-04 00:32:51 +00002085Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
2086 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00002087 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002088 AssociatedNamespaces.clear();
2089 AssociatedClasses.clear();
2090
John McCallc7e04da2010-05-28 18:45:08 +00002091 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
2092
Douglas Gregorfa047642009-02-04 00:32:51 +00002093 // C++ [basic.lookup.koenig]p2:
2094 // For each argument type T in the function call, there is a set
2095 // of zero or more associated namespaces and a set of zero or more
2096 // associated classes to be considered. The sets of namespaces and
2097 // classes is determined entirely by the types of the function
2098 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00002099 // argument).
Douglas Gregorfa047642009-02-04 00:32:51 +00002100 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
2101 Expr *Arg = Args[ArgIdx];
2102
2103 if (Arg->getType() != Context.OverloadTy) {
John McCallc7e04da2010-05-28 18:45:08 +00002104 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002105 continue;
2106 }
2107
2108 // [...] In addition, if the argument is the name or address of a
2109 // set of overloaded functions and/or function templates, its
2110 // associated classes and namespaces are the union of those
2111 // associated with each of the members of the set: the namespace
2112 // in which the function or function template is defined and the
2113 // classes and namespaces associated with its (non-dependent)
2114 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00002115 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00002116 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCall2de56d12010-08-25 11:45:40 +00002117 if (unaryOp->getOpcode() == UO_AddrOf)
John McCallba135432009-11-21 08:51:07 +00002118 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002119
John McCallc7e04da2010-05-28 18:45:08 +00002120 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2121 if (!ULE) continue;
John McCallba135432009-11-21 08:51:07 +00002122
John McCallc7e04da2010-05-28 18:45:08 +00002123 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2124 I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00002125 // Look through any using declarations to find the underlying function.
2126 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002127
Chandler Carruthbd647292009-12-29 06:17:27 +00002128 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2129 if (!FDecl)
2130 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002131
2132 // Add the classes and namespaces associated with the parameter
2133 // types and return type of this function.
John McCallc7e04da2010-05-28 18:45:08 +00002134 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002135 }
2136 }
2137}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002138
2139/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2140/// an acceptable non-member overloaded operator for a call whose
2141/// arguments have types T1 (and, if non-empty, T2). This routine
2142/// implements the check in C++ [over.match.oper]p3b2 concerning
2143/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00002144static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002145IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2146 QualType T1, QualType T2,
2147 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00002148 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2149 return true;
2150
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002151 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2152 return true;
2153
John McCall183700f2009-09-21 23:43:11 +00002154 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002155 if (Proto->getNumArgs() < 1)
2156 return false;
2157
2158 if (T1->isEnumeralType()) {
2159 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002160 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002161 return true;
2162 }
2163
2164 if (Proto->getNumArgs() < 2)
2165 return false;
2166
2167 if (!T2.isNull() && T2->isEnumeralType()) {
2168 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002169 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002170 return true;
2171 }
2172
2173 return false;
2174}
2175
John McCall7d384dd2009-11-18 07:57:50 +00002176NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002177 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00002178 LookupNameKind NameKind,
2179 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002180 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00002181 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00002182 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00002183}
2184
Douglas Gregor6e378de2009-04-23 23:18:26 +00002185/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002186ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002187 SourceLocation IdLoc,
2188 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002189 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002190 LookupObjCProtocolName, Redecl);
Douglas Gregor6e378de2009-04-23 23:18:26 +00002191 return cast_or_null<ObjCProtocolDecl>(D);
2192}
2193
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002194void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00002195 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00002196 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002197 // C++ [over.match.oper]p3:
2198 // -- The set of non-member candidates is the result of the
2199 // unqualified lookup of operator@ in the context of the
2200 // expression according to the usual rules for name lookup in
2201 // unqualified function calls (3.4.2) except that all member
2202 // functions are ignored. However, if no operand has a class
2203 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00002204 // that have a first parameter of type T1 or "reference to
2205 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002206 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00002207 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002208 // when T2 is an enumeration type, are candidate functions.
2209 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00002210 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2211 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002212
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002213 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2214
John McCallf36e02d2009-10-09 21:13:30 +00002215 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002216 return;
2217
2218 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2219 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002220 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2221 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002222 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002223 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00002224 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002225 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00002226 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00002227 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00002228 // later?
2229 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002230 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00002231 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002232 }
2233}
2234
Sean Huntc39b6bc2011-06-24 02:11:39 +00002235Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Sean Hunt308742c2011-06-04 04:32:43 +00002236 CXXSpecialMember SM,
2237 bool ConstArg,
2238 bool VolatileArg,
2239 bool RValueThis,
2240 bool ConstThis,
2241 bool VolatileThis) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002242 RD = RD->getDefinition();
2243 assert((RD && !RD->isBeingDefined()) &&
Sean Hunt308742c2011-06-04 04:32:43 +00002244 "doing special member lookup into record that isn't fully complete");
2245 if (RValueThis || ConstThis || VolatileThis)
2246 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2247 "constructors and destructors always have unqualified lvalue this");
2248 if (ConstArg || VolatileArg)
2249 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2250 "parameter-less special members can't have qualified arguments");
2251
2252 llvm::FoldingSetNodeID ID;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002253 ID.AddPointer(RD);
Sean Hunt308742c2011-06-04 04:32:43 +00002254 ID.AddInteger(SM);
2255 ID.AddInteger(ConstArg);
2256 ID.AddInteger(VolatileArg);
2257 ID.AddInteger(RValueThis);
2258 ID.AddInteger(ConstThis);
2259 ID.AddInteger(VolatileThis);
2260
2261 void *InsertPoint;
2262 SpecialMemberOverloadResult *Result =
2263 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2264
2265 // This was already cached
2266 if (Result)
2267 return Result;
2268
Sean Hunt30543582011-06-07 00:11:58 +00002269 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2270 Result = new (Result) SpecialMemberOverloadResult(ID);
Sean Hunt308742c2011-06-04 04:32:43 +00002271 SpecialMemberCache.InsertNode(Result, InsertPoint);
2272
2273 if (SM == CXXDestructor) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002274 if (!RD->hasDeclaredDestructor())
2275 DeclareImplicitDestructor(RD);
2276 CXXDestructorDecl *DD = RD->getDestructor();
Sean Hunt308742c2011-06-04 04:32:43 +00002277 assert(DD && "record without a destructor");
2278 Result->setMethod(DD);
Richard Smith7d5088a2012-02-18 02:02:13 +00002279 Result->setSuccess(!DD->isDeleted());
Sean Hunt308742c2011-06-04 04:32:43 +00002280 Result->setConstParamMatch(false);
2281 return Result;
2282 }
2283
Sean Huntb320e0c2011-06-10 03:50:41 +00002284 // Prepare for overload resolution. Here we construct a synthetic argument
2285 // if necessary and make sure that implicit functions are declared.
Sean Huntc39b6bc2011-06-24 02:11:39 +00002286 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Sean Huntb320e0c2011-06-10 03:50:41 +00002287 DeclarationName Name;
2288 Expr *Arg = 0;
2289 unsigned NumArgs;
2290
2291 if (SM == CXXDefaultConstructor) {
2292 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2293 NumArgs = 0;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002294 if (RD->needsImplicitDefaultConstructor())
2295 DeclareImplicitDefaultConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002296 } else {
2297 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2298 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002299 if (!RD->hasDeclaredCopyConstructor())
2300 DeclareImplicitCopyConstructor(RD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002301 if (getLangOptions().CPlusPlus0x && RD->needsImplicitMoveConstructor())
2302 DeclareImplicitMoveConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002303 } else {
2304 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002305 if (!RD->hasDeclaredCopyAssignment())
2306 DeclareImplicitCopyAssignment(RD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002307 if (getLangOptions().CPlusPlus0x && RD->needsImplicitMoveAssignment())
2308 DeclareImplicitMoveAssignment(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002309 }
2310
2311 QualType ArgType = CanTy;
2312 if (ConstArg)
2313 ArgType.addConst();
2314 if (VolatileArg)
2315 ArgType.addVolatile();
2316
2317 // This isn't /really/ specified by the standard, but it's implied
2318 // we should be working from an RValue in the case of move to ensure
2319 // that we prefer to bind to rvalue references, and an LValue in the
2320 // case of copy to ensure we don't bind to rvalue references.
2321 // Possibly an XValue is actually correct in the case of move, but
2322 // there is no semantic difference for class types in this restricted
2323 // case.
2324 ExprValueKind VK;
Sean Huntab183df2011-06-22 22:13:13 +00002325 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Sean Huntb320e0c2011-06-10 03:50:41 +00002326 VK = VK_LValue;
2327 else
2328 VK = VK_RValue;
2329
2330 NumArgs = 1;
2331 Arg = new (Context) OpaqueValueExpr(SourceLocation(), ArgType, VK);
2332 }
2333
2334 // Create the object argument
2335 QualType ThisTy = CanTy;
2336 if (ConstThis)
2337 ThisTy.addConst();
2338 if (VolatileThis)
2339 ThisTy.addVolatile();
Sean Hunt4cc12c62011-06-23 00:26:20 +00002340 Expr::Classification Classification =
Sean Huntb320e0c2011-06-10 03:50:41 +00002341 (new (Context) OpaqueValueExpr(SourceLocation(), ThisTy,
2342 RValueThis ? VK_RValue : VK_LValue))->
2343 Classify(Context);
2344
2345 // Now we perform lookup on the name we computed earlier and do overload
2346 // resolution. Lookup is only performed directly into the class since there
2347 // will always be a (possibly implicit) declaration to shadow any others.
2348 OverloadCandidateSet OCS((SourceLocation()));
2349 DeclContext::lookup_iterator I, E;
2350 Result->setConstParamMatch(false);
2351
Sean Huntc39b6bc2011-06-24 02:11:39 +00002352 llvm::tie(I, E) = RD->lookup(Name);
Sean Huntb320e0c2011-06-10 03:50:41 +00002353 assert((I != E) &&
2354 "lookup for a constructor or assignment operator was empty");
2355 for ( ; I != E; ++I) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002356 Decl *Cand = *I;
Sean Hunt4cc12c62011-06-23 00:26:20 +00002357
Sean Huntc39b6bc2011-06-24 02:11:39 +00002358 if (Cand->isInvalidDecl())
Sean Huntb320e0c2011-06-10 03:50:41 +00002359 continue;
2360
Sean Huntc39b6bc2011-06-24 02:11:39 +00002361 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2362 // FIXME: [namespace.udecl]p15 says that we should only consider a
2363 // using declaration here if it does not match a declaration in the
2364 // derived class. We do not implement this correctly in other cases
2365 // either.
2366 Cand = U->getTargetDecl();
2367
2368 if (Cand->isInvalidDecl())
2369 continue;
2370 }
2371
2372 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002373 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Sean Huntc39b6bc2011-06-24 02:11:39 +00002374 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Sean Hunt4cc12c62011-06-23 00:26:20 +00002375 Classification, &Arg, NumArgs, OCS, true);
2376 else
2377 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public), &Arg,
2378 NumArgs, OCS, true);
Sean Huntb320e0c2011-06-10 03:50:41 +00002379
2380 // Here we're looking for a const parameter to speed up creation of
2381 // implicit copy methods.
2382 if ((SM == CXXCopyAssignment && M->isCopyAssignmentOperator()) ||
2383 (SM == CXXCopyConstructor &&
2384 cast<CXXConstructorDecl>(M)->isCopyConstructor())) {
2385 QualType ArgType = M->getType()->getAs<FunctionProtoType>()->getArgType(0);
Sean Hunt661c67a2011-06-21 23:42:56 +00002386 if (!ArgType->isReferenceType() ||
2387 ArgType->getPointeeType().isConstQualified())
Sean Huntb320e0c2011-06-10 03:50:41 +00002388 Result->setConstParamMatch(true);
2389 }
Sean Hunt431a1cb2011-06-22 02:58:46 +00002390 } else if (FunctionTemplateDecl *Tmpl =
Sean Huntc39b6bc2011-06-24 02:11:39 +00002391 dyn_cast<FunctionTemplateDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002392 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2393 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Sean Huntc39b6bc2011-06-24 02:11:39 +00002394 RD, 0, ThisTy, Classification, &Arg, NumArgs,
Sean Hunt4cc12c62011-06-23 00:26:20 +00002395 OCS, true);
2396 else
2397 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
2398 0, &Arg, NumArgs, OCS, true);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002399 } else {
2400 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Sean Huntb320e0c2011-06-10 03:50:41 +00002401 }
2402 }
2403
2404 OverloadCandidateSet::iterator Best;
2405 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2406 case OR_Success:
2407 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2408 Result->setSuccess(true);
2409 break;
2410
2411 case OR_Deleted:
2412 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2413 Result->setSuccess(false);
2414 break;
2415
2416 case OR_Ambiguous:
2417 case OR_No_Viable_Function:
2418 Result->setMethod(0);
2419 Result->setSuccess(false);
2420 break;
2421 }
2422
2423 return Result;
2424}
2425
2426/// \brief Look up the default constructor for the given class.
2427CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Sean Huntc530d172011-06-10 04:44:37 +00002428 SpecialMemberOverloadResult *Result =
Sean Huntb320e0c2011-06-10 03:50:41 +00002429 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2430 false, false);
2431
2432 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Sean Hunt308742c2011-06-04 04:32:43 +00002433}
2434
Sean Hunt661c67a2011-06-21 23:42:56 +00002435/// \brief Look up the copying constructor for the given class.
2436CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
2437 unsigned Quals,
2438 bool *ConstParamMatch) {
Sean Huntc530d172011-06-10 04:44:37 +00002439 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2440 "non-const, non-volatile qualifiers for copy ctor arg");
2441 SpecialMemberOverloadResult *Result =
2442 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2443 Quals & Qualifiers::Volatile, false, false, false);
2444
2445 if (ConstParamMatch)
2446 *ConstParamMatch = Result->hasConstParamMatch();
2447
2448 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2449}
2450
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002451/// \brief Look up the moving constructor for the given class.
2452CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class) {
2453 SpecialMemberOverloadResult *Result =
2454 LookupSpecialMember(Class, CXXMoveConstructor, false,
2455 false, false, false, false);
2456
2457 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2458}
2459
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002460/// \brief Look up the constructors for the given class.
2461DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002462 // If the implicit constructors have not yet been declared, do so now.
Douglas Gregor18274032010-07-03 00:47:00 +00002463 if (CanDeclareSpecialMemberFunction(Context, Class)) {
Sean Huntcdee3fe2011-05-11 22:34:38 +00002464 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002465 DeclareImplicitDefaultConstructor(Class);
2466 if (!Class->hasDeclaredCopyConstructor())
2467 DeclareImplicitCopyConstructor(Class);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002468 if (getLangOptions().CPlusPlus0x && Class->needsImplicitMoveConstructor())
2469 DeclareImplicitMoveConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +00002470 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002471
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002472 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2473 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2474 return Class->lookup(Name);
2475}
2476
Sean Hunt661c67a2011-06-21 23:42:56 +00002477/// \brief Look up the copying assignment operator for the given class.
2478CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2479 unsigned Quals, bool RValueThis,
2480 unsigned ThisQuals,
2481 bool *ConstParamMatch) {
2482 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2483 "non-const, non-volatile qualifiers for copy assignment arg");
2484 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2485 "non-const, non-volatile qualifiers for copy assignment this");
2486 SpecialMemberOverloadResult *Result =
2487 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2488 Quals & Qualifiers::Volatile, RValueThis,
2489 ThisQuals & Qualifiers::Const,
2490 ThisQuals & Qualifiers::Volatile);
2491
2492 if (ConstParamMatch)
2493 *ConstParamMatch = Result->hasConstParamMatch();
2494
2495 return Result->getMethod();
2496}
2497
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002498/// \brief Look up the moving assignment operator for the given class.
2499CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
2500 bool RValueThis,
2501 unsigned ThisQuals) {
2502 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2503 "non-const, non-volatile qualifiers for copy assignment this");
2504 SpecialMemberOverloadResult *Result =
2505 LookupSpecialMember(Class, CXXMoveAssignment, false, false, RValueThis,
2506 ThisQuals & Qualifiers::Const,
2507 ThisQuals & Qualifiers::Volatile);
2508
2509 return Result->getMethod();
2510}
2511
Douglas Gregordb89f282010-07-01 22:47:18 +00002512/// \brief Look for the destructor of the given class.
2513///
Sean Huntc5c9b532011-06-03 21:10:40 +00002514/// During semantic analysis, this routine should be used in lieu of
2515/// CXXRecordDecl::getDestructor().
Douglas Gregordb89f282010-07-01 22:47:18 +00002516///
2517/// \returns The destructor for this class.
2518CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Sean Hunt308742c2011-06-04 04:32:43 +00002519 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2520 false, false, false,
2521 false, false)->getMethod());
Douglas Gregordb89f282010-07-01 22:47:18 +00002522}
2523
John McCall7edb5fd2010-01-26 07:16:45 +00002524void ADLResult::insert(NamedDecl *New) {
2525 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2526
2527 // If we haven't yet seen a decl for this key, or the last decl
2528 // was exactly this one, we're done.
2529 if (Old == 0 || Old == New) {
2530 Old = New;
2531 return;
2532 }
2533
2534 // Otherwise, decide which is a more recent redeclaration.
2535 FunctionDecl *OldFD, *NewFD;
2536 if (isa<FunctionTemplateDecl>(New)) {
2537 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2538 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2539 } else {
2540 OldFD = cast<FunctionDecl>(Old);
2541 NewFD = cast<FunctionDecl>(New);
2542 }
2543
2544 FunctionDecl *Cursor = NewFD;
2545 while (true) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002546 Cursor = Cursor->getPreviousDecl();
John McCall7edb5fd2010-01-26 07:16:45 +00002547
2548 // If we got to the end without finding OldFD, OldFD is the newer
2549 // declaration; leave things as they are.
2550 if (!Cursor) return;
2551
2552 // If we do find OldFD, then NewFD is newer.
2553 if (Cursor == OldFD) break;
2554
2555 // Otherwise, keep looking.
2556 }
2557
2558 Old = New;
2559}
2560
Sebastian Redl644be852009-10-23 19:23:15 +00002561void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002562 Expr **Args, unsigned NumArgs,
Richard Smithad762fc2011-04-14 22:09:26 +00002563 ADLResult &Result,
2564 bool StdNamespaceIsAssociated) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002565 // Find all of the associated namespaces and classes based on the
2566 // arguments we have.
2567 AssociatedNamespaceSet AssociatedNamespaces;
2568 AssociatedClassSet AssociatedClasses;
Mike Stump1eb44332009-09-09 15:08:12 +00002569 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCall6ff07852009-08-07 22:18:02 +00002570 AssociatedNamespaces,
2571 AssociatedClasses);
Richard Smithad762fc2011-04-14 22:09:26 +00002572 if (StdNamespaceIsAssociated && StdNamespace)
2573 AssociatedNamespaces.insert(getStdNamespace());
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002574
Sebastian Redl644be852009-10-23 19:23:15 +00002575 QualType T1, T2;
2576 if (Operator) {
2577 T1 = Args[0]->getType();
2578 if (NumArgs >= 2)
2579 T2 = Args[1]->getType();
2580 }
2581
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002582 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002583 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2584 // and let Y be the lookup set produced by argument dependent
2585 // lookup (defined as follows). If X contains [...] then Y is
2586 // empty. Otherwise Y is the set of declarations found in the
2587 // namespaces associated with the argument types as described
2588 // below. The set of declarations found by the lookup of the name
2589 // is the union of X and Y.
2590 //
2591 // Here, we compute Y and add its members to the overloaded
2592 // candidate set.
2593 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002594 NSEnd = AssociatedNamespaces.end();
2595 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002596 // When considering an associated namespace, the lookup is the
2597 // same as the lookup performed when the associated namespace is
2598 // used as a qualifier (3.4.3.2) except that:
2599 //
2600 // -- Any using-directives in the associated namespace are
2601 // ignored.
2602 //
John McCall6ff07852009-08-07 22:18:02 +00002603 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002604 // associated classes are visible within their respective
2605 // namespaces even if they are not visible during an ordinary
2606 // lookup (11.4).
2607 DeclContext::lookup_iterator I, E;
John McCall3f9a8a62009-08-11 06:59:38 +00002608 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall6e266892010-01-26 03:27:55 +00002609 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00002610 // If the only declaration here is an ordinary friend, consider
2611 // it only if it was declared in an associated classes.
2612 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00002613 DeclContext *LexDC = D->getLexicalDeclContext();
2614 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2615 continue;
2616 }
Mike Stump1eb44332009-09-09 15:08:12 +00002617
John McCalla113e722010-01-26 06:04:06 +00002618 if (isa<UsingShadowDecl>(D))
2619 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00002620
John McCalla113e722010-01-26 06:04:06 +00002621 if (isa<FunctionDecl>(D)) {
2622 if (Operator &&
2623 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2624 T1, T2, Context))
2625 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00002626 } else if (!isa<FunctionTemplateDecl>(D))
2627 continue;
2628
2629 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00002630 }
2631 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002632}
Douglas Gregor546be3c2009-12-30 17:04:44 +00002633
2634//----------------------------------------------------------------------------
2635// Search for all visible declarations.
2636//----------------------------------------------------------------------------
2637VisibleDeclConsumer::~VisibleDeclConsumer() { }
2638
2639namespace {
2640
2641class ShadowContextRAII;
2642
2643class VisibleDeclsRecord {
2644public:
2645 /// \brief An entry in the shadow map, which is optimized to store a
2646 /// single declaration (the common case) but can also store a list
2647 /// of declarations.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002648 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002649
2650private:
2651 /// \brief A mapping from declaration names to the declarations that have
2652 /// this name within a particular scope.
2653 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2654
2655 /// \brief A list of shadow maps, which is used to model name hiding.
2656 std::list<ShadowMap> ShadowMaps;
2657
2658 /// \brief The declaration contexts we have already visited.
2659 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2660
2661 friend class ShadowContextRAII;
2662
2663public:
2664 /// \brief Determine whether we have already visited this context
2665 /// (and, if not, note that we are going to visit that context now).
2666 bool visitedContext(DeclContext *Ctx) {
2667 return !VisitedContexts.insert(Ctx);
2668 }
2669
Douglas Gregor8071e422010-08-15 06:18:01 +00002670 bool alreadyVisitedContext(DeclContext *Ctx) {
2671 return VisitedContexts.count(Ctx);
2672 }
2673
Douglas Gregor546be3c2009-12-30 17:04:44 +00002674 /// \brief Determine whether the given declaration is hidden in the
2675 /// current scope.
2676 ///
2677 /// \returns the declaration that hides the given declaration, or
2678 /// NULL if no such declaration exists.
2679 NamedDecl *checkHidden(NamedDecl *ND);
2680
2681 /// \brief Add a declaration to the current shadow map.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002682 void add(NamedDecl *ND) {
2683 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2684 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002685};
2686
2687/// \brief RAII object that records when we've entered a shadow context.
2688class ShadowContextRAII {
2689 VisibleDeclsRecord &Visible;
2690
2691 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2692
2693public:
2694 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2695 Visible.ShadowMaps.push_back(ShadowMap());
2696 }
2697
2698 ~ShadowContextRAII() {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002699 Visible.ShadowMaps.pop_back();
2700 }
2701};
2702
2703} // end anonymous namespace
2704
Douglas Gregor546be3c2009-12-30 17:04:44 +00002705NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002706 // Look through using declarations.
2707 ND = ND->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002708
Douglas Gregor546be3c2009-12-30 17:04:44 +00002709 unsigned IDNS = ND->getIdentifierNamespace();
2710 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2711 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2712 SM != SMEnd; ++SM) {
2713 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2714 if (Pos == SM->end())
2715 continue;
2716
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002717 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00002718 IEnd = Pos->second.end();
2719 I != IEnd; ++I) {
2720 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002721 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002722 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor546be3c2009-12-30 17:04:44 +00002723 Decl::IDNS_ObjCProtocol)))
2724 continue;
2725
2726 // Protocols are in distinct namespaces from everything else.
2727 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2728 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2729 (*I)->getIdentifierNamespace() != IDNS)
2730 continue;
2731
Douglas Gregor0cc84042010-01-14 15:47:35 +00002732 // Functions and function templates in the same scope overload
2733 // rather than hide. FIXME: Look for hiding based on function
2734 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002735 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002736 ND->isFunctionOrFunctionTemplate() &&
2737 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002738 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002739
Douglas Gregor546be3c2009-12-30 17:04:44 +00002740 // We've found a declaration that hides this one.
2741 return *I;
2742 }
2743 }
2744
2745 return 0;
2746}
2747
2748static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2749 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002750 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002751 VisibleDeclConsumer &Consumer,
2752 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00002753 if (!Ctx)
2754 return;
2755
Douglas Gregor546be3c2009-12-30 17:04:44 +00002756 // Make sure we don't visit the same context twice.
2757 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2758 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002759
Douglas Gregor4923aa22010-07-02 20:37:36 +00002760 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2761 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2762
Douglas Gregor546be3c2009-12-30 17:04:44 +00002763 // Enumerate all of the results in this context.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00002764 llvm::SmallVector<DeclContext *, 2> Contexts;
2765 Ctx->collectAllContexts(Contexts);
2766 for (unsigned I = 0, N = Contexts.size(); I != N; ++I) {
2767 DeclContext *CurCtx = Contexts[I];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002768 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00002769 DEnd = CurCtx->decls_end();
2770 D != DEnd; ++D) {
Douglas Gregor70c23352010-12-09 21:44:02 +00002771 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) {
Douglas Gregor55368912011-12-14 16:03:29 +00002772 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00002773 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002774 Visited.add(ND);
2775 }
Douglas Gregor70c23352010-12-09 21:44:02 +00002776 }
Douglas Gregord98abd82011-02-16 01:39:26 +00002777
Sebastian Redl410c4f22010-08-31 20:53:31 +00002778 // Visit transparent contexts and inline namespaces inside this context.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002779 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
Sebastian Redl410c4f22010-08-31 20:53:31 +00002780 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Douglas Gregor0cc84042010-01-14 15:47:35 +00002781 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002782 Consumer, Visited);
2783 }
2784 }
2785 }
2786
2787 // Traverse using directives for qualified name lookup.
2788 if (QualifiedNameLookup) {
2789 ShadowContextRAII Shadow(Visited);
2790 DeclContext::udir_iterator I, E;
2791 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002792 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002793 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002794 }
2795 }
2796
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002797 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002798 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00002799 if (!Record->hasDefinition())
2800 return;
2801
Douglas Gregor546be3c2009-12-30 17:04:44 +00002802 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2803 BEnd = Record->bases_end();
2804 B != BEnd; ++B) {
2805 QualType BaseType = B->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002806
Douglas Gregor546be3c2009-12-30 17:04:44 +00002807 // Don't look into dependent bases, because name lookup can't look
2808 // there anyway.
2809 if (BaseType->isDependentType())
2810 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002811
Douglas Gregor546be3c2009-12-30 17:04:44 +00002812 const RecordType *Record = BaseType->getAs<RecordType>();
2813 if (!Record)
2814 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002815
Douglas Gregor546be3c2009-12-30 17:04:44 +00002816 // FIXME: It would be nice to be able to determine whether referencing
2817 // a particular member would be ambiguous. For example, given
2818 //
2819 // struct A { int member; };
2820 // struct B { int member; };
2821 // struct C : A, B { };
2822 //
2823 // void f(C *c) { c->### }
2824 //
2825 // accessing 'member' would result in an ambiguity. However, we
2826 // could be smart enough to qualify the member with the base
2827 // class, e.g.,
2828 //
2829 // c->B::member
2830 //
2831 // or
2832 //
2833 // c->A::member
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002834
Douglas Gregor546be3c2009-12-30 17:04:44 +00002835 // Find results in this base class (and its bases).
2836 ShadowContextRAII Shadow(Visited);
2837 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002838 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002839 }
2840 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002841
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002842 // Traverse the contexts of Objective-C classes.
2843 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2844 // Traverse categories.
2845 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2846 Category; Category = Category->getNextClassCategory()) {
2847 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002848 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002849 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002850 }
2851
2852 // Traverse protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00002853 for (ObjCInterfaceDecl::all_protocol_iterator
2854 I = IFace->all_referenced_protocol_begin(),
2855 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002856 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002857 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002858 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002859 }
2860
2861 // Traverse the superclass.
2862 if (IFace->getSuperClass()) {
2863 ShadowContextRAII Shadow(Visited);
2864 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002865 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002866 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002867
Douglas Gregorc220a182010-04-19 18:02:19 +00002868 // If there is an implementation, traverse it. We do this to find
2869 // synthesized ivars.
2870 if (IFace->getImplementation()) {
2871 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002872 LookupVisibleDecls(IFace->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00002873 QualifiedNameLookup, true, Consumer, Visited);
2874 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002875 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2876 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2877 E = Protocol->protocol_end(); I != E; ++I) {
2878 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002879 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002880 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002881 }
2882 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2883 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2884 E = Category->protocol_end(); I != E; ++I) {
2885 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002886 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002887 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002888 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002889
Douglas Gregorc220a182010-04-19 18:02:19 +00002890 // If there is an implementation, traverse it.
2891 if (Category->getImplementation()) {
2892 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002893 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00002894 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002895 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002896 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002897}
2898
2899static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2900 UnqualUsingDirectiveSet &UDirs,
2901 VisibleDeclConsumer &Consumer,
2902 VisibleDeclsRecord &Visited) {
2903 if (!S)
2904 return;
2905
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002906 if (!S->getEntity() ||
2907 (!S->getParent() &&
Douglas Gregor8071e422010-08-15 06:18:01 +00002908 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor539c5c32010-01-07 00:31:29 +00002909 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2910 // Walk through the declarations in this Scope.
2911 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2912 D != DEnd; ++D) {
John McCalld226f652010-08-21 09:40:31 +00002913 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor55368912011-12-14 16:03:29 +00002914 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00002915 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002916 Visited.add(ND);
2917 }
2918 }
2919 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002920
Douglas Gregor711be1e2010-03-15 14:33:29 +00002921 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00002922 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00002923 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002924 // Look into this scope's declaration context, along with any of its
2925 // parent lookup contexts (e.g., enclosing classes), up to the point
2926 // where we hit the context stored in the next outer scope.
2927 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00002928 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002929
Douglas Gregordbdf5e72010-03-15 15:26:48 +00002930 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002931 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002932 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2933 if (Method->isInstanceMethod()) {
2934 // For instance methods, look for ivars in the method's interface.
2935 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2936 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregorca45da02010-11-02 20:36:02 +00002937 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002938 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Fariborz Jahanian8697d302011-08-31 22:24:06 +00002939 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorca45da02010-11-02 20:36:02 +00002940 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002941 }
2942
2943 // We've already performed all of the name lookup that we need
2944 // to for Objective-C methods; the next context will be the
2945 // outer scope.
2946 break;
2947 }
2948
Douglas Gregor546be3c2009-12-30 17:04:44 +00002949 if (Ctx->isFunctionOrMethod())
2950 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002951
2952 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002953 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002954 }
2955 } else if (!S->getParent()) {
2956 // Look into the translation unit scope. We walk through the translation
2957 // unit's declaration context, because the Scope itself won't have all of
2958 // the declarations if we loaded a precompiled header.
2959 // FIXME: We would like the translation unit's Scope object to point to the
2960 // translation unit, so we don't need this special "if" branch. However,
2961 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002962 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002963 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00002964 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002965 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002966 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002967 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002968 }
2969
Douglas Gregor546be3c2009-12-30 17:04:44 +00002970 if (Entity) {
2971 // Lookup visible declarations in any namespaces found by using
2972 // directives.
2973 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2974 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2975 for (; UI != UEnd; ++UI)
2976 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002977 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002978 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002979 }
2980
2981 // Lookup names in the parent scope.
2982 ShadowContextRAII Shadow(Visited);
2983 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2984}
2985
2986void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00002987 VisibleDeclConsumer &Consumer,
2988 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002989 // Determine the set of using directives available during
2990 // unqualified name lookup.
2991 Scope *Initial = S;
2992 UnqualUsingDirectiveSet UDirs;
2993 if (getLangOptions().CPlusPlus) {
2994 // Find the first namespace or translation-unit scope.
2995 while (S && !isNamespaceOrTranslationUnitScope(S))
2996 S = S->getParent();
2997
2998 UDirs.visitScopeChain(Initial, S);
2999 }
3000 UDirs.done();
3001
3002 // Look for visible declarations.
3003 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3004 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003005 if (!IncludeGlobalScope)
3006 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003007 ShadowContextRAII Shadow(Visited);
3008 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3009}
3010
3011void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00003012 VisibleDeclConsumer &Consumer,
3013 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003014 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3015 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003016 if (!IncludeGlobalScope)
3017 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003018 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003019 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003020 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003021}
3022
Chris Lattner4ae493c2011-02-18 02:08:43 +00003023/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara67843042011-03-05 18:21:20 +00003024/// If GnuLabelLoc is a valid source location, then this is a definition
3025/// of an __label__ label name, otherwise it is a normal label definition
3026/// or use.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003027LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara67843042011-03-05 18:21:20 +00003028 SourceLocation GnuLabelLoc) {
Chris Lattner337e5502011-02-18 01:27:55 +00003029 // Do a lookup to see if we have a label with this name already.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003030 NamedDecl *Res = 0;
Abramo Bagnara67843042011-03-05 18:21:20 +00003031
3032 if (GnuLabelLoc.isValid()) {
3033 // Local label definitions always shadow existing labels.
3034 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3035 Scope *S = CurScope;
3036 PushOnScopeChains(Res, S, true);
3037 return cast<LabelDecl>(Res);
3038 }
3039
3040 // Not a GNU local label.
3041 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3042 // If we found a label, check to see if it is in the same context as us.
3043 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattner337e5502011-02-18 01:27:55 +00003044 if (Res && Res->getDeclContext() != CurContext)
3045 Res = 0;
Chris Lattner337e5502011-02-18 01:27:55 +00003046 if (Res == 0) {
3047 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara67843042011-03-05 18:21:20 +00003048 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3049 Scope *S = CurScope->getFnParent();
Chris Lattnerfebb5b82011-02-18 21:16:39 +00003050 assert(S && "Not in a function?");
3051 PushOnScopeChains(Res, S, true);
Chris Lattner337e5502011-02-18 01:27:55 +00003052 }
Chris Lattner337e5502011-02-18 01:27:55 +00003053 return cast<LabelDecl>(Res);
3054}
3055
3056//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003057// Typo correction
Chris Lattner337e5502011-02-18 01:27:55 +00003058//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003059
3060namespace {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003061
3062typedef llvm::StringMap<TypoCorrection, llvm::BumpPtrAllocator> TypoResultsMap;
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003063typedef std::map<unsigned, TypoResultsMap *> TypoEditDistanceMap;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003064
3065static const unsigned MaxTypoDistanceResultSets = 5;
3066
Douglas Gregor546be3c2009-12-30 17:04:44 +00003067class TypoCorrectionConsumer : public VisibleDeclConsumer {
3068 /// \brief The name written that is a typo in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003069 StringRef Typo;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003070
3071 /// \brief The results found that have the smallest edit distance
3072 /// found (so far) with the typo name.
Douglas Gregore24b5752010-10-14 20:34:08 +00003073 ///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003074 /// The pointer value being set to the current DeclContext indicates
3075 /// whether there is a keyword with this name.
3076 TypoEditDistanceMap BestResults;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003077
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003078 Sema &SemaRef;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003079
Douglas Gregor546be3c2009-12-30 17:04:44 +00003080public:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003081 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003082 : Typo(Typo->getName()),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003083 SemaRef(SemaRef) { }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003084
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003085 ~TypoCorrectionConsumer() {
3086 for (TypoEditDistanceMap::iterator I = BestResults.begin(),
3087 IEnd = BestResults.end();
3088 I != IEnd;
3089 ++I)
3090 delete I->second;
3091 }
3092
Erik Verbruggend1205962011-10-06 07:27:49 +00003093 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3094 bool InBaseClass);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003095 void FoundName(StringRef Name);
3096 void addKeywordResult(StringRef Keyword);
3097 void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003098 NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003099 void addCorrection(TypoCorrection Correction);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003100
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003101 typedef TypoResultsMap::iterator result_iterator;
3102 typedef TypoEditDistanceMap::iterator distance_iterator;
3103 distance_iterator begin() { return BestResults.begin(); }
3104 distance_iterator end() { return BestResults.end(); }
3105 void erase(distance_iterator I) { BestResults.erase(I); }
Douglas Gregore24b5752010-10-14 20:34:08 +00003106 unsigned size() const { return BestResults.size(); }
3107 bool empty() const { return BestResults.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003108
Chris Lattner5f9e2722011-07-23 10:55:15 +00003109 TypoCorrection &operator[](StringRef Name) {
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003110 return (*BestResults.begin()->second)[Name];
Douglas Gregor7b824e82010-10-15 13:35:25 +00003111 }
3112
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003113 unsigned getBestEditDistance(bool Normalized) {
3114 if (BestResults.empty())
3115 return (std::numeric_limits<unsigned>::max)();
3116
3117 unsigned BestED = BestResults.begin()->first;
3118 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003119 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003120};
3121
3122}
3123
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003124void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggend1205962011-10-06 07:27:49 +00003125 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003126 // Don't consider hidden names for typo correction.
3127 if (Hiding)
3128 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003129
Douglas Gregor546be3c2009-12-30 17:04:44 +00003130 // Only consider entities with identifiers for names, ignoring
3131 // special names (constructors, overloaded operators, selectors,
3132 // etc.).
3133 IdentifierInfo *Name = ND->getIdentifier();
3134 if (!Name)
3135 return;
3136
Douglas Gregor95f42922010-10-14 22:11:03 +00003137 FoundName(Name->getName());
3138}
3139
Chris Lattner5f9e2722011-07-23 10:55:15 +00003140void TypoCorrectionConsumer::FoundName(StringRef Name) {
Douglas Gregor362a8f22010-10-19 19:39:10 +00003141 // Use a simple length-based heuristic to determine the minimum possible
3142 // edit distance. If the minimum isn't good enough, bail out early.
3143 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003144 if (MinED && Typo.size() / MinED < 3)
Douglas Gregor362a8f22010-10-19 19:39:10 +00003145 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003146
Douglas Gregora1194772010-10-19 22:14:33 +00003147 // Compute an upper bound on the allowable edit distance, so that the
3148 // edit-distance algorithm can short-circuit.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003149 unsigned UpperBound = (Typo.size() + 2) / 3;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003150
Douglas Gregor546be3c2009-12-30 17:04:44 +00003151 // Compute the edit distance between the typo and the name of this
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003152 // entity, and add the identifier to the list of results.
3153 addName(Name, NULL, Typo.edit_distance(Name, true, UpperBound));
Douglas Gregor546be3c2009-12-30 17:04:44 +00003154}
3155
Chris Lattner5f9e2722011-07-23 10:55:15 +00003156void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003157 // Compute the edit distance between the typo and this keyword,
3158 // and add the keyword to the list of results.
3159 addName(Keyword, NULL, Typo.edit_distance(Keyword), NULL, true);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003160}
3161
Chris Lattner5f9e2722011-07-23 10:55:15 +00003162void TypoCorrectionConsumer::addName(StringRef Name,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003163 NamedDecl *ND,
3164 unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003165 NestedNameSpecifier *NNS,
3166 bool isKeyword) {
3167 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
3168 if (isKeyword) TC.makeKeyword();
3169 addCorrection(TC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003170}
3171
3172void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003173 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003174 TypoResultsMap *& Map = BestResults[Correction.getEditDistance(false)];
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003175 if (!Map)
3176 Map = new TypoResultsMap;
Chandler Carruth55620532011-06-28 22:48:40 +00003177
3178 TypoCorrection &CurrentCorrection = (*Map)[Name];
3179 if (!CurrentCorrection ||
3180 // FIXME: The following should be rolled up into an operator< on
3181 // TypoCorrection with a more principled definition.
3182 CurrentCorrection.isKeyword() < Correction.isKeyword() ||
3183 Correction.getAsString(SemaRef.getLangOptions()) <
3184 CurrentCorrection.getAsString(SemaRef.getLangOptions()))
3185 CurrentCorrection = Correction;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003186
3187 while (BestResults.size() > MaxTypoDistanceResultSets) {
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003188 TypoEditDistanceMap::iterator Last = BestResults.end();
3189 --Last;
3190 delete Last->second;
3191 BestResults.erase(Last);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003192 }
3193}
3194
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003195// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3196// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3197// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3198static void getNestedNameSpecifierIdentifiers(
3199 NestedNameSpecifier *NNS,
3200 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3201 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3202 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3203 else
3204 Identifiers.clear();
3205
3206 const IdentifierInfo *II = NULL;
3207
3208 switch (NNS->getKind()) {
3209 case NestedNameSpecifier::Identifier:
3210 II = NNS->getAsIdentifier();
3211 break;
3212
3213 case NestedNameSpecifier::Namespace:
3214 if (NNS->getAsNamespace()->isAnonymousNamespace())
3215 return;
3216 II = NNS->getAsNamespace()->getIdentifier();
3217 break;
3218
3219 case NestedNameSpecifier::NamespaceAlias:
3220 II = NNS->getAsNamespaceAlias()->getIdentifier();
3221 break;
3222
3223 case NestedNameSpecifier::TypeSpecWithTemplate:
3224 case NestedNameSpecifier::TypeSpec:
3225 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3226 break;
3227
3228 case NestedNameSpecifier::Global:
3229 return;
3230 }
3231
3232 if (II)
3233 Identifiers.push_back(II);
3234}
3235
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003236namespace {
3237
3238class SpecifierInfo {
3239 public:
3240 DeclContext* DeclCtx;
3241 NestedNameSpecifier* NameSpecifier;
3242 unsigned EditDistance;
3243
3244 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3245 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3246};
3247
Chris Lattner5f9e2722011-07-23 10:55:15 +00003248typedef SmallVector<DeclContext*, 4> DeclContextList;
3249typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003250
3251class NamespaceSpecifierSet {
3252 ASTContext &Context;
3253 DeclContextList CurContextChain;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003254 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3255 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003256 bool isSorted;
3257
3258 SpecifierInfoList Specifiers;
3259 llvm::SmallSetVector<unsigned, 4> Distances;
3260 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3261
3262 /// \brief Helper for building the list of DeclContexts between the current
3263 /// context and the top of the translation unit
3264 static DeclContextList BuildContextChain(DeclContext *Start);
3265
3266 void SortNamespaces();
3267
3268 public:
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003269 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3270 CXXScopeSpec *CurScopeSpec)
Benjamin Kramerc5bb9d42011-07-05 09:46:31 +00003271 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003272 isSorted(true) {
3273 if (CurScopeSpec && CurScopeSpec->getScopeRep())
3274 getNestedNameSpecifierIdentifiers(CurScopeSpec->getScopeRep(),
3275 CurNameSpecifierIdentifiers);
3276 // Build the list of identifiers that would be used for an absolute
3277 // (from the global context) NestedNameSpecifier refering to the current
3278 // context.
3279 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3280 CEnd = CurContextChain.rend();
3281 C != CEnd; ++C) {
3282 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3283 CurContextIdentifiers.push_back(ND->getIdentifier());
3284 }
3285 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003286
3287 /// \brief Add the namespace to the set, computing the corresponding
3288 /// NestedNameSpecifier and its distance in the process.
3289 void AddNamespace(NamespaceDecl *ND);
3290
3291 typedef SpecifierInfoList::iterator iterator;
3292 iterator begin() {
3293 if (!isSorted) SortNamespaces();
3294 return Specifiers.begin();
3295 }
3296 iterator end() { return Specifiers.end(); }
3297};
3298
3299}
3300
3301DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003302 assert(Start && "Bulding a context chain from a null context");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003303 DeclContextList Chain;
3304 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3305 DC = DC->getLookupParent()) {
3306 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3307 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3308 !(ND && ND->isAnonymousNamespace()))
3309 Chain.push_back(DC->getPrimaryContext());
3310 }
3311 return Chain;
3312}
3313
3314void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003315 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003316 sortedDistances.append(Distances.begin(), Distances.end());
3317
3318 if (sortedDistances.size() > 1)
3319 std::sort(sortedDistances.begin(), sortedDistances.end());
3320
3321 Specifiers.clear();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003322 for (SmallVector<unsigned, 4>::iterator DI = sortedDistances.begin(),
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003323 DIEnd = sortedDistances.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003324 DI != DIEnd; ++DI) {
3325 SpecifierInfoList &SpecList = DistanceMap[*DI];
3326 Specifiers.append(SpecList.begin(), SpecList.end());
3327 }
3328
3329 isSorted = true;
3330}
3331
3332void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003333 DeclContext *Ctx = cast<DeclContext>(ND);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003334 NestedNameSpecifier *NNS = NULL;
3335 unsigned NumSpecifiers = 0;
3336 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003337 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003338
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003339 // Eliminate common elements from the two DeclContext chains.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003340 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3341 CEnd = CurContextChain.rend();
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003342 C != CEnd && !NamespaceDeclChain.empty() &&
3343 NamespaceDeclChain.back() == *C; ++C) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003344 NamespaceDeclChain.pop_back();
3345 }
3346
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003347 // Add an explicit leading '::' specifier if needed.
3348 if (NamespaceDecl *ND =
Kaelyn Uhrain3ad02aa2012-02-15 22:59:03 +00003349 NamespaceDeclChain.empty() ? NULL :
3350 dyn_cast_or_null<NamespaceDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003351 IdentifierInfo *Name = ND->getIdentifier();
3352 if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3353 Name) != CurContextIdentifiers.end() ||
3354 std::find(CurNameSpecifierIdentifiers.begin(),
3355 CurNameSpecifierIdentifiers.end(),
3356 Name) != CurNameSpecifierIdentifiers.end()) {
3357 NamespaceDeclChain = FullNamespaceDeclChain;
3358 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3359 }
3360 }
3361
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003362 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3363 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3364 CEnd = NamespaceDeclChain.rend();
3365 C != CEnd; ++C) {
3366 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3367 if (ND) {
3368 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3369 ++NumSpecifiers;
3370 }
3371 }
3372
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003373 // If the built NestedNameSpecifier would be replacing an existing
3374 // NestedNameSpecifier, use the number of component identifiers that
3375 // would need to be changed as the edit distance instead of the number
3376 // of components in the built NestedNameSpecifier.
3377 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3378 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3379 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3380 NumSpecifiers = llvm::ComputeEditDistance(
3381 llvm::ArrayRef<const IdentifierInfo*>(CurNameSpecifierIdentifiers),
3382 llvm::ArrayRef<const IdentifierInfo*>(NewNameSpecifierIdentifiers));
3383 }
3384
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003385 isSorted = false;
3386 Distances.insert(NumSpecifiers);
3387 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
Douglas Gregoraaf87162010-04-14 20:04:41 +00003388}
3389
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003390/// \brief Perform name lookup for a possible result for typo correction.
3391static void LookupPotentialTypoResult(Sema &SemaRef,
3392 LookupResult &Res,
3393 IdentifierInfo *Name,
3394 Scope *S, CXXScopeSpec *SS,
3395 DeclContext *MemberContext,
3396 bool EnteringContext,
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003397 bool isObjCIvarLookup) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003398 Res.suppressDiagnostics();
3399 Res.clear();
3400 Res.setLookupName(Name);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003401 if (MemberContext) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003402 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003403 if (isObjCIvarLookup) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003404 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3405 Res.addDecl(Ivar);
3406 Res.resolveKind();
3407 return;
3408 }
3409 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003410
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003411 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3412 Res.addDecl(Prop);
3413 Res.resolveKind();
3414 return;
3415 }
3416 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003417
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003418 SemaRef.LookupQualifiedName(Res, MemberContext);
3419 return;
3420 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003421
3422 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003423 EnteringContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003424
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003425 // Fake ivar lookup; this should really be part of
3426 // LookupParsedName.
3427 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3428 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003429 (Res.empty() ||
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003430 (Res.isSingleResult() &&
3431 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003432 if (ObjCIvarDecl *IV
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003433 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3434 Res.addDecl(IV);
3435 Res.resolveKind();
3436 }
3437 }
3438 }
3439}
3440
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003441/// \brief Add keywords to the consumer as possible typo corrections.
3442static void AddKeywordsToConsumer(Sema &SemaRef,
3443 TypoCorrectionConsumer &Consumer,
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003444 Scope *S, CorrectionCandidateCallback &CCC) {
3445 if (CCC.WantObjCSuper)
3446 Consumer.addKeywordResult("super");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003447
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003448 if (CCC.WantTypeSpecifiers) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003449 // Add type-specifier keywords to the set of results.
3450 const char *CTypeSpecs[] = {
3451 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor07f4a062011-07-01 21:27:45 +00003452 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003453 "_Complex", "_Imaginary",
3454 // storage-specifiers as well
3455 "extern", "inline", "static", "typedef"
3456 };
3457
3458 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3459 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3460 Consumer.addKeywordResult(CTypeSpecs[I]);
3461
3462 if (SemaRef.getLangOptions().C99)
3463 Consumer.addKeywordResult("restrict");
3464 if (SemaRef.getLangOptions().Bool || SemaRef.getLangOptions().CPlusPlus)
3465 Consumer.addKeywordResult("bool");
Douglas Gregor07f4a062011-07-01 21:27:45 +00003466 else if (SemaRef.getLangOptions().C99)
3467 Consumer.addKeywordResult("_Bool");
3468
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003469 if (SemaRef.getLangOptions().CPlusPlus) {
3470 Consumer.addKeywordResult("class");
3471 Consumer.addKeywordResult("typename");
3472 Consumer.addKeywordResult("wchar_t");
3473
3474 if (SemaRef.getLangOptions().CPlusPlus0x) {
3475 Consumer.addKeywordResult("char16_t");
3476 Consumer.addKeywordResult("char32_t");
3477 Consumer.addKeywordResult("constexpr");
3478 Consumer.addKeywordResult("decltype");
3479 Consumer.addKeywordResult("thread_local");
3480 }
3481 }
3482
3483 if (SemaRef.getLangOptions().GNUMode)
3484 Consumer.addKeywordResult("typeof");
3485 }
3486
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003487 if (CCC.WantCXXNamedCasts && SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003488 Consumer.addKeywordResult("const_cast");
3489 Consumer.addKeywordResult("dynamic_cast");
3490 Consumer.addKeywordResult("reinterpret_cast");
3491 Consumer.addKeywordResult("static_cast");
3492 }
3493
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003494 if (CCC.WantExpressionKeywords) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003495 Consumer.addKeywordResult("sizeof");
3496 if (SemaRef.getLangOptions().Bool || SemaRef.getLangOptions().CPlusPlus) {
3497 Consumer.addKeywordResult("false");
3498 Consumer.addKeywordResult("true");
3499 }
3500
3501 if (SemaRef.getLangOptions().CPlusPlus) {
3502 const char *CXXExprs[] = {
3503 "delete", "new", "operator", "throw", "typeid"
3504 };
3505 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3506 for (unsigned I = 0; I != NumCXXExprs; ++I)
3507 Consumer.addKeywordResult(CXXExprs[I]);
3508
3509 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3510 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3511 Consumer.addKeywordResult("this");
3512
3513 if (SemaRef.getLangOptions().CPlusPlus0x) {
3514 Consumer.addKeywordResult("alignof");
3515 Consumer.addKeywordResult("nullptr");
3516 }
3517 }
3518 }
3519
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003520 if (CCC.WantRemainingKeywords) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003521 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3522 // Statements.
3523 const char *CStmts[] = {
3524 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3525 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3526 for (unsigned I = 0; I != NumCStmts; ++I)
3527 Consumer.addKeywordResult(CStmts[I]);
3528
3529 if (SemaRef.getLangOptions().CPlusPlus) {
3530 Consumer.addKeywordResult("catch");
3531 Consumer.addKeywordResult("try");
3532 }
3533
3534 if (S && S->getBreakParent())
3535 Consumer.addKeywordResult("break");
3536
3537 if (S && S->getContinueParent())
3538 Consumer.addKeywordResult("continue");
3539
3540 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3541 Consumer.addKeywordResult("case");
3542 Consumer.addKeywordResult("default");
3543 }
3544 } else {
3545 if (SemaRef.getLangOptions().CPlusPlus) {
3546 Consumer.addKeywordResult("namespace");
3547 Consumer.addKeywordResult("template");
3548 }
3549
3550 if (S && S->isClassScope()) {
3551 Consumer.addKeywordResult("explicit");
3552 Consumer.addKeywordResult("friend");
3553 Consumer.addKeywordResult("mutable");
3554 Consumer.addKeywordResult("private");
3555 Consumer.addKeywordResult("protected");
3556 Consumer.addKeywordResult("public");
3557 Consumer.addKeywordResult("virtual");
3558 }
3559 }
3560
3561 if (SemaRef.getLangOptions().CPlusPlus) {
3562 Consumer.addKeywordResult("using");
3563
3564 if (SemaRef.getLangOptions().CPlusPlus0x)
3565 Consumer.addKeywordResult("static_assert");
3566 }
3567 }
3568}
3569
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003570static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3571 TypoCorrection &Candidate) {
3572 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3573 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3574}
3575
Douglas Gregor546be3c2009-12-30 17:04:44 +00003576/// \brief Try to "correct" a typo in the source code by finding
3577/// visible declarations whose names are similar to the name that was
3578/// present in the source code.
3579///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003580/// \param TypoName the \c DeclarationNameInfo structure that contains
3581/// the name that was present in the source code along with its location.
3582///
3583/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003584///
3585/// \param S the scope in which name lookup occurs.
3586///
3587/// \param SS the nested-name-specifier that precedes the name we're
3588/// looking for, if present.
3589///
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003590/// \param CCC A CorrectionCandidateCallback object that provides further
3591/// validation of typo correction candidates. It also provides flags for
3592/// determining the set of keywords permitted.
3593///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003594/// \param MemberContext if non-NULL, the context in which to look for
3595/// a member access expression.
3596///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003597/// \param EnteringContext whether we're entering the context described by
Douglas Gregorbb092ba2009-12-31 05:20:13 +00003598/// the nested-name-specifier SS.
3599///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003600/// \param OPT when non-NULL, the search for visible declarations will
3601/// also walk the protocols in the qualified interfaces of \p OPT.
3602///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003603/// \returns a \c TypoCorrection containing the corrected name if the typo
3604/// along with information such as the \c NamedDecl where the corrected name
3605/// was declared, and any additional \c NestedNameSpecifier needed to access
3606/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3607TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3608 Sema::LookupNameKind LookupKind,
3609 Scope *S, CXXScopeSpec *SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00003610 CorrectionCandidateCallback &CCC,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003611 DeclContext *MemberContext,
3612 bool EnteringContext,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003613 const ObjCObjectPointerType *OPT) {
Douglas Gregora0068fc2010-07-09 17:35:33 +00003614 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003615 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003616
Francois Pichet4d604d62011-12-03 15:55:29 +00003617 // In Microsoft mode, don't perform typo correction in a template member
3618 // function dependent context because it interferes with the "lookup into
3619 // dependent bases of class templates" feature.
3620 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
3621 isa<CXXMethodDecl>(CurContext))
3622 return TypoCorrection();
3623
Douglas Gregor546be3c2009-12-30 17:04:44 +00003624 // We only attempt to correct typos for identifiers.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003625 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003626 if (!Typo)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003627 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003628
3629 // If the scope specifier itself was invalid, don't try to correct
3630 // typos.
3631 if (SS && SS->isInvalid())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003632 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003633
3634 // Never try to correct typos during template deduction or
3635 // instantiation.
3636 if (!ActiveTemplateInstantiations.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003637 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003638
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003639 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003640
3641 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003642
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003643 // If a callback object considers an empty typo correction candidate to be
3644 // viable, assume it does not do any actual validation of the candidates.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003645 TypoCorrection EmptyCorrection;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003646 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003647
Douglas Gregoraaf87162010-04-14 20:04:41 +00003648 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003649 bool IsUnqualifiedLookup = false;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003650 DeclContext *QualifiedDC = MemberContext;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003651 if (MemberContext) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003652 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003653
3654 // Look in qualified interfaces.
3655 if (OPT) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003656 for (ObjCObjectPointerType::qual_iterator
3657 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003658 I != E; ++I)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003659 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003660 }
3661 } else if (SS && SS->isSet()) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003662 QualifiedDC = computeDeclContext(*SS, EnteringContext);
3663 if (!QualifiedDC)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003664 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003665
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003666 // Provide a stop gap for files that are just seriously broken. Trying
3667 // to correct all typos can turn into a HUGE performance penalty, causing
3668 // some files to take minutes to get rejected by the parser.
3669 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003670 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003671 ++TyposCorrected;
3672
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003673 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003674 } else {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003675 IsUnqualifiedLookup = true;
3676 UnqualifiedTyposCorrectedMap::iterator Cached
3677 = UnqualifiedTyposCorrected.find(Typo);
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003678 if (Cached != UnqualifiedTyposCorrected.end()) {
3679 // Add the cached value, unless it's a keyword or fails validation. In the
3680 // keyword case, we'll end up adding the keyword below.
3681 if (Cached->second) {
3682 if (!Cached->second.isKeyword() &&
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003683 isCandidateViable(CCC, Cached->second))
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003684 Consumer.addCorrection(Cached->second);
3685 } else {
3686 // Only honor no-correction cache hits when a callback that will validate
3687 // correction candidates is not being used.
3688 if (!ValidatingCallback)
3689 return TypoCorrection();
3690 }
3691 }
3692 if (Cached == UnqualifiedTyposCorrected.end()) {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003693 // Provide a stop gap for files that are just seriously broken. Trying
3694 // to correct all typos can turn into a HUGE performance penalty, causing
3695 // some files to take minutes to get rejected by the parser.
3696 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003697 return TypoCorrection();
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003698 }
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003699 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003700
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003701 if (IsUnqualifiedLookup || (QualifiedDC && QualifiedDC->isNamespace())) {
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003702 // For unqualified lookup, look through all of the names that we have
3703 // seen in this translation unit.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003704 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003705 for (IdentifierTable::iterator I = Context.Idents.begin(),
3706 IEnd = Context.Idents.end();
3707 I != IEnd; ++I)
3708 Consumer.FoundName(I->getKey());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003709
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003710 // Walk through identifiers in external identifier sources.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003711 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003712 if (IdentifierInfoLookup *External
3713 = Context.Idents.getExternalIdentifierLookup()) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00003714 OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003715 do {
3716 StringRef Name = Iter->Next();
3717 if (Name.empty())
3718 break;
Douglas Gregor95f42922010-10-14 22:11:03 +00003719
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003720 Consumer.FoundName(Name);
3721 } while (true);
Douglas Gregor95f42922010-10-14 22:11:03 +00003722 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003723 }
3724
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00003725 AddKeywordsToConsumer(*this, Consumer, S, CCC);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003726
Douglas Gregoraaf87162010-04-14 20:04:41 +00003727 // If we haven't found anything, we're done.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003728 if (Consumer.empty()) {
3729 // If this was an unqualified lookup, note that no correction was found.
3730 if (IsUnqualifiedLookup)
3731 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003732
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003733 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003734 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003735
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003736 // Make sure that the user typed at least 3 characters for each correction
Douglas Gregore24b5752010-10-14 20:34:08 +00003737 // made. Otherwise, we don't even both looking at the results.
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003738 unsigned ED = Consumer.getBestEditDistance(true);
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003739 if (ED > 0 && Typo->getName().size() / ED < 3) {
3740 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregor157a3ff2010-10-27 14:20:34 +00003741 if (IsUnqualifiedLookup)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003742 (void)UnqualifiedTyposCorrected[Typo];
3743
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003744 return TypoCorrection();
3745 }
3746
3747 // Build the NestedNameSpecifiers for the KnownNamespaces
3748 if (getLangOptions().CPlusPlus) {
3749 // Load any externally-known namespaces.
3750 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003751 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003752 LoadedExternalKnownNamespaces = true;
3753 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
3754 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
3755 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
3756 }
3757
3758 for (llvm::DenseMap<NamespaceDecl*, bool>::iterator
3759 KNI = KnownNamespaces.begin(),
3760 KNIEnd = KnownNamespaces.end();
3761 KNI != KNIEnd; ++KNI)
3762 Namespaces.AddNamespace(KNI->first);
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003763 }
Douglas Gregore24b5752010-10-14 20:34:08 +00003764
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003765 // Weed out any names that could not be found by name lookup or, if a
3766 // CorrectionCandidateCallback object was provided, failed validation.
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003767 llvm::SmallVector<TypoCorrection, 16> QualifiedResults;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003768 LookupResult TmpRes(*this, TypoName, LookupKind);
3769 TmpRes.suppressDiagnostics();
3770 while (!Consumer.empty()) {
3771 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3772 unsigned ED = DI->first;
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003773 for (TypoCorrectionConsumer::result_iterator I = DI->second->begin(),
3774 IEnd = DI->second->end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003775 I != IEnd; /* Increment in loop. */) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003776 // If the item already has been looked up or is a keyword, keep it.
3777 // If a validator callback object was given, drop the correction
3778 // unless it passes validation.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003779 if (I->second.isResolved()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003780 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003781 ++I;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003782 if (!isCandidateViable(CCC, Prev->second))
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003783 DI->second->erase(Prev);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003784 continue;
Douglas Gregore24b5752010-10-14 20:34:08 +00003785 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003786
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003787 // Perform name lookup on this name.
3788 IdentifierInfo *Name = I->second.getCorrectionAsIdentifierInfo();
3789 LookupPotentialTypoResult(*this, TmpRes, Name, S, SS, MemberContext,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00003790 EnteringContext, CCC.IsObjCIvarLookup);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003791
3792 switch (TmpRes.getResultKind()) {
3793 case LookupResult::NotFound:
3794 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00003795 case LookupResult::FoundUnresolvedValue:
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003796 QualifiedResults.push_back(I->second);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003797 // We didn't find this name in our scope, or didn't like what we found;
3798 // ignore it.
3799 {
3800 TypoCorrectionConsumer::result_iterator Next = I;
3801 ++Next;
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003802 DI->second->erase(I);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003803 I = Next;
3804 }
3805 break;
3806
3807 case LookupResult::Ambiguous:
3808 // We don't deal with ambiguities.
3809 return TypoCorrection();
3810
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003811 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003812 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003813 // Store all of the Decls for overloaded symbols
3814 for (LookupResult::iterator TRD = TmpRes.begin(),
3815 TRDEnd = TmpRes.end();
3816 TRD != TRDEnd; ++TRD)
3817 I->second.addCorrectionDecl(*TRD);
3818 ++I;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003819 if (!isCandidateViable(CCC, Prev->second))
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003820 DI->second->erase(Prev);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003821 break;
3822 }
3823
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003824 case LookupResult::Found: {
3825 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003826 I->second.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
3827 ++I;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003828 if (!isCandidateViable(CCC, Prev->second))
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003829 DI->second->erase(Prev);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003830 break;
3831 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003832
3833 }
Douglas Gregore24b5752010-10-14 20:34:08 +00003834 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003835
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003836 if (DI->second->empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003837 Consumer.erase(DI);
3838 else if (!getLangOptions().CPlusPlus || QualifiedResults.empty() || !ED)
3839 // If there are results in the closest possible bucket, stop
3840 break;
3841
3842 // Only perform the qualified lookups for C++
3843 if (getLangOptions().CPlusPlus) {
3844 TmpRes.suppressDiagnostics();
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003845 for (llvm::SmallVector<TypoCorrection,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003846 16>::iterator QRI = QualifiedResults.begin(),
3847 QRIEnd = QualifiedResults.end();
3848 QRI != QRIEnd; ++QRI) {
3849 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
3850 NIEnd = Namespaces.end();
3851 NI != NIEnd; ++NI) {
3852 DeclContext *Ctx = NI->DeclCtx;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003853
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003854 // FIXME: Stop searching once the namespaces are too far away to create
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003855 // acceptable corrections for this identifier (since the namespaces
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003856 // are sorted in ascending order by edit distance).
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003857
3858 TmpRes.clear();
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003859 TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003860 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
3861
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003862 // Any corrections added below will be validated in subsequent
3863 // iterations of the main while() loop over the Consumer's contents.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003864 switch (TmpRes.getResultKind()) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003865 case LookupResult::Found: {
3866 TypoCorrection TC(*QRI);
3867 TC.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
3868 TC.setCorrectionSpecifier(NI->NameSpecifier);
3869 TC.setQualifierDistance(NI->EditDistance);
3870 Consumer.addCorrection(TC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003871 break;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003872 }
3873 case LookupResult::FoundOverloaded: {
3874 TypoCorrection TC(*QRI);
3875 TC.setCorrectionSpecifier(NI->NameSpecifier);
3876 TC.setQualifierDistance(NI->EditDistance);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003877 for (LookupResult::iterator TRD = TmpRes.begin(),
3878 TRDEnd = TmpRes.end();
3879 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003880 TC.addCorrectionDecl(*TRD);
3881 Consumer.addCorrection(TC);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003882 break;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003883 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003884 case LookupResult::NotFound:
3885 case LookupResult::NotFoundInCurrentInstantiation:
3886 case LookupResult::Ambiguous:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00003887 case LookupResult::FoundUnresolvedValue:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003888 break;
3889 }
3890 }
3891 }
3892 }
3893
3894 QualifiedResults.clear();
3895 }
3896
3897 // No corrections remain...
3898 if (Consumer.empty()) return TypoCorrection();
3899
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003900 TypoResultsMap &BestResults = *Consumer.begin()->second;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003901 ED = TypoCorrection::NormalizeEditDistance(Consumer.begin()->first);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003902
3903 if (ED > 0 && Typo->getName().size() / ED < 3) {
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003904 // If this was an unqualified lookup and we believe the callback
3905 // object wouldn't have filtered out possible corrections, note
3906 // that no correction was found.
3907 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003908 (void)UnqualifiedTyposCorrected[Typo];
3909
3910 return TypoCorrection();
3911 }
3912
Douglas Gregore24b5752010-10-14 20:34:08 +00003913 // If only a single name remains, return that result.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003914 if (BestResults.size() == 1) {
3915 const llvm::StringMapEntry<TypoCorrection> &Correction = *(BestResults.begin());
3916 const TypoCorrection &Result = Correction.second;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003917
Douglas Gregor53e4b552010-10-26 17:18:00 +00003918 // Don't correct to a keyword that's the same as the typo; the keyword
3919 // wasn't actually in scope.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003920 if (ED == 0 && Result.isKeyword()) return TypoCorrection();
3921
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003922 // Record the correction for unqualified lookup.
3923 if (IsUnqualifiedLookup)
3924 UnqualifiedTyposCorrected[Typo] = Result;
3925
3926 return Result;
3927 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003928 else if (BestResults.size() > 1
3929 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
3930 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
3931 // some instances of CTC_Unknown, while WantRemainingKeywords is true
3932 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00003933 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003934 && BestResults["super"].isKeyword()) {
3935 // Prefer 'super' when we're completing in a message-receiver
3936 // context.
3937
3938 // Don't correct to a keyword that's the same as the typo; the keyword
3939 // wasn't actually in scope.
3940 if (ED == 0) return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003941
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003942 // Record the correction for unqualified lookup.
3943 if (IsUnqualifiedLookup)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003944 UnqualifiedTyposCorrected[Typo] = BestResults["super"];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003945
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003946 return BestResults["super"];
Douglas Gregor7b824e82010-10-15 13:35:25 +00003947 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003948
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003949 // If this was an unqualified lookup and we believe the callback object did
3950 // not filter out possible corrections, note that no correction was found.
3951 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003952 (void)UnqualifiedTyposCorrected[Typo];
3953
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003954 return TypoCorrection();
3955}
3956
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003957void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
3958 if (!CDecl) return;
3959
3960 if (isKeyword())
3961 CorrectionDecls.clear();
3962
3963 CorrectionDecls.push_back(CDecl);
3964
3965 if (!CorrectionName)
3966 CorrectionName = CDecl->getDeclName();
3967}
3968
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003969std::string TypoCorrection::getAsString(const LangOptions &LO) const {
3970 if (CorrectionNameSpec) {
3971 std::string tmpBuffer;
3972 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
3973 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
3974 return PrefixOStream.str() + CorrectionName.getAsString();
3975 }
3976
3977 return CorrectionName.getAsString();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003978}