blob: a5fc682d18c96052a30758704f03bff572b6939e [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 Gregoreb11cd02009-01-14 22:20:51 +000035#include "llvm/ADT/STLExtras.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000036#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregore24b5752010-10-14 20:34:08 +000037#include "llvm/ADT/StringMap.h"
Chris Lattnerb5f65472011-07-18 01:54:02 +000038#include "llvm/ADT/TinyPtrVector.h"
John McCall6e247262009-10-10 05:48:19 +000039#include "llvm/Support/ErrorHandling.h"
Douglas Gregore24b5752010-10-14 20:34:08 +000040#include <limits>
Douglas Gregor546be3c2009-12-30 17:04:44 +000041#include <list>
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +000042#include <set>
Douglas Gregor2a3009a2009-02-03 19:21:40 +000043#include <vector>
44#include <iterator>
45#include <utility>
46#include <algorithm>
Douglas Gregord8bba9c2011-06-28 16:20:02 +000047#include <map>
Douglas Gregoreb11cd02009-01-14 22:20:51 +000048
49using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000050using namespace sema;
Douglas Gregoreb11cd02009-01-14 22:20:51 +000051
John McCalld7be78a2009-11-10 07:01:13 +000052namespace {
53 class UnqualUsingEntry {
54 const DeclContext *Nominated;
55 const DeclContext *CommonAncestor;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000056
John McCalld7be78a2009-11-10 07:01:13 +000057 public:
58 UnqualUsingEntry(const DeclContext *Nominated,
59 const DeclContext *CommonAncestor)
60 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
61 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000062
John McCalld7be78a2009-11-10 07:01:13 +000063 const DeclContext *getCommonAncestor() const {
64 return CommonAncestor;
65 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000066
John McCalld7be78a2009-11-10 07:01:13 +000067 const DeclContext *getNominatedNamespace() const {
68 return Nominated;
69 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000070
John McCalld7be78a2009-11-10 07:01:13 +000071 // Sort by the pointer value of the common ancestor.
72 struct Comparator {
73 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
74 return L.getCommonAncestor() < R.getCommonAncestor();
75 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000076
John McCalld7be78a2009-11-10 07:01:13 +000077 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
78 return E.getCommonAncestor() < DC;
79 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000080
John McCalld7be78a2009-11-10 07:01:13 +000081 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
82 return DC < E.getCommonAncestor();
83 }
84 };
85 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +000086
John McCalld7be78a2009-11-10 07:01:13 +000087 /// A collection of using directives, as used by C++ unqualified
88 /// lookup.
89 class UnqualUsingDirectiveSet {
Chris Lattner5f9e2722011-07-23 10:55:15 +000090 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000091
John McCalld7be78a2009-11-10 07:01:13 +000092 ListTy list;
93 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000094
John McCalld7be78a2009-11-10 07:01:13 +000095 public:
96 UnqualUsingDirectiveSet() {}
Douglas Gregor2a3009a2009-02-03 19:21:40 +000097
John McCalld7be78a2009-11-10 07:01:13 +000098 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000099 // C++ [namespace.udir]p1:
John McCalld7be78a2009-11-10 07:01:13 +0000100 // During unqualified name lookup, the names appear as if they
101 // were declared in the nearest enclosing namespace which contains
102 // both the using-directive and the nominated namespace.
103 DeclContext *InnermostFileDC
104 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
105 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000106
John McCalld7be78a2009-11-10 07:01:13 +0000107 for (; S; S = S->getParent()) {
John McCalld7be78a2009-11-10 07:01:13 +0000108 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
109 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
110 visit(Ctx, EffectiveDC);
111 } else {
112 Scope::udir_iterator I = S->using_directives_begin(),
113 End = S->using_directives_end();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000114
John McCalld7be78a2009-11-10 07:01:13 +0000115 for (; I != End; ++I)
John McCalld226f652010-08-21 09:40:31 +0000116 visit(*I, InnermostFileDC);
John McCalld7be78a2009-11-10 07:01:13 +0000117 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000118 }
119 }
John McCalld7be78a2009-11-10 07:01:13 +0000120
121 // Visits a context and collect all of its using directives
122 // recursively. Treats all using directives as if they were
123 // declared in the context.
124 //
125 // A given context is only every visited once, so it is important
126 // that contexts be visited from the inside out in order to get
127 // the effective DCs right.
128 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
129 if (!visited.insert(DC))
130 return;
131
132 addUsingDirectives(DC, EffectiveDC);
133 }
134
135 // Visits a using directive and collects all of its using
136 // directives recursively. Treats all using directives as if they
137 // were declared in the effective DC.
138 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
139 DeclContext *NS = UD->getNominatedNamespace();
140 if (!visited.insert(NS))
141 return;
142
143 addUsingDirective(UD, EffectiveDC);
144 addUsingDirectives(NS, EffectiveDC);
145 }
146
147 // Adds all the using directives in a context (and those nominated
148 // by its using directives, transitively) as if they appeared in
149 // the given effective context.
150 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000151 SmallVector<DeclContext*,4> queue;
John McCalld7be78a2009-11-10 07:01:13 +0000152 while (true) {
153 DeclContext::udir_iterator I, End;
154 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
155 UsingDirectiveDecl *UD = *I;
156 DeclContext *NS = UD->getNominatedNamespace();
157 if (visited.insert(NS)) {
158 addUsingDirective(UD, EffectiveDC);
159 queue.push_back(NS);
160 }
161 }
162
163 if (queue.empty())
164 return;
165
166 DC = queue.back();
167 queue.pop_back();
168 }
169 }
170
171 // Add a using directive as if it had been declared in the given
172 // context. This helps implement C++ [namespace.udir]p3:
173 // The using-directive is transitive: if a scope contains a
174 // using-directive that nominates a second namespace that itself
175 // contains using-directives, the effect is as if the
176 // using-directives from the second namespace also appeared in
177 // the first.
178 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
179 // Find the common ancestor between the effective context and
180 // the nominated namespace.
181 DeclContext *Common = UD->getNominatedNamespace();
182 while (!Common->Encloses(EffectiveDC))
183 Common = Common->getParent();
John McCall12ea5782009-11-10 09:20:04 +0000184 Common = Common->getPrimaryContext();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000185
John McCalld7be78a2009-11-10 07:01:13 +0000186 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
187 }
188
189 void done() {
190 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
191 }
192
John McCalld7be78a2009-11-10 07:01:13 +0000193 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000194
John McCalld7be78a2009-11-10 07:01:13 +0000195 const_iterator begin() const { return list.begin(); }
196 const_iterator end() const { return list.end(); }
197
198 std::pair<const_iterator,const_iterator>
199 getNamespacesFor(DeclContext *DC) const {
John McCall12ea5782009-11-10 09:20:04 +0000200 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCalld7be78a2009-11-10 07:01:13 +0000201 UnqualUsingEntry::Comparator());
202 }
203 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000204}
205
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000206// Retrieve the set of identifier namespaces that correspond to a
207// specific kind of name lookup.
John McCall1d7c5282009-12-18 10:40:03 +0000208static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
209 bool CPlusPlus,
210 bool Redeclaration) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000211 unsigned IDNS = 0;
212 switch (NameKind) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +0000213 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000214 case Sema::LookupOrdinaryName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000215 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000216 IDNS = Decl::IDNS_Ordinary;
John McCall1d7c5282009-12-18 10:40:03 +0000217 if (CPlusPlus) {
John McCall0d6b1642010-04-23 18:46:30 +0000218 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattner337e5502011-02-18 01:27:55 +0000219 if (Redeclaration)
220 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCall1d7c5282009-12-18 10:40:03 +0000221 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000222 break;
223
John McCall76d32642010-04-24 01:30:58 +0000224 case Sema::LookupOperatorName:
225 // Operator lookup is its own crazy thing; it is not the same
226 // as (e.g.) looking up an operator name for redeclaration.
227 assert(!Redeclaration && "cannot do redeclaration operator lookup");
228 IDNS = Decl::IDNS_NonMemberOperator;
229 break;
230
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000231 case Sema::LookupTagName:
John McCall0d6b1642010-04-23 18:46:30 +0000232 if (CPlusPlus) {
233 IDNS = Decl::IDNS_Type;
234
235 // When looking for a redeclaration of a tag name, we add:
236 // 1) TagFriend to find undeclared friend decls
237 // 2) Namespace because they can't "overload" with tag decls.
238 // 3) Tag because it includes class templates, which can't
239 // "overload" with tag decls.
240 if (Redeclaration)
241 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
242 } else {
243 IDNS = Decl::IDNS_Tag;
244 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000245 break;
Chris Lattner337e5502011-02-18 01:27:55 +0000246 case Sema::LookupLabel:
247 IDNS = Decl::IDNS_Label;
248 break;
249
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000250 case Sema::LookupMemberName:
251 IDNS = Decl::IDNS_Member;
252 if (CPlusPlus)
Mike Stump1eb44332009-09-09 15:08:12 +0000253 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000254 break;
255
256 case Sema::LookupNestedNameSpecifierName:
John McCall0d6b1642010-04-23 18:46:30 +0000257 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
258 break;
259
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000260 case Sema::LookupNamespaceName:
John McCall0d6b1642010-04-23 18:46:30 +0000261 IDNS = Decl::IDNS_Namespace;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000262 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000263
John McCall9f54ad42009-12-10 09:41:52 +0000264 case Sema::LookupUsingDeclName:
265 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
266 | Decl::IDNS_Member | Decl::IDNS_Using;
267 break;
268
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000269 case Sema::LookupObjCProtocolName:
270 IDNS = Decl::IDNS_ObjCProtocol;
271 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000272
Douglas Gregor8071e422010-08-15 06:18:01 +0000273 case Sema::LookupAnyName:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000274 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor8071e422010-08-15 06:18:01 +0000275 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
276 | Decl::IDNS_Type;
277 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000278 }
279 return IDNS;
280}
281
John McCall1d7c5282009-12-18 10:40:03 +0000282void LookupResult::configure() {
Chris Lattner337e5502011-02-18 01:27:55 +0000283 IDNS = getIDNS(LookupKind, SemaRef.getLangOptions().CPlusPlus,
John McCall1d7c5282009-12-18 10:40:03 +0000284 isForRedeclaration());
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000285
286 // If we're looking for one of the allocation or deallocation
287 // operators, make sure that the implicitly-declared new and delete
288 // operators can be found.
289 if (!isForRedeclaration()) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000290 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000291 case OO_New:
292 case OO_Delete:
293 case OO_Array_New:
294 case OO_Array_Delete:
295 SemaRef.DeclareGlobalNewDelete();
296 break;
297
298 default:
299 break;
300 }
301 }
John McCall1d7c5282009-12-18 10:40:03 +0000302}
303
John McCall2a7fb272010-08-25 05:32:35 +0000304void LookupResult::sanity() const {
305 assert(ResultKind != NotFound || Decls.size() == 0);
306 assert(ResultKind != Found || Decls.size() == 1);
307 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
308 (Decls.size() == 1 &&
309 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
310 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
311 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorf17b58c2010-10-22 22:08:47 +0000312 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
313 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall2a7fb272010-08-25 05:32:35 +0000314 assert((Paths != NULL) == (ResultKind == Ambiguous &&
315 (Ambiguity == AmbiguousBaseSubobjectTypes ||
316 Ambiguity == AmbiguousBaseSubobjects)));
317}
John McCall2a7fb272010-08-25 05:32:35 +0000318
John McCallf36e02d2009-10-09 21:13:30 +0000319// Necessary because CXXBasePaths is not complete in Sema.h
John McCall7d384dd2009-11-18 07:57:50 +0000320void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCallf36e02d2009-10-09 21:13:30 +0000321 delete Paths;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000322}
323
Douglas Gregor55368912011-12-14 16:03:29 +0000324static NamedDecl *getVisibleDecl(NamedDecl *D);
325
326NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
327 return getVisibleDecl(D);
328}
329
John McCall7453ed42009-11-22 00:44:51 +0000330/// Resolves the result kind of this lookup.
John McCall7d384dd2009-11-18 07:57:50 +0000331void LookupResult::resolveKind() {
John McCallf36e02d2009-10-09 21:13:30 +0000332 unsigned N = Decls.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000333
John McCallf36e02d2009-10-09 21:13:30 +0000334 // Fast case: no possible ambiguity.
John McCall68263142009-11-18 22:49:29 +0000335 if (N == 0) {
John McCalldc5c7862010-01-15 21:27:01 +0000336 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall68263142009-11-18 22:49:29 +0000337 return;
338 }
339
John McCall7453ed42009-11-22 00:44:51 +0000340 // If there's a single decl, we need to examine it to decide what
341 // kind of lookup this is.
John McCall7ba107a2009-11-18 02:36:19 +0000342 if (N == 1) {
Douglas Gregor2b147f02010-04-25 21:15:30 +0000343 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
344 if (isa<FunctionTemplateDecl>(D))
John McCall7453ed42009-11-22 00:44:51 +0000345 ResultKind = FoundOverloaded;
Douglas Gregor2b147f02010-04-25 21:15:30 +0000346 else if (isa<UnresolvedUsingValueDecl>(D))
John McCall7ba107a2009-11-18 02:36:19 +0000347 ResultKind = FoundUnresolvedValue;
348 return;
349 }
John McCallf36e02d2009-10-09 21:13:30 +0000350
John McCall6e247262009-10-10 05:48:19 +0000351 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000352 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000353
John McCallf36e02d2009-10-09 21:13:30 +0000354 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000355 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000356
John McCallf36e02d2009-10-09 21:13:30 +0000357 bool Ambiguous = false;
358 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000359 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000360
361 unsigned UniqueTagIndex = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000362
John McCallf36e02d2009-10-09 21:13:30 +0000363 unsigned I = 0;
364 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000365 NamedDecl *D = Decls[I]->getUnderlyingDecl();
366 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000367
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000368 // Redeclarations of types via typedef can occur both within a scope
369 // and, through using declarations and directives, across scopes. There is
370 // no ambiguity if they all refer to the same type, so unique based on the
371 // canonical type.
372 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
373 if (!TD->getDeclContext()->isRecord()) {
374 QualType T = SemaRef.Context.getTypeDeclType(TD);
375 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
376 // The type is not unique; pull something off the back and continue
377 // at this index.
378 Decls[I] = Decls[--N];
379 continue;
380 }
381 }
382 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000383
John McCall314be4e2009-11-17 07:50:12 +0000384 if (!Unique.insert(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000385 // If it's not unique, pull something off the back (and
386 // continue at this index).
387 Decls[I] = Decls[--N];
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000388 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000389 }
390
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000391 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000392
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000393 if (isa<UnresolvedUsingValueDecl>(D)) {
394 HasUnresolved = true;
395 } else if (isa<TagDecl>(D)) {
396 if (HasTag)
397 Ambiguous = true;
398 UniqueTagIndex = I;
399 HasTag = true;
400 } else if (isa<FunctionTemplateDecl>(D)) {
401 HasFunction = true;
402 HasFunctionTemplate = true;
403 } else if (isa<FunctionDecl>(D)) {
404 HasFunction = true;
405 } else {
406 if (HasNonFunction)
407 Ambiguous = true;
408 HasNonFunction = true;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000409 }
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000410 I++;
Mike Stump1eb44332009-09-09 15:08:12 +0000411 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000412
John McCallf36e02d2009-10-09 21:13:30 +0000413 // C++ [basic.scope.hiding]p2:
414 // A class name or enumeration name can be hidden by the name of
415 // an object, function, or enumerator declared in the same
416 // scope. If a class or enumeration name and an object, function,
417 // or enumerator are declared in the same scope (in any order)
418 // with the same name, the class or enumeration name is hidden
419 // wherever the object, function, or enumerator name is visible.
420 // But it's still an error if there are distinct tag types found,
421 // even if they're not visible. (ref?)
John McCallfda8e122009-12-03 00:58:24 +0000422 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregor77a1a882010-10-23 16:06:17 +0000423 (HasFunction || HasNonFunction || HasUnresolved)) {
424 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
425 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
426 Decls[UniqueTagIndex] = Decls[--N];
427 else
428 Ambiguous = true;
429 }
Anders Carlsson8b50d012009-06-26 03:37:05 +0000430
John McCallf36e02d2009-10-09 21:13:30 +0000431 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000432
John McCallfda8e122009-12-03 00:58:24 +0000433 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000434 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000435
John McCallf36e02d2009-10-09 21:13:30 +0000436 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000437 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000438 else if (HasUnresolved)
439 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000440 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000441 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000442 else
John McCalla24dc2e2009-11-17 02:14:36 +0000443 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000444}
445
John McCall7d384dd2009-11-18 07:57:50 +0000446void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall6b2accb2010-02-10 09:31:12 +0000447 CXXBasePaths::const_paths_iterator I, E;
John McCallf36e02d2009-10-09 21:13:30 +0000448 DeclContext::lookup_iterator DI, DE;
449 for (I = P.begin(), E = P.end(); I != E; ++I)
450 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
451 addDecl(*DI);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000452}
453
John McCall7d384dd2009-11-18 07:57:50 +0000454void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000455 Paths = new CXXBasePaths;
456 Paths->swap(P);
457 addDeclsFromBasePaths(*Paths);
458 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000459 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000460}
461
John McCall7d384dd2009-11-18 07:57:50 +0000462void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000463 Paths = new CXXBasePaths;
464 Paths->swap(P);
465 addDeclsFromBasePaths(*Paths);
466 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000467 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000468}
469
Chris Lattner5f9e2722011-07-23 10:55:15 +0000470void LookupResult::print(raw_ostream &Out) {
John McCallf36e02d2009-10-09 21:13:30 +0000471 Out << Decls.size() << " result(s)";
472 if (isAmbiguous()) Out << ", ambiguous";
473 if (Paths) Out << ", base paths present";
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000474
John McCallf36e02d2009-10-09 21:13:30 +0000475 for (iterator I = begin(), E = end(); I != E; ++I) {
476 Out << "\n";
477 (*I)->print(Out, 2);
478 }
479}
480
Douglas Gregor85910982010-02-12 05:48:04 +0000481/// \brief Lookup a builtin function, when name lookup would otherwise
482/// fail.
483static bool LookupBuiltin(Sema &S, LookupResult &R) {
484 Sema::LookupNameKind NameKind = R.getLookupKind();
485
486 // If we didn't find a use of this identifier, and if the identifier
487 // corresponds to a compiler builtin, create the decl object for the builtin
488 // now, injecting it into translation unit scope, and return it.
489 if (NameKind == Sema::LookupOrdinaryName ||
490 NameKind == Sema::LookupRedeclarationWithLinkage) {
491 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
492 if (II) {
493 // If this is a builtin on this (or all) targets, create the decl.
494 if (unsigned BuiltinID = II->getBuiltinID()) {
495 // In C++, we don't have any predefined library functions like
496 // 'malloc'. Instead, we'll just error.
497 if (S.getLangOptions().CPlusPlus &&
498 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
499 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000500
501 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
502 BuiltinID, S.TUScope,
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000503 R.isForRedeclaration(),
504 R.getNameLoc())) {
Douglas Gregor85910982010-02-12 05:48:04 +0000505 R.addDecl(D);
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000506 return true;
507 }
508
509 if (R.isForRedeclaration()) {
510 // If we're redeclaring this function anyway, forget that
511 // this was a builtin at all.
512 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
513 }
514
515 return false;
Douglas Gregor85910982010-02-12 05:48:04 +0000516 }
517 }
518 }
519
520 return false;
521}
522
Douglas Gregor4923aa22010-07-02 20:37:36 +0000523/// \brief Determine whether we can declare a special member function within
524/// the class at this point.
525static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
526 const CXXRecordDecl *Class) {
John McCallb3b50a82010-08-11 23:52:36 +0000527 // Don't do it if the class is invalid.
528 if (Class->isInvalidDecl())
529 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000530
Douglas Gregor4923aa22010-07-02 20:37:36 +0000531 // We need to have a definition for the class.
532 if (!Class->getDefinition() || Class->isDependentContext())
533 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000534
Douglas Gregor4923aa22010-07-02 20:37:36 +0000535 // We can't be in the middle of defining the class.
536 if (const RecordType *RecordTy
537 = Context.getTypeDeclType(Class)->getAs<RecordType>())
538 return !RecordTy->isBeingDefined();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000539
Douglas Gregor4923aa22010-07-02 20:37:36 +0000540 return false;
541}
542
543void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregor22584312010-07-02 23:41:54 +0000544 if (!CanDeclareSpecialMemberFunction(Context, Class))
545 return;
Douglas Gregor18274032010-07-03 00:47:00 +0000546
547 // If the default constructor has not yet been declared, do so now.
Sean Huntcdee3fe2011-05-11 22:34:38 +0000548 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +0000549 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000550
Douglas Gregor22584312010-07-02 23:41:54 +0000551 // If the copy constructor has not yet been declared, do so now.
552 if (!Class->hasDeclaredCopyConstructor())
553 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000554
Douglas Gregora376d102010-07-02 21:50:04 +0000555 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000556 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +0000557 DeclareImplicitCopyAssignment(Class);
558
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000559 if (getLangOptions().CPlusPlus0x) {
560 // If the move constructor has not yet been declared, do so now.
561 if (Class->needsImplicitMoveConstructor())
562 DeclareImplicitMoveConstructor(Class); // might not actually do it
563
564 // If the move assignment operator has not yet been declared, do so now.
565 if (Class->needsImplicitMoveAssignment())
566 DeclareImplicitMoveAssignment(Class); // might not actually do it
567 }
568
Douglas Gregor4923aa22010-07-02 20:37:36 +0000569 // If the destructor has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000570 if (!Class->hasDeclaredDestructor())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000571 DeclareImplicitDestructor(Class);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000572}
573
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000574/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregora376d102010-07-02 21:50:04 +0000575/// special member function.
576static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
577 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000578 case DeclarationName::CXXConstructorName:
Douglas Gregora376d102010-07-02 21:50:04 +0000579 case DeclarationName::CXXDestructorName:
580 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000581
Douglas Gregora376d102010-07-02 21:50:04 +0000582 case DeclarationName::CXXOperatorName:
583 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000584
Douglas Gregora376d102010-07-02 21:50:04 +0000585 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000586 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000587 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000588
Douglas Gregora376d102010-07-02 21:50:04 +0000589 return false;
590}
591
592/// \brief If there are any implicit member functions with the given name
593/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000594static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregora376d102010-07-02 21:50:04 +0000595 DeclarationName Name,
596 const DeclContext *DC) {
597 if (!DC)
598 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000599
Douglas Gregora376d102010-07-02 21:50:04 +0000600 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000601 case DeclarationName::CXXConstructorName:
602 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor18274032010-07-03 00:47:00 +0000603 if (Record->getDefinition() &&
604 CanDeclareSpecialMemberFunction(S.Context, Record)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000605 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Sean Huntcdee3fe2011-05-11 22:34:38 +0000606 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000607 S.DeclareImplicitDefaultConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +0000608 if (!Record->hasDeclaredCopyConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000609 S.DeclareImplicitCopyConstructor(Class);
610 if (S.getLangOptions().CPlusPlus0x &&
611 Record->needsImplicitMoveConstructor())
612 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +0000613 }
Douglas Gregor22584312010-07-02 23:41:54 +0000614 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000615
Douglas Gregora376d102010-07-02 21:50:04 +0000616 case DeclarationName::CXXDestructorName:
617 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
618 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
619 CanDeclareSpecialMemberFunction(S.Context, Record))
620 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregora376d102010-07-02 21:50:04 +0000621 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000622
Douglas Gregora376d102010-07-02 21:50:04 +0000623 case DeclarationName::CXXOperatorName:
624 if (Name.getCXXOverloadedOperator() != OO_Equal)
625 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000626
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000627 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
628 if (Record->getDefinition() &&
629 CanDeclareSpecialMemberFunction(S.Context, Record)) {
630 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
631 if (!Record->hasDeclaredCopyAssignment())
632 S.DeclareImplicitCopyAssignment(Class);
633 if (S.getLangOptions().CPlusPlus0x &&
634 Record->needsImplicitMoveAssignment())
635 S.DeclareImplicitMoveAssignment(Class);
636 }
637 }
Douglas Gregora376d102010-07-02 21:50:04 +0000638 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000639
Douglas Gregora376d102010-07-02 21:50:04 +0000640 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000641 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000642 }
643}
Douglas Gregor4923aa22010-07-02 20:37:36 +0000644
John McCallf36e02d2009-10-09 21:13:30 +0000645// Adds all qualifying matches for a name within a decl context to the
646// given lookup result. Returns true if any matches were found.
Douglas Gregor85910982010-02-12 05:48:04 +0000647static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000648 bool Found = false;
649
Douglas Gregor4923aa22010-07-02 20:37:36 +0000650 // Lazily declare C++ special member functions.
Douglas Gregora376d102010-07-02 21:50:04 +0000651 if (S.getLangOptions().CPlusPlus)
652 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000653
Douglas Gregor4923aa22010-07-02 20:37:36 +0000654 // Perform lookup into this declaration context.
John McCalld7be78a2009-11-10 07:01:13 +0000655 DeclContext::lookup_const_iterator I, E;
Douglas Gregor48026d22010-01-11 18:40:55 +0000656 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall46460a62010-01-20 21:53:11 +0000657 NamedDecl *D = *I;
Douglas Gregor55368912011-12-14 16:03:29 +0000658 if ((D = R.getAcceptableDecl(D))) {
John McCall46460a62010-01-20 21:53:11 +0000659 R.addDecl(D);
Douglas Gregor48026d22010-01-11 18:40:55 +0000660 Found = true;
661 }
662 }
John McCallf36e02d2009-10-09 21:13:30 +0000663
Douglas Gregor85910982010-02-12 05:48:04 +0000664 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
665 return true;
666
Douglas Gregor48026d22010-01-11 18:40:55 +0000667 if (R.getLookupName().getNameKind()
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000668 != DeclarationName::CXXConversionFunctionName ||
669 R.getLookupName().getCXXNameType()->isDependentType() ||
670 !isa<CXXRecordDecl>(DC))
671 return Found;
672
673 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000674 // A specialization of a conversion function template is not found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000675 // name lookup. Instead, any conversion function templates visible in the
676 // context of the use are considered. [...]
677 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCall5e1cdac2011-10-07 06:10:15 +0000678 if (!Record->isCompleteDefinition())
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000679 return Found;
680
681 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000682 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000683 UEnd = Unresolved->end(); U != UEnd; ++U) {
684 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
685 if (!ConvTemplate)
686 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000687
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000688 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000689 // add the conversion function template. When we deduce template
690 // arguments for specializations, we'll end up unifying the return
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000691 // type of the new declaration with the type of the function template.
692 if (R.isForRedeclaration()) {
693 R.addDecl(ConvTemplate);
694 Found = true;
695 continue;
696 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000697
Douglas Gregor48026d22010-01-11 18:40:55 +0000698 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000699 // [...] For each such operator, if argument deduction succeeds
700 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000701 // name lookup.
702 //
703 // When referencing a conversion function for any purpose other than
704 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000705 // result), perform template argument deduction and place the
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000706 // specialization into the result set. We do this to avoid forcing all
707 // callers to perform special deduction for conversion functions.
John McCall2a7fb272010-08-25 05:32:35 +0000708 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000709 FunctionDecl *Specialization = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000710
711 const FunctionProtoType *ConvProto
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000712 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
713 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3f477a12010-01-12 01:17:50 +0000714
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000715 // Compute the type of the function that we would expect the conversion
716 // function to have, if it were to match the name given.
717 // FIXME: Calling convention!
John McCalle23cf432010-12-14 08:05:40 +0000718 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
719 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
Sebastian Redl8b5b4092011-03-06 10:52:04 +0000720 EPI.ExceptionSpecType = EST_None;
John McCalle23cf432010-12-14 08:05:40 +0000721 EPI.NumExceptions = 0;
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000722 QualType ExpectedType
723 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
John McCalle23cf432010-12-14 08:05:40 +0000724 0, 0, EPI);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000725
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000726 // Perform template argument deduction against the type that we would
727 // expect the function to have.
728 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
729 Specialization, Info)
730 == Sema::TDK_Success) {
731 R.addDecl(Specialization);
732 Found = true;
Douglas Gregor48026d22010-01-11 18:40:55 +0000733 }
734 }
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000735
John McCallf36e02d2009-10-09 21:13:30 +0000736 return Found;
737}
738
John McCalld7be78a2009-11-10 07:01:13 +0000739// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000740static bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000741CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregor85910982010-02-12 05:48:04 +0000742 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000743
744 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
745
John McCalld7be78a2009-11-10 07:01:13 +0000746 // Perform direct name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +0000747 bool Found = LookupDirect(S, R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000748
John McCalld7be78a2009-11-10 07:01:13 +0000749 // Perform direct name lookup into the namespaces nominated by the
750 // using directives whose common ancestor is this namespace.
751 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
752 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000753
John McCalld7be78a2009-11-10 07:01:13 +0000754 for (; UI != UEnd; ++UI)
Douglas Gregor85910982010-02-12 05:48:04 +0000755 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000756 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000757
758 R.resolveKind();
759
760 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000761}
762
763static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000764 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000765 return Ctx->isFileContext();
766 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000767}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000768
Douglas Gregor711be1e2010-03-15 14:33:29 +0000769// Find the next outer declaration context from this scope. This
770// routine actually returns the semantic outer context, which may
771// differ from the lexical context (encoded directly in the Scope
772// stack) when we are parsing a member of a class template. In this
773// case, the second element of the pair will be true, to indicate that
774// name lookup should continue searching in this semantic context when
775// it leaves the current template parameter scope.
776static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
777 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
778 DeclContext *Lexical = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000779 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor711be1e2010-03-15 14:33:29 +0000780 OuterS = OuterS->getParent()) {
781 if (OuterS->getEntity()) {
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000782 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor711be1e2010-03-15 14:33:29 +0000783 break;
784 }
785 }
786
787 // C++ [temp.local]p8:
788 // In the definition of a member of a class template that appears
789 // outside of the namespace containing the class template
790 // definition, the name of a template-parameter hides the name of
791 // a member of this namespace.
792 //
793 // Example:
794 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000795 // namespace N {
796 // class C { };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000797 //
798 // template<class T> class B {
799 // void f(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000800 // };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000801 // }
802 //
803 // template<class C> void N::B<C>::f(C) {
804 // C b; // C is the template parameter, not N::C
805 // }
806 //
807 // In this example, the lexical context we return is the
808 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000809 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor711be1e2010-03-15 14:33:29 +0000810 !S->getParent()->isTemplateParamScope())
811 return std::make_pair(Lexical, false);
812
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000813 // Find the outermost template parameter scope.
Douglas Gregor711be1e2010-03-15 14:33:29 +0000814 // For the example, this is the scope for the template parameters of
815 // template<class C>.
816 Scope *OutermostTemplateScope = S->getParent();
817 while (OutermostTemplateScope->getParent() &&
818 OutermostTemplateScope->getParent()->isTemplateParamScope())
819 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000820
Douglas Gregor711be1e2010-03-15 14:33:29 +0000821 // Find the namespace context in which the original scope occurs. In
822 // the example, this is namespace N.
823 DeclContext *Semantic = DC;
824 while (!Semantic->isFileContext())
825 Semantic = Semantic->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000826
Douglas Gregor711be1e2010-03-15 14:33:29 +0000827 // Find the declaration context just outside of the template
828 // parameter scope. This is the context in which the template is
829 // being lexically declaration (a namespace context). In the
830 // example, this is the global scope.
831 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
832 Lexical->Encloses(Semantic))
833 return std::make_pair(Semantic, true);
834
835 return std::make_pair(Lexical, false);
Douglas Gregore942bbe2009-09-10 16:57:35 +0000836}
837
John McCalla24dc2e2009-11-17 02:14:36 +0000838bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCall1d7c5282009-12-18 10:40:03 +0000839 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000840
841 DeclarationName Name = R.getLookupName();
842
Douglas Gregora376d102010-07-02 21:50:04 +0000843 // If this is the name of an implicitly-declared special member function,
844 // go through the scope stack to implicitly declare
845 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
846 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
847 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
848 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
849 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000850
Douglas Gregora376d102010-07-02 21:50:04 +0000851 // Implicitly declare member functions with the name we're looking for, if in
852 // fact we are in a scope where it matters.
853
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000854 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000855 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000856 I = IdResolver.begin(Name),
857 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000858
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000859 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000860 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000861 // ...During unqualified name lookup (3.4.1), the names appear as if
862 // they were declared in the nearest enclosing namespace which contains
863 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000864 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000865 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000866 //
867 // For example:
868 // namespace A { int i; }
869 // void foo() {
870 // int i;
871 // {
872 // using namespace A;
873 // ++i; // finds local 'i', A::i appears at global scope
874 // }
875 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000876 //
Douglas Gregor711be1e2010-03-15 14:33:29 +0000877 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000878 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregord2235f62010-05-20 20:58:56 +0000879 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
880
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000881 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000882 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000883 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor55368912011-12-14 16:03:29 +0000884 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
John McCallf36e02d2009-10-09 21:13:30 +0000885 Found = true;
Douglas Gregor55368912011-12-14 16:03:29 +0000886 R.addDecl(ND);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000887 }
888 }
John McCallf36e02d2009-10-09 21:13:30 +0000889 if (Found) {
890 R.resolveKind();
Douglas Gregord2235f62010-05-20 20:58:56 +0000891 if (S->isClassScope())
892 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
893 R.setNamingClass(Record);
John McCallf36e02d2009-10-09 21:13:30 +0000894 return true;
895 }
896
Douglas Gregor711be1e2010-03-15 14:33:29 +0000897 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
898 S->getParent() && !S->getParent()->isTemplateParamScope()) {
899 // We've just searched the last template parameter scope and
900 // found nothing, so look into the the contexts between the
901 // lexical and semantic declaration contexts returned by
902 // findOuterContext(). This implements the name lookup behavior
903 // of C++ [temp.local]p8.
904 Ctx = OutsideOfTemplateParamDC;
905 OutsideOfTemplateParamDC = 0;
906 }
907
908 if (Ctx) {
909 DeclContext *OuterCtx;
910 bool SearchAfterTemplateScope;
911 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
912 if (SearchAfterTemplateScope)
913 OutsideOfTemplateParamDC = OuterCtx;
914
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000915 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-02-19 16:08:35 +0000916 // We do not directly look into transparent contexts, since
917 // those entities will be found in the nearest enclosing
918 // non-transparent context.
919 if (Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000920 continue;
Douglas Gregor36262b82010-02-19 16:08:35 +0000921
922 // We do not look directly into function or method contexts,
923 // since all of the local variables and parameters of the
924 // function/method are present within the Scope.
925 if (Ctx->isFunctionOrMethod()) {
926 // If we have an Objective-C instance method, look for ivars
927 // in the corresponding interface.
928 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
929 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
930 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
931 ObjCInterfaceDecl *ClassDeclared;
932 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000933 Name.getAsIdentifierInfo(),
Douglas Gregor36262b82010-02-19 16:08:35 +0000934 ClassDeclared)) {
Douglas Gregor55368912011-12-14 16:03:29 +0000935 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
936 R.addDecl(ND);
Douglas Gregor36262b82010-02-19 16:08:35 +0000937 R.resolveKind();
938 return true;
939 }
940 }
941 }
942 }
943
944 continue;
945 }
946
Douglas Gregore942bbe2009-09-10 16:57:35 +0000947 // Perform qualified name lookup into this context.
948 // FIXME: In some cases, we know that every name that could be found by
949 // this qualified name lookup will also be on the identifier chain. For
950 // example, inside a class without any base classes, we never need to
951 // perform qualified lookup because all of the members are on top of the
952 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000953 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +0000954 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +0000955 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000956 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000957 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000958
John McCalld7be78a2009-11-10 07:01:13 +0000959 // Stop if we ran out of scopes.
960 // FIXME: This really, really shouldn't be happening.
961 if (!S) return false;
962
Argyrios Kyrtzidis78f59112010-10-29 16:12:50 +0000963 // If we are looking for members, no need to look into global/namespace scope.
964 if (R.getLookupKind() == LookupMemberName)
965 return false;
966
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000967 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000968 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +0000969 //
Mike Stump390b4cc2009-05-16 07:39:55 +0000970 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
971 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000972
John McCalld7be78a2009-11-10 07:01:13 +0000973 UnqualUsingDirectiveSet UDirs;
974 UDirs.visitScopeChain(Initial, S);
975 UDirs.done();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000976
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000977 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000978 // Unqualified name lookup in C++ requires looking into scopes
979 // that aren't strictly lexical, and therefore we walk through the
980 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000981
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000982 for (; S; S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000983 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000984 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000985 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor55368912011-12-14 16:03:29 +0000986 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000987 // We found something. Look for anything else in our scope
988 // with this same name and in an acceptable identifier
989 // namespace, so that we can construct an overload set if we
990 // need to.
John McCallf36e02d2009-10-09 21:13:30 +0000991 Found = true;
Douglas Gregor55368912011-12-14 16:03:29 +0000992 R.addDecl(ND);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000993 }
994 }
995
Douglas Gregor00b4b032010-05-14 04:53:42 +0000996 if (Found && S->isTemplateParamScope()) {
John McCallf36e02d2009-10-09 21:13:30 +0000997 R.resolveKind();
998 return true;
999 }
1000
Douglas Gregor00b4b032010-05-14 04:53:42 +00001001 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1002 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1003 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1004 // We've just searched the last template parameter scope and
1005 // found nothing, so look into the the contexts between the
1006 // lexical and semantic declaration contexts returned by
1007 // findOuterContext(). This implements the name lookup behavior
1008 // of C++ [temp.local]p8.
1009 Ctx = OutsideOfTemplateParamDC;
1010 OutsideOfTemplateParamDC = 0;
1011 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001012
Douglas Gregor00b4b032010-05-14 04:53:42 +00001013 if (Ctx) {
1014 DeclContext *OuterCtx;
1015 bool SearchAfterTemplateScope;
1016 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1017 if (SearchAfterTemplateScope)
1018 OutsideOfTemplateParamDC = OuterCtx;
1019
1020 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1021 // We do not directly look into transparent contexts, since
1022 // those entities will be found in the nearest enclosing
1023 // non-transparent context.
1024 if (Ctx->isTransparentContext())
1025 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001026
Douglas Gregor00b4b032010-05-14 04:53:42 +00001027 // If we have a context, and it's not a context stashed in the
1028 // template parameter scope for an out-of-line definition, also
1029 // look into that context.
1030 if (!(Found && S && S->isTemplateParamScope())) {
1031 assert(Ctx->isFileContext() &&
1032 "We should have been looking only at file context here already.");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001033
Douglas Gregor00b4b032010-05-14 04:53:42 +00001034 // Look into context considering using-directives.
1035 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1036 Found = true;
1037 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001038
Douglas Gregor00b4b032010-05-14 04:53:42 +00001039 if (Found) {
1040 R.resolveKind();
1041 return true;
1042 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001043
Douglas Gregor00b4b032010-05-14 04:53:42 +00001044 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1045 return false;
1046 }
1047 }
1048
Douglas Gregor1df0ee92010-02-05 07:07:10 +00001049 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +00001050 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001051 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001052
John McCallf36e02d2009-10-09 21:13:30 +00001053 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001054}
1055
Douglas Gregor55368912011-12-14 16:03:29 +00001056/// \brief Retrieve the previous declaration of D.
1057static NamedDecl *getPreviousDeclaration(NamedDecl *D) {
1058 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1059 return TD->getPreviousDeclaration();
1060 if (VarDecl *VD = dyn_cast<VarDecl>(D))
1061 return VD->getPreviousDeclaration();
1062 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1063 return FD->getPreviousDeclaration();
1064 if (RedeclarableTemplateDecl *RTD = dyn_cast<RedeclarableTemplateDecl>(D))
1065 return RTD->getPreviousDeclaration();
Douglas Gregora1be2782011-12-17 23:38:30 +00001066 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
1067 return TD->getPreviousDeclaration();
Douglas Gregord63348c2011-12-15 20:36:27 +00001068 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
1069 return ID->getPreviousDeclaration();
Douglas Gregor55368912011-12-14 16:03:29 +00001070
1071 return 0;
1072}
1073
1074/// \brief Retrieve the visible declaration corresponding to D, if any.
1075///
1076/// This routine determines whether the declaration D is visible in the current
1077/// module, with the current imports. If not, it checks whether any
1078/// redeclaration of D is visible, and if so, returns that declaration.
1079///
1080/// \returns D, or a visible previous declaration of D, whichever is more recent
1081/// and visible. If no declaration of D is visible, returns null.
1082static NamedDecl *getVisibleDecl(NamedDecl *D) {
1083 if (LookupResult::isVisible(D))
1084 return D;
1085
1086 while ((D = getPreviousDeclaration(D))) {
1087 if (LookupResult::isVisible(D))
1088 return D;
1089 }
1090
1091 return 0;
1092}
1093
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001094/// @brief Perform unqualified name lookup starting from a given
1095/// scope.
1096///
1097/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1098/// used to find names within the current scope. For example, 'x' in
1099/// @code
1100/// int x;
1101/// int f() {
1102/// return x; // unqualified name look finds 'x' in the global scope
1103/// }
1104/// @endcode
1105///
1106/// Different lookup criteria can find different names. For example, a
1107/// particular scope can have both a struct and a function of the same
1108/// name, and each can be found by certain lookup criteria. For more
1109/// information about lookup criteria, see the documentation for the
1110/// class LookupCriteria.
1111///
1112/// @param S The scope from which unqualified name lookup will
1113/// begin. If the lookup criteria permits, name lookup may also search
1114/// in the parent scopes.
1115///
1116/// @param Name The name of the entity that we are searching for.
1117///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001118/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001119/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001120/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001121///
1122/// @returns The result of name lookup, which includes zero or more
1123/// declarations and possibly additional information used to diagnose
1124/// ambiguities.
John McCalla24dc2e2009-11-17 02:14:36 +00001125bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1126 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +00001127 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001128
John McCalla24dc2e2009-11-17 02:14:36 +00001129 LookupNameKind NameKind = R.getLookupKind();
1130
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001131 if (!getLangOptions().CPlusPlus) {
1132 // Unqualified name lookup in C/Objective-C is purely lexical, so
1133 // search in the declarations attached to the name.
John McCall1d7c5282009-12-18 10:40:03 +00001134 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001135 // Find the nearest non-transparent declaration scope.
1136 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001137 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001138 static_cast<DeclContext *>(S->getEntity())
1139 ->isTransparentContext()))
1140 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001141 }
1142
John McCall1d7c5282009-12-18 10:40:03 +00001143 unsigned IDNS = R.getIdentifierNamespace();
1144
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001145 // Scan up the scope chain looking for a decl that matches this
1146 // identifier that is in the appropriate namespace. This search
1147 // should not take long, as shadowing of names is uncommon, and
1148 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001149 bool LeftStartingScope = false;
1150
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001151 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +00001152 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001153 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001154 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001155 if (NameKind == LookupRedeclarationWithLinkage) {
1156 // Determine whether this (or a previous) declaration is
1157 // out-of-scope.
John McCalld226f652010-08-21 09:40:31 +00001158 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001159 LeftStartingScope = true;
1160
1161 // If we found something outside of our starting scope that
1162 // does not have linkage, skip it.
1163 if (LeftStartingScope && !((*I)->hasLinkage()))
1164 continue;
1165 }
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001166 else if (NameKind == LookupObjCImplicitSelfParam &&
1167 !isa<ImplicitParamDecl>(*I))
1168 continue;
1169
Douglas Gregor10ce9322011-12-02 20:08:44 +00001170 // If this declaration is module-private and it came from an AST
1171 // file, we can't see it.
Douglas Gregor2ccd89c2011-12-20 18:11:52 +00001172 NamedDecl *D = R.isForRedeclaration()? *I : getVisibleDecl(*I);
Douglas Gregor55368912011-12-14 16:03:29 +00001173 if (!D)
Douglas Gregor10ce9322011-12-02 20:08:44 +00001174 continue;
Douglas Gregor55368912011-12-14 16:03:29 +00001175
1176 R.addDecl(D);
John McCallf36e02d2009-10-09 21:13:30 +00001177
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001178 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00001179 // If this declaration has the "overloadable" attribute, we
1180 // might have a set of overloaded functions.
1181
1182 // Figure out what scope the identifier is in.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001183 while (!(S->getFlags() & Scope::DeclScope) ||
John McCalld226f652010-08-21 09:40:31 +00001184 !S->isDeclScope(*I))
Douglas Gregorf9201e02009-02-11 23:02:49 +00001185 S = S->getParent();
1186
1187 // Find the last declaration in this scope (with the same
1188 // name, naturally).
1189 IdentifierResolver::iterator LastI = I;
1190 for (++LastI; LastI != IEnd; ++LastI) {
John McCalld226f652010-08-21 09:40:31 +00001191 if (!S->isDeclScope(*LastI))
Douglas Gregorf9201e02009-02-11 23:02:49 +00001192 break;
Douglas Gregor55368912011-12-14 16:03:29 +00001193
1194 D = getVisibleDecl(*LastI);
1195 if (D)
1196 R.addDecl(D);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001197 }
Douglas Gregorf9201e02009-02-11 23:02:49 +00001198 }
1199
John McCallf36e02d2009-10-09 21:13:30 +00001200 R.resolveKind();
1201
1202 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +00001203 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001204 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001205 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +00001206 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +00001207 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001208 }
1209
1210 // If we didn't find a use of this identifier, and if the identifier
1211 // corresponds to a compiler builtin, create the decl object for the builtin
1212 // now, injecting it into translation unit scope, and return it.
Axel Naumann42151d52011-04-13 13:19:46 +00001213 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1214 return true;
Douglas Gregor3e41d602009-02-13 23:20:09 +00001215
Axel Naumannf8291a12011-02-24 16:47:47 +00001216 // If we didn't find a use of this identifier, the ExternalSource
1217 // may be able to handle the situation.
1218 // Note: some lookup failures are expected!
1219 // See e.g. R.isForRedeclaration().
1220 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001221}
1222
John McCall6e247262009-10-10 05:48:19 +00001223/// @brief Perform qualified name lookup in the namespaces nominated by
1224/// using directives by the given context.
1225///
1226/// C++98 [namespace.qual]p2:
1227/// Given X::m (where X is a user-declared namespace), or given ::m
1228/// (where X is the global namespace), let S be the set of all
1229/// declarations of m in X and in the transitive closure of all
1230/// namespaces nominated by using-directives in X and its used
1231/// namespaces, except that using-directives are ignored in any
1232/// namespace, including X, directly containing one or more
1233/// declarations of m. No namespace is searched more than once in
1234/// the lookup of a name. If S is the empty set, the program is
1235/// ill-formed. Otherwise, if S has exactly one member, or if the
1236/// context of the reference is a using-declaration
1237/// (namespace.udecl), S is the required set of declarations of
1238/// m. Otherwise if the use of m is not one that allows a unique
1239/// declaration to be chosen from S, the program is ill-formed.
1240/// C++98 [namespace.qual]p5:
1241/// During the lookup of a qualified namespace member name, if the
1242/// lookup finds more than one declaration of the member, and if one
1243/// declaration introduces a class name or enumeration name and the
1244/// other declarations either introduce the same object, the same
1245/// enumerator or a set of functions, the non-type name hides the
1246/// class or enumeration name if and only if the declarations are
1247/// from the same namespace; otherwise (the declarations are from
1248/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +00001249static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +00001250 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +00001251 assert(StartDC->isFileContext() && "start context is not a file context");
1252
1253 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1254 DeclContext::udir_iterator E = StartDC->using_directives_end();
1255
1256 if (I == E) return false;
1257
1258 // We have at least added all these contexts to the queue.
1259 llvm::DenseSet<DeclContext*> Visited;
1260 Visited.insert(StartDC);
1261
1262 // We have not yet looked into these namespaces, much less added
1263 // their "using-children" to the queue.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001264 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6e247262009-10-10 05:48:19 +00001265
1266 // We have already looked into the initial namespace; seed the queue
1267 // with its using-children.
1268 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001269 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6e247262009-10-10 05:48:19 +00001270 if (Visited.insert(ND).second)
1271 Queue.push_back(ND);
1272 }
1273
1274 // The easiest way to implement the restriction in [namespace.qual]p5
1275 // is to check whether any of the individual results found a tag
1276 // and, if so, to declare an ambiguity if the final result is not
1277 // a tag.
1278 bool FoundTag = false;
1279 bool FoundNonTag = false;
1280
John McCall7d384dd2009-11-18 07:57:50 +00001281 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001282
1283 bool Found = false;
1284 while (!Queue.empty()) {
1285 NamespaceDecl *ND = Queue.back();
1286 Queue.pop_back();
1287
1288 // We go through some convolutions here to avoid copying results
1289 // between LookupResults.
1290 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001291 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001292 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001293
1294 if (FoundDirect) {
1295 // First do any local hiding.
1296 DirectR.resolveKind();
1297
1298 // If the local result is a tag, remember that.
1299 if (DirectR.isSingleTagDecl())
1300 FoundTag = true;
1301 else
1302 FoundNonTag = true;
1303
1304 // Append the local results to the total results if necessary.
1305 if (UseLocal) {
1306 R.addAllDecls(LocalR);
1307 LocalR.clear();
1308 }
1309 }
1310
1311 // If we find names in this namespace, ignore its using directives.
1312 if (FoundDirect) {
1313 Found = true;
1314 continue;
1315 }
1316
1317 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1318 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1319 if (Visited.insert(Nom).second)
1320 Queue.push_back(Nom);
1321 }
1322 }
1323
1324 if (Found) {
1325 if (FoundTag && FoundNonTag)
1326 R.setAmbiguousQualifiedTagHiding();
1327 else
1328 R.resolveKind();
1329 }
1330
1331 return Found;
1332}
1333
Douglas Gregor8071e422010-08-15 06:18:01 +00001334/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001335static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor8071e422010-08-15 06:18:01 +00001336 CXXBasePath &Path,
1337 void *Name) {
1338 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001339
Douglas Gregor8071e422010-08-15 06:18:01 +00001340 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1341 Path.Decls = BaseRecord->lookup(N);
1342 return Path.Decls.first != Path.Decls.second;
1343}
1344
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001345/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001346/// static members, nested types, and enumerators.
1347template<typename InputIterator>
1348static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1349 Decl *D = (*First)->getUnderlyingDecl();
1350 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1351 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001352
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001353 if (isa<CXXMethodDecl>(D)) {
1354 // Determine whether all of the methods are static.
1355 bool AllMethodsAreStatic = true;
1356 for(; First != Last; ++First) {
1357 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001358
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001359 if (!isa<CXXMethodDecl>(D)) {
1360 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1361 break;
1362 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001363
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001364 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1365 AllMethodsAreStatic = false;
1366 break;
1367 }
1368 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001369
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001370 if (AllMethodsAreStatic)
1371 return true;
1372 }
1373
1374 return false;
1375}
1376
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001377/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001378///
1379/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1380/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001381/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001382///
1383/// Different lookup criteria can find different names. For example, a
1384/// particular scope can have both a struct and a function of the same
1385/// name, and each can be found by certain lookup criteria. For more
1386/// information about lookup criteria, see the documentation for the
1387/// class LookupCriteria.
1388///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001389/// \param R captures both the lookup criteria and any lookup results found.
1390///
1391/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001392/// search. If the lookup criteria permits, name lookup may also search
1393/// in the parent contexts or (for C++ classes) base classes.
1394///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001395/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001396/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001397///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001398/// \returns true if lookup succeeded, false if it failed.
1399bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1400 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001401 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001402
John McCalla24dc2e2009-11-17 02:14:36 +00001403 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001404 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001405
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001406 // Make sure that the declaration context is complete.
1407 assert((!isa<TagDecl>(LookupCtx) ||
1408 LookupCtx->isDependentContext() ||
John McCall5e1cdac2011-10-07 06:10:15 +00001409 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001410 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1411 ->isBeingDefined()) &&
1412 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001413
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001414 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001415 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001416 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001417 if (isa<CXXRecordDecl>(LookupCtx))
1418 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001419 return true;
1420 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001421
John McCall6e247262009-10-10 05:48:19 +00001422 // Don't descend into implied contexts for redeclarations.
1423 // C++98 [namespace.qual]p6:
1424 // In a declaration for a namespace member in which the
1425 // declarator-id is a qualified-id, given that the qualified-id
1426 // for the namespace member has the form
1427 // nested-name-specifier unqualified-id
1428 // the unqualified-id shall name a member of the namespace
1429 // designated by the nested-name-specifier.
1430 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001431 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001432 return false;
1433
John McCalla24dc2e2009-11-17 02:14:36 +00001434 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001435 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001436 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001437
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001438 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001439 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001440 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor025291b2010-07-01 00:21:21 +00001441 if (!LookupRec || !LookupRec->getDefinition())
John McCallf36e02d2009-10-09 21:13:30 +00001442 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001443
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001444 // If we're performing qualified name lookup into a dependent class,
1445 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001446 // dependent base classes, then we either have to delay lookup until
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001447 // template instantiation time (at which point all bases will be available)
1448 // or we have to fail.
1449 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1450 LookupRec->hasAnyDependentBases()) {
1451 R.setNotFoundInCurrentInstantiation();
1452 return false;
1453 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001454
Douglas Gregor7176fff2009-01-15 00:26:24 +00001455 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001456 CXXBasePaths Paths;
1457 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001458
1459 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001460 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001461 switch (R.getLookupKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001462 case LookupObjCImplicitSelfParam:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001463 case LookupOrdinaryName:
1464 case LookupMemberName:
1465 case LookupRedeclarationWithLinkage:
1466 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1467 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001468
Douglas Gregora8f32e02009-10-06 17:59:45 +00001469 case LookupTagName:
1470 BaseCallback = &CXXRecordDecl::FindTagMember;
1471 break;
John McCall9f54ad42009-12-10 09:41:52 +00001472
Douglas Gregor8071e422010-08-15 06:18:01 +00001473 case LookupAnyName:
1474 BaseCallback = &LookupAnyMember;
1475 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001476
John McCall9f54ad42009-12-10 09:41:52 +00001477 case LookupUsingDeclName:
1478 // This lookup is for redeclarations only.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001479
Douglas Gregora8f32e02009-10-06 17:59:45 +00001480 case LookupOperatorName:
1481 case LookupNamespaceName:
1482 case LookupObjCProtocolName:
Chris Lattner337e5502011-02-18 01:27:55 +00001483 case LookupLabel:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001484 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001485 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001486
Douglas Gregora8f32e02009-10-06 17:59:45 +00001487 case LookupNestedNameSpecifierName:
1488 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1489 break;
1490 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001491
John McCalla24dc2e2009-11-17 02:14:36 +00001492 if (!LookupRec->lookupInBases(BaseCallback,
1493 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001494 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001495
John McCall92f88312010-01-23 00:46:32 +00001496 R.setNamingClass(LookupRec);
1497
Douglas Gregor7176fff2009-01-15 00:26:24 +00001498 // C++ [class.member.lookup]p2:
1499 // [...] If the resulting set of declarations are not all from
1500 // sub-objects of the same type, or the set has a nonstatic member
1501 // and includes members from distinct sub-objects, there is an
1502 // ambiguity and the program is ill-formed. Otherwise that set is
1503 // the result of the lookup.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001504 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001505 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001506 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001507
Douglas Gregora8f32e02009-10-06 17:59:45 +00001508 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001509 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001510 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001511
John McCall46460a62010-01-20 21:53:11 +00001512 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1513 // across all paths.
1514 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001515
Douglas Gregor7176fff2009-01-15 00:26:24 +00001516 // Determine whether we're looking at a distinct sub-object or not.
1517 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001518 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001519 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1520 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001521 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001522 }
1523
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001524 if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001525 != Context.getCanonicalType(PathElement.Base->getType())) {
1526 // We found members of the given name in two subobjects of
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001527 // different types. If the declaration sets aren't the same, this
1528 // this lookup is ambiguous.
1529 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1530 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1531 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1532 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001533
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001534 while (FirstD != FirstPath->Decls.second &&
1535 CurrentD != Path->Decls.second) {
1536 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1537 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1538 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001539
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001540 ++FirstD;
1541 ++CurrentD;
1542 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001543
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001544 if (FirstD == FirstPath->Decls.second &&
1545 CurrentD == Path->Decls.second)
1546 continue;
1547 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001548
John McCallf36e02d2009-10-09 21:13:30 +00001549 R.setAmbiguousBaseSubobjectTypes(Paths);
1550 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001551 }
1552
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001553 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001554 // We have a different subobject of the same type.
1555
1556 // C++ [class.member.lookup]p5:
1557 // A static member, a nested type or an enumerator defined in
1558 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001559 // has more than one base class subobject of type T.
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001560 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
Douglas Gregor7176fff2009-01-15 00:26:24 +00001561 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001562
Douglas Gregor7176fff2009-01-15 00:26:24 +00001563 // We have found a nonstatic member name in multiple, distinct
1564 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001565 R.setAmbiguousBaseSubobjects(Paths);
1566 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001567 }
1568 }
1569
1570 // Lookup in a base class succeeded; return these results.
1571
John McCallf36e02d2009-10-09 21:13:30 +00001572 DeclContext::lookup_iterator I, E;
John McCall92f88312010-01-23 00:46:32 +00001573 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1574 NamedDecl *D = *I;
1575 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1576 D->getAccess());
1577 R.addDecl(D, AS);
1578 }
John McCallf36e02d2009-10-09 21:13:30 +00001579 R.resolveKind();
1580 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001581}
1582
1583/// @brief Performs name lookup for a name that was parsed in the
1584/// source code, and may contain a C++ scope specifier.
1585///
1586/// This routine is a convenience routine meant to be called from
1587/// contexts that receive a name and an optional C++ scope specifier
1588/// (e.g., "N::M::x"). It will then perform either qualified or
1589/// unqualified name lookup (with LookupQualifiedName or LookupName,
1590/// respectively) on the given name and return those results.
1591///
1592/// @param S The scope from which unqualified name lookup will
1593/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001594///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001595/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001596///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001597/// @param EnteringContext Indicates whether we are going to enter the
1598/// context of the scope-specifier SS (if present).
1599///
John McCallf36e02d2009-10-09 21:13:30 +00001600/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001601bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001602 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001603 if (SS && SS->isInvalid()) {
1604 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001605 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001606 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001607 }
Mike Stump1eb44332009-09-09 15:08:12 +00001608
Douglas Gregor495c35d2009-08-25 22:51:20 +00001609 if (SS && SS->isSet()) {
1610 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001611 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001612 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001613 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001614 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001615
John McCalla24dc2e2009-11-17 02:14:36 +00001616 R.setContextRange(SS->getRange());
John McCalla24dc2e2009-11-17 02:14:36 +00001617 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001618 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001619
Douglas Gregor495c35d2009-08-25 22:51:20 +00001620 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001621 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001622 // Name lookup can't find anything in this case.
Douglas Gregor3eafbb82011-10-24 22:24:50 +00001623 R.setNotFoundInCurrentInstantiation();
1624 R.setContextRange(SS->getRange());
John McCallf36e02d2009-10-09 21:13:30 +00001625 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001626 }
1627
Mike Stump1eb44332009-09-09 15:08:12 +00001628 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001629 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001630}
1631
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001632
Douglas Gregor7176fff2009-01-15 00:26:24 +00001633/// @brief Produce a diagnostic describing the ambiguity that resulted
1634/// from name lookup.
1635///
1636/// @param Result The ambiguous name lookup result.
Mike Stump1eb44332009-09-09 15:08:12 +00001637///
Douglas Gregor7176fff2009-01-15 00:26:24 +00001638/// @param Name The name of the entity that name lookup was
1639/// searching for.
1640///
1641/// @param NameLoc The location of the name within the source code.
1642///
1643/// @param LookupRange A source range that provides more
1644/// source-location information concerning the lookup itself. For
1645/// example, this range might highlight a nested-name-specifier that
1646/// precedes the name.
1647///
1648/// @returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001649bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001650 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1651
John McCalla24dc2e2009-11-17 02:14:36 +00001652 DeclarationName Name = Result.getLookupName();
1653 SourceLocation NameLoc = Result.getNameLoc();
1654 SourceRange LookupRange = Result.getContextRange();
1655
John McCall6e247262009-10-10 05:48:19 +00001656 switch (Result.getAmbiguityKind()) {
1657 case LookupResult::AmbiguousBaseSubobjects: {
1658 CXXBasePaths *Paths = Result.getBasePaths();
1659 QualType SubobjectType = Paths->front().back().Base->getType();
1660 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1661 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1662 << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001663
John McCall6e247262009-10-10 05:48:19 +00001664 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1665 while (isa<CXXMethodDecl>(*Found) &&
1666 cast<CXXMethodDecl>(*Found)->isStatic())
1667 ++Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001668
John McCall6e247262009-10-10 05:48:19 +00001669 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001670
John McCall6e247262009-10-10 05:48:19 +00001671 return true;
1672 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001673
John McCall6e247262009-10-10 05:48:19 +00001674 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001675 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1676 << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001677
John McCall6e247262009-10-10 05:48:19 +00001678 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001679 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001680 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1681 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001682 Path != PathEnd; ++Path) {
1683 Decl *D = *Path->Decls.first;
1684 if (DeclsPrinted.insert(D).second)
1685 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1686 }
1687
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001688 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001689 }
1690
John McCall6e247262009-10-10 05:48:19 +00001691 case LookupResult::AmbiguousTagHiding: {
1692 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001693
John McCall6e247262009-10-10 05:48:19 +00001694 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1695
1696 LookupResult::iterator DI, DE = Result.end();
1697 for (DI = Result.begin(); DI != DE; ++DI)
1698 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1699 TagDecls.insert(TD);
1700 Diag(TD->getLocation(), diag::note_hidden_tag);
1701 }
1702
1703 for (DI = Result.begin(); DI != DE; ++DI)
1704 if (!isa<TagDecl>(*DI))
1705 Diag((*DI)->getLocation(), diag::note_hiding_object);
1706
1707 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001708 LookupResult::Filter F = Result.makeFilter();
1709 while (F.hasNext()) {
1710 if (TagDecls.count(F.next()))
1711 F.erase();
1712 }
1713 F.done();
John McCall6e247262009-10-10 05:48:19 +00001714
1715 return true;
1716 }
1717
1718 case LookupResult::AmbiguousReference: {
1719 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001720
John McCall6e247262009-10-10 05:48:19 +00001721 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1722 for (; DI != DE; ++DI)
1723 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001724
John McCall6e247262009-10-10 05:48:19 +00001725 return true;
1726 }
1727 }
1728
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001729 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001730 return true;
1731}
Douglas Gregorfa047642009-02-04 00:32:51 +00001732
John McCallc7e04da2010-05-28 18:45:08 +00001733namespace {
1734 struct AssociatedLookup {
1735 AssociatedLookup(Sema &S,
1736 Sema::AssociatedNamespaceSet &Namespaces,
1737 Sema::AssociatedClassSet &Classes)
1738 : S(S), Namespaces(Namespaces), Classes(Classes) {
1739 }
1740
1741 Sema &S;
1742 Sema::AssociatedNamespaceSet &Namespaces;
1743 Sema::AssociatedClassSet &Classes;
1744 };
1745}
1746
Mike Stump1eb44332009-09-09 15:08:12 +00001747static void
John McCallc7e04da2010-05-28 18:45:08 +00001748addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCall6ff07852009-08-07 22:18:02 +00001749
Douglas Gregor54022952010-04-30 07:08:38 +00001750static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1751 DeclContext *Ctx) {
1752 // Add the associated namespace for this class.
1753
1754 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1755 // be a locally scoped record.
1756
Sebastian Redl410c4f22010-08-31 20:53:31 +00001757 // We skip out of inline namespaces. The innermost non-inline namespace
1758 // contains all names of all its nested inline namespaces anyway, so we can
1759 // replace the entire inline namespace tree with its root.
1760 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1761 Ctx->isInlineNamespace())
Douglas Gregor54022952010-04-30 07:08:38 +00001762 Ctx = Ctx->getParent();
1763
John McCall6ff07852009-08-07 22:18:02 +00001764 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001765 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001766}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001767
Mike Stump1eb44332009-09-09 15:08:12 +00001768// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001769// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001770static void
John McCallc7e04da2010-05-28 18:45:08 +00001771addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1772 const TemplateArgument &Arg) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001773 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001774 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001775 switch (Arg.getKind()) {
1776 case TemplateArgument::Null:
1777 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001778
Douglas Gregor69be8d62009-07-08 07:51:57 +00001779 case TemplateArgument::Type:
1780 // [...] the namespaces and classes associated with the types of the
1781 // template arguments provided for template type parameters (excluding
1782 // template template parameters)
John McCallc7e04da2010-05-28 18:45:08 +00001783 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor69be8d62009-07-08 07:51:57 +00001784 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001785
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001786 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001787 case TemplateArgument::TemplateExpansion: {
Mike Stump1eb44332009-09-09 15:08:12 +00001788 // [...] the namespaces in which any template template arguments are
1789 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001790 // template template arguments are defined.
Douglas Gregora7fc9012011-01-05 18:58:31 +00001791 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump1eb44332009-09-09 15:08:12 +00001792 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001793 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001794 DeclContext *Ctx = ClassTemplate->getDeclContext();
1795 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001796 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001797 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001798 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001799 }
1800 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001801 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001802
Douglas Gregor788cd062009-11-11 01:00:40 +00001803 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001804 case TemplateArgument::Integral:
1805 case TemplateArgument::Expression:
Mike Stump1eb44332009-09-09 15:08:12 +00001806 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001807 // associated namespaces. ]
1808 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001809
Douglas Gregor69be8d62009-07-08 07:51:57 +00001810 case TemplateArgument::Pack:
1811 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1812 PEnd = Arg.pack_end();
1813 P != PEnd; ++P)
John McCallc7e04da2010-05-28 18:45:08 +00001814 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001815 break;
1816 }
1817}
1818
Douglas Gregorfa047642009-02-04 00:32:51 +00001819// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001820// argument-dependent lookup with an argument of class type
1821// (C++ [basic.lookup.koenig]p2).
1822static void
John McCallc7e04da2010-05-28 18:45:08 +00001823addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1824 CXXRecordDecl *Class) {
1825
1826 // Just silently ignore anything whose name is __va_list_tag.
1827 if (Class->getDeclName() == Result.S.VAListTagName)
1828 return;
1829
Douglas Gregorfa047642009-02-04 00:32:51 +00001830 // C++ [basic.lookup.koenig]p2:
1831 // [...]
1832 // -- If T is a class type (including unions), its associated
1833 // classes are: the class itself; the class of which it is a
1834 // member, if any; and its direct and indirect base
1835 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001836 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001837
1838 // Add the class of which it is a member, if any.
1839 DeclContext *Ctx = Class->getDeclContext();
1840 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001841 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001842 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001843 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Douglas Gregorfa047642009-02-04 00:32:51 +00001845 // Add the class itself. If we've already seen this class, we don't
1846 // need to visit base classes.
John McCallc7e04da2010-05-28 18:45:08 +00001847 if (!Result.Classes.insert(Class))
Douglas Gregorfa047642009-02-04 00:32:51 +00001848 return;
1849
Mike Stump1eb44332009-09-09 15:08:12 +00001850 // -- If T is a template-id, its associated namespaces and classes are
1851 // the namespace in which the template is defined; for member
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001852 // templates, the member template's class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001853 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001854 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001855 // namespaces in which any template template arguments are defined; and
1856 // the classes in which any member templates used as template template
1857 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001858 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001859 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001860 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1861 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1862 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001863 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001864 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001865 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001866
Douglas Gregor69be8d62009-07-08 07:51:57 +00001867 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1868 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallc7e04da2010-05-28 18:45:08 +00001869 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001870 }
Mike Stump1eb44332009-09-09 15:08:12 +00001871
John McCall86ff3082010-02-04 22:26:26 +00001872 // Only recurse into base classes for complete types.
1873 if (!Class->hasDefinition()) {
1874 // FIXME: we might need to instantiate templates here
1875 return;
1876 }
1877
Douglas Gregorfa047642009-02-04 00:32:51 +00001878 // Add direct and indirect base classes along with their associated
1879 // namespaces.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001880 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregorfa047642009-02-04 00:32:51 +00001881 Bases.push_back(Class);
1882 while (!Bases.empty()) {
1883 // Pop this class off the stack.
1884 Class = Bases.back();
1885 Bases.pop_back();
1886
1887 // Visit the base classes.
1888 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1889 BaseEnd = Class->bases_end();
1890 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001891 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001892 // In dependent contexts, we do ADL twice, and the first time around,
1893 // the base type might be a dependent TemplateSpecializationType, or a
1894 // TemplateTypeParmType. If that happens, simply ignore it.
1895 // FIXME: If we want to support export, we probably need to add the
1896 // namespace of the template in a TemplateSpecializationType, or even
1897 // the classes and namespaces of known non-dependent arguments.
1898 if (!BaseType)
1899 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001900 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001901 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001902 // Find the associated namespace for this base class.
1903 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallc7e04da2010-05-28 18:45:08 +00001904 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001905
1906 // Make sure we visit the bases of this base class.
1907 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1908 Bases.push_back(BaseDecl);
1909 }
1910 }
1911 }
1912}
1913
1914// \brief Add the associated classes and namespaces for
1915// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001916// (C++ [basic.lookup.koenig]p2).
1917static void
John McCallc7e04da2010-05-28 18:45:08 +00001918addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001919 // C++ [basic.lookup.koenig]p2:
1920 //
1921 // For each argument type T in the function call, there is a set
1922 // of zero or more associated namespaces and a set of zero or more
1923 // associated classes to be considered. The sets of namespaces and
1924 // classes is determined entirely by the types of the function
1925 // arguments (and the namespace of any template template
1926 // argument). Typedef names and using-declarations used to specify
1927 // the types do not contribute to this set. The sets of namespaces
1928 // and classes are determined in the following way:
Douglas Gregorfa047642009-02-04 00:32:51 +00001929
Chris Lattner5f9e2722011-07-23 10:55:15 +00001930 SmallVector<const Type *, 16> Queue;
John McCallfa4edcf2010-05-28 06:08:54 +00001931 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1932
Douglas Gregorfa047642009-02-04 00:32:51 +00001933 while (true) {
John McCallfa4edcf2010-05-28 06:08:54 +00001934 switch (T->getTypeClass()) {
1935
1936#define TYPE(Class, Base)
1937#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1938#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1939#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1940#define ABSTRACT_TYPE(Class, Base)
1941#include "clang/AST/TypeNodes.def"
1942 // T is canonical. We can also ignore dependent types because
1943 // we don't need to do ADL at the definition point, but if we
1944 // wanted to implement template export (or if we find some other
1945 // use for associated classes and namespaces...) this would be
1946 // wrong.
Douglas Gregorfa047642009-02-04 00:32:51 +00001947 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00001948
John McCallfa4edcf2010-05-28 06:08:54 +00001949 // -- If T is a pointer to U or an array of U, its associated
1950 // namespaces and classes are those associated with U.
1951 case Type::Pointer:
1952 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1953 continue;
1954 case Type::ConstantArray:
1955 case Type::IncompleteArray:
1956 case Type::VariableArray:
1957 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1958 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001959
John McCallfa4edcf2010-05-28 06:08:54 +00001960 // -- If T is a fundamental type, its associated sets of
1961 // namespaces and classes are both empty.
1962 case Type::Builtin:
1963 break;
1964
1965 // -- If T is a class type (including unions), its associated
1966 // classes are: the class itself; the class of which it is a
1967 // member, if any; and its direct and indirect base
1968 // classes. Its associated namespaces are the namespaces in
1969 // which its associated classes are defined.
1970 case Type::Record: {
1971 CXXRecordDecl *Class
1972 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001973 addAssociatedClassesAndNamespaces(Result, Class);
John McCallfa4edcf2010-05-28 06:08:54 +00001974 break;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001975 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00001976
John McCallfa4edcf2010-05-28 06:08:54 +00001977 // -- If T is an enumeration type, its associated namespace is
1978 // the namespace in which it is defined. If it is class
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001979 // member, its associated class is the member's class; else
John McCallfa4edcf2010-05-28 06:08:54 +00001980 // it has no associated class.
1981 case Type::Enum: {
1982 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001983
John McCallfa4edcf2010-05-28 06:08:54 +00001984 DeclContext *Ctx = Enum->getDeclContext();
1985 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001986 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001987
John McCallfa4edcf2010-05-28 06:08:54 +00001988 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001989 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001990
John McCallfa4edcf2010-05-28 06:08:54 +00001991 break;
1992 }
1993
1994 // -- If T is a function type, its associated namespaces and
1995 // classes are those associated with the function parameter
1996 // types and those associated with the return type.
1997 case Type::FunctionProto: {
1998 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1999 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
2000 ArgEnd = Proto->arg_type_end();
2001 Arg != ArgEnd; ++Arg)
2002 Queue.push_back(Arg->getTypePtr());
2003 // fallthrough
2004 }
2005 case Type::FunctionNoProto: {
2006 const FunctionType *FnType = cast<FunctionType>(T);
2007 T = FnType->getResultType().getTypePtr();
2008 continue;
2009 }
2010
2011 // -- If T is a pointer to a member function of a class X, its
2012 // associated namespaces and classes are those associated
2013 // with the function parameter types and return type,
2014 // together with those associated with X.
2015 //
2016 // -- If T is a pointer to a data member of class X, its
2017 // associated namespaces and classes are those associated
2018 // with the member type together with those associated with
2019 // X.
2020 case Type::MemberPointer: {
2021 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2022
2023 // Queue up the class type into which this points.
2024 Queue.push_back(MemberPtr->getClass());
2025
2026 // And directly continue with the pointee type.
2027 T = MemberPtr->getPointeeType().getTypePtr();
2028 continue;
2029 }
2030
2031 // As an extension, treat this like a normal pointer.
2032 case Type::BlockPointer:
2033 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2034 continue;
2035
2036 // References aren't covered by the standard, but that's such an
2037 // obvious defect that we cover them anyway.
2038 case Type::LValueReference:
2039 case Type::RValueReference:
2040 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2041 continue;
2042
2043 // These are fundamental types.
2044 case Type::Vector:
2045 case Type::ExtVector:
2046 case Type::Complex:
2047 break;
2048
Douglas Gregorf25760e2011-04-12 01:02:45 +00002049 // If T is an Objective-C object or interface type, or a pointer to an
2050 // object or interface type, the associated namespace is the global
2051 // namespace.
John McCallfa4edcf2010-05-28 06:08:54 +00002052 case Type::ObjCObject:
2053 case Type::ObjCInterface:
2054 case Type::ObjCObjectPointer:
Douglas Gregorf25760e2011-04-12 01:02:45 +00002055 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCallfa4edcf2010-05-28 06:08:54 +00002056 break;
Eli Friedmanb001de72011-10-06 23:00:33 +00002057
2058 // Atomic types are just wrappers; use the associations of the
2059 // contained type.
2060 case Type::Atomic:
2061 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2062 continue;
John McCallfa4edcf2010-05-28 06:08:54 +00002063 }
2064
2065 if (Queue.empty()) break;
2066 T = Queue.back();
2067 Queue.pop_back();
Douglas Gregorfa047642009-02-04 00:32:51 +00002068 }
Douglas Gregorfa047642009-02-04 00:32:51 +00002069}
2070
2071/// \brief Find the associated classes and namespaces for
2072/// argument-dependent lookup for a call with the given set of
2073/// arguments.
2074///
2075/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00002076/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00002077/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00002078void
Douglas Gregorfa047642009-02-04 00:32:51 +00002079Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
2080 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00002081 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002082 AssociatedNamespaces.clear();
2083 AssociatedClasses.clear();
2084
John McCallc7e04da2010-05-28 18:45:08 +00002085 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
2086
Douglas Gregorfa047642009-02-04 00:32:51 +00002087 // C++ [basic.lookup.koenig]p2:
2088 // For each argument type T in the function call, there is a set
2089 // of zero or more associated namespaces and a set of zero or more
2090 // associated classes to be considered. The sets of namespaces and
2091 // classes is determined entirely by the types of the function
2092 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00002093 // argument).
Douglas Gregorfa047642009-02-04 00:32:51 +00002094 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
2095 Expr *Arg = Args[ArgIdx];
2096
2097 if (Arg->getType() != Context.OverloadTy) {
John McCallc7e04da2010-05-28 18:45:08 +00002098 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002099 continue;
2100 }
2101
2102 // [...] In addition, if the argument is the name or address of a
2103 // set of overloaded functions and/or function templates, its
2104 // associated classes and namespaces are the union of those
2105 // associated with each of the members of the set: the namespace
2106 // in which the function or function template is defined and the
2107 // classes and namespaces associated with its (non-dependent)
2108 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00002109 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00002110 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCall2de56d12010-08-25 11:45:40 +00002111 if (unaryOp->getOpcode() == UO_AddrOf)
John McCallba135432009-11-21 08:51:07 +00002112 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002113
John McCallc7e04da2010-05-28 18:45:08 +00002114 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2115 if (!ULE) continue;
John McCallba135432009-11-21 08:51:07 +00002116
John McCallc7e04da2010-05-28 18:45:08 +00002117 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2118 I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00002119 // Look through any using declarations to find the underlying function.
2120 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002121
Chandler Carruthbd647292009-12-29 06:17:27 +00002122 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2123 if (!FDecl)
2124 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002125
2126 // Add the classes and namespaces associated with the parameter
2127 // types and return type of this function.
John McCallc7e04da2010-05-28 18:45:08 +00002128 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002129 }
2130 }
2131}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002132
2133/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2134/// an acceptable non-member overloaded operator for a call whose
2135/// arguments have types T1 (and, if non-empty, T2). This routine
2136/// implements the check in C++ [over.match.oper]p3b2 concerning
2137/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00002138static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002139IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2140 QualType T1, QualType T2,
2141 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00002142 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2143 return true;
2144
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002145 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2146 return true;
2147
John McCall183700f2009-09-21 23:43:11 +00002148 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002149 if (Proto->getNumArgs() < 1)
2150 return false;
2151
2152 if (T1->isEnumeralType()) {
2153 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002154 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002155 return true;
2156 }
2157
2158 if (Proto->getNumArgs() < 2)
2159 return false;
2160
2161 if (!T2.isNull() && T2->isEnumeralType()) {
2162 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002163 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002164 return true;
2165 }
2166
2167 return false;
2168}
2169
John McCall7d384dd2009-11-18 07:57:50 +00002170NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002171 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00002172 LookupNameKind NameKind,
2173 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002174 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00002175 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00002176 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00002177}
2178
Douglas Gregor6e378de2009-04-23 23:18:26 +00002179/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002180ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002181 SourceLocation IdLoc) {
2182 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2183 LookupObjCProtocolName);
Douglas Gregor6e378de2009-04-23 23:18:26 +00002184 return cast_or_null<ObjCProtocolDecl>(D);
2185}
2186
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002187void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00002188 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00002189 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002190 // C++ [over.match.oper]p3:
2191 // -- The set of non-member candidates is the result of the
2192 // unqualified lookup of operator@ in the context of the
2193 // expression according to the usual rules for name lookup in
2194 // unqualified function calls (3.4.2) except that all member
2195 // functions are ignored. However, if no operand has a class
2196 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00002197 // that have a first parameter of type T1 or "reference to
2198 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002199 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00002200 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002201 // when T2 is an enumeration type, are candidate functions.
2202 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00002203 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2204 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002205
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002206 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2207
John McCallf36e02d2009-10-09 21:13:30 +00002208 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002209 return;
2210
2211 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2212 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002213 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2214 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002215 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002216 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00002217 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002218 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00002219 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00002220 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00002221 // later?
2222 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002223 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00002224 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002225 }
2226}
2227
Sean Huntc39b6bc2011-06-24 02:11:39 +00002228Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Sean Hunt308742c2011-06-04 04:32:43 +00002229 CXXSpecialMember SM,
2230 bool ConstArg,
2231 bool VolatileArg,
2232 bool RValueThis,
2233 bool ConstThis,
2234 bool VolatileThis) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002235 RD = RD->getDefinition();
2236 assert((RD && !RD->isBeingDefined()) &&
Sean Hunt308742c2011-06-04 04:32:43 +00002237 "doing special member lookup into record that isn't fully complete");
2238 if (RValueThis || ConstThis || VolatileThis)
2239 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2240 "constructors and destructors always have unqualified lvalue this");
2241 if (ConstArg || VolatileArg)
2242 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2243 "parameter-less special members can't have qualified arguments");
2244
2245 llvm::FoldingSetNodeID ID;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002246 ID.AddPointer(RD);
Sean Hunt308742c2011-06-04 04:32:43 +00002247 ID.AddInteger(SM);
2248 ID.AddInteger(ConstArg);
2249 ID.AddInteger(VolatileArg);
2250 ID.AddInteger(RValueThis);
2251 ID.AddInteger(ConstThis);
2252 ID.AddInteger(VolatileThis);
2253
2254 void *InsertPoint;
2255 SpecialMemberOverloadResult *Result =
2256 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2257
2258 // This was already cached
2259 if (Result)
2260 return Result;
2261
Sean Hunt30543582011-06-07 00:11:58 +00002262 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2263 Result = new (Result) SpecialMemberOverloadResult(ID);
Sean Hunt308742c2011-06-04 04:32:43 +00002264 SpecialMemberCache.InsertNode(Result, InsertPoint);
2265
2266 if (SM == CXXDestructor) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002267 if (!RD->hasDeclaredDestructor())
2268 DeclareImplicitDestructor(RD);
2269 CXXDestructorDecl *DD = RD->getDestructor();
Sean Hunt308742c2011-06-04 04:32:43 +00002270 assert(DD && "record without a destructor");
2271 Result->setMethod(DD);
2272 Result->setSuccess(DD->isDeleted());
2273 Result->setConstParamMatch(false);
2274 return Result;
2275 }
2276
Sean Huntb320e0c2011-06-10 03:50:41 +00002277 // Prepare for overload resolution. Here we construct a synthetic argument
2278 // if necessary and make sure that implicit functions are declared.
Sean Huntc39b6bc2011-06-24 02:11:39 +00002279 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Sean Huntb320e0c2011-06-10 03:50:41 +00002280 DeclarationName Name;
2281 Expr *Arg = 0;
2282 unsigned NumArgs;
2283
2284 if (SM == CXXDefaultConstructor) {
2285 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2286 NumArgs = 0;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002287 if (RD->needsImplicitDefaultConstructor())
2288 DeclareImplicitDefaultConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002289 } else {
2290 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2291 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002292 if (!RD->hasDeclaredCopyConstructor())
2293 DeclareImplicitCopyConstructor(RD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002294 if (getLangOptions().CPlusPlus0x && RD->needsImplicitMoveConstructor())
2295 DeclareImplicitMoveConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002296 } else {
2297 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002298 if (!RD->hasDeclaredCopyAssignment())
2299 DeclareImplicitCopyAssignment(RD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002300 if (getLangOptions().CPlusPlus0x && RD->needsImplicitMoveAssignment())
2301 DeclareImplicitMoveAssignment(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002302 }
2303
2304 QualType ArgType = CanTy;
2305 if (ConstArg)
2306 ArgType.addConst();
2307 if (VolatileArg)
2308 ArgType.addVolatile();
2309
2310 // This isn't /really/ specified by the standard, but it's implied
2311 // we should be working from an RValue in the case of move to ensure
2312 // that we prefer to bind to rvalue references, and an LValue in the
2313 // case of copy to ensure we don't bind to rvalue references.
2314 // Possibly an XValue is actually correct in the case of move, but
2315 // there is no semantic difference for class types in this restricted
2316 // case.
2317 ExprValueKind VK;
Sean Huntab183df2011-06-22 22:13:13 +00002318 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Sean Huntb320e0c2011-06-10 03:50:41 +00002319 VK = VK_LValue;
2320 else
2321 VK = VK_RValue;
2322
2323 NumArgs = 1;
2324 Arg = new (Context) OpaqueValueExpr(SourceLocation(), ArgType, VK);
2325 }
2326
2327 // Create the object argument
2328 QualType ThisTy = CanTy;
2329 if (ConstThis)
2330 ThisTy.addConst();
2331 if (VolatileThis)
2332 ThisTy.addVolatile();
Sean Hunt4cc12c62011-06-23 00:26:20 +00002333 Expr::Classification Classification =
Sean Huntb320e0c2011-06-10 03:50:41 +00002334 (new (Context) OpaqueValueExpr(SourceLocation(), ThisTy,
2335 RValueThis ? VK_RValue : VK_LValue))->
2336 Classify(Context);
2337
2338 // Now we perform lookup on the name we computed earlier and do overload
2339 // resolution. Lookup is only performed directly into the class since there
2340 // will always be a (possibly implicit) declaration to shadow any others.
2341 OverloadCandidateSet OCS((SourceLocation()));
2342 DeclContext::lookup_iterator I, E;
2343 Result->setConstParamMatch(false);
2344
Sean Huntc39b6bc2011-06-24 02:11:39 +00002345 llvm::tie(I, E) = RD->lookup(Name);
Sean Huntb320e0c2011-06-10 03:50:41 +00002346 assert((I != E) &&
2347 "lookup for a constructor or assignment operator was empty");
2348 for ( ; I != E; ++I) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002349 Decl *Cand = *I;
Sean Hunt4cc12c62011-06-23 00:26:20 +00002350
Sean Huntc39b6bc2011-06-24 02:11:39 +00002351 if (Cand->isInvalidDecl())
Sean Huntb320e0c2011-06-10 03:50:41 +00002352 continue;
2353
Sean Huntc39b6bc2011-06-24 02:11:39 +00002354 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2355 // FIXME: [namespace.udecl]p15 says that we should only consider a
2356 // using declaration here if it does not match a declaration in the
2357 // derived class. We do not implement this correctly in other cases
2358 // either.
2359 Cand = U->getTargetDecl();
2360
2361 if (Cand->isInvalidDecl())
2362 continue;
2363 }
2364
2365 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002366 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Sean Huntc39b6bc2011-06-24 02:11:39 +00002367 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Sean Hunt4cc12c62011-06-23 00:26:20 +00002368 Classification, &Arg, NumArgs, OCS, true);
2369 else
2370 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public), &Arg,
2371 NumArgs, OCS, true);
Sean Huntb320e0c2011-06-10 03:50:41 +00002372
2373 // Here we're looking for a const parameter to speed up creation of
2374 // implicit copy methods.
2375 if ((SM == CXXCopyAssignment && M->isCopyAssignmentOperator()) ||
2376 (SM == CXXCopyConstructor &&
2377 cast<CXXConstructorDecl>(M)->isCopyConstructor())) {
2378 QualType ArgType = M->getType()->getAs<FunctionProtoType>()->getArgType(0);
Sean Hunt661c67a2011-06-21 23:42:56 +00002379 if (!ArgType->isReferenceType() ||
2380 ArgType->getPointeeType().isConstQualified())
Sean Huntb320e0c2011-06-10 03:50:41 +00002381 Result->setConstParamMatch(true);
2382 }
Sean Hunt431a1cb2011-06-22 02:58:46 +00002383 } else if (FunctionTemplateDecl *Tmpl =
Sean Huntc39b6bc2011-06-24 02:11:39 +00002384 dyn_cast<FunctionTemplateDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002385 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2386 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Sean Huntc39b6bc2011-06-24 02:11:39 +00002387 RD, 0, ThisTy, Classification, &Arg, NumArgs,
Sean Hunt4cc12c62011-06-23 00:26:20 +00002388 OCS, true);
2389 else
2390 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
2391 0, &Arg, NumArgs, OCS, true);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002392 } else {
2393 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Sean Huntb320e0c2011-06-10 03:50:41 +00002394 }
2395 }
2396
2397 OverloadCandidateSet::iterator Best;
2398 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2399 case OR_Success:
2400 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2401 Result->setSuccess(true);
2402 break;
2403
2404 case OR_Deleted:
2405 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2406 Result->setSuccess(false);
2407 break;
2408
2409 case OR_Ambiguous:
2410 case OR_No_Viable_Function:
2411 Result->setMethod(0);
2412 Result->setSuccess(false);
2413 break;
2414 }
2415
2416 return Result;
2417}
2418
2419/// \brief Look up the default constructor for the given class.
2420CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Sean Huntc530d172011-06-10 04:44:37 +00002421 SpecialMemberOverloadResult *Result =
Sean Huntb320e0c2011-06-10 03:50:41 +00002422 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2423 false, false);
2424
2425 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Sean Hunt308742c2011-06-04 04:32:43 +00002426}
2427
Sean Hunt661c67a2011-06-21 23:42:56 +00002428/// \brief Look up the copying constructor for the given class.
2429CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
2430 unsigned Quals,
2431 bool *ConstParamMatch) {
Sean Huntc530d172011-06-10 04:44:37 +00002432 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2433 "non-const, non-volatile qualifiers for copy ctor arg");
2434 SpecialMemberOverloadResult *Result =
2435 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2436 Quals & Qualifiers::Volatile, false, false, false);
2437
2438 if (ConstParamMatch)
2439 *ConstParamMatch = Result->hasConstParamMatch();
2440
2441 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2442}
2443
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002444/// \brief Look up the moving constructor for the given class.
2445CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class) {
2446 SpecialMemberOverloadResult *Result =
2447 LookupSpecialMember(Class, CXXMoveConstructor, false,
2448 false, false, false, false);
2449
2450 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2451}
2452
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002453/// \brief Look up the constructors for the given class.
2454DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002455 // If the implicit constructors have not yet been declared, do so now.
Douglas Gregor18274032010-07-03 00:47:00 +00002456 if (CanDeclareSpecialMemberFunction(Context, Class)) {
Sean Huntcdee3fe2011-05-11 22:34:38 +00002457 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002458 DeclareImplicitDefaultConstructor(Class);
2459 if (!Class->hasDeclaredCopyConstructor())
2460 DeclareImplicitCopyConstructor(Class);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002461 if (getLangOptions().CPlusPlus0x && Class->needsImplicitMoveConstructor())
2462 DeclareImplicitMoveConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +00002463 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002464
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002465 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2466 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2467 return Class->lookup(Name);
2468}
2469
Sean Hunt661c67a2011-06-21 23:42:56 +00002470/// \brief Look up the copying assignment operator for the given class.
2471CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2472 unsigned Quals, bool RValueThis,
2473 unsigned ThisQuals,
2474 bool *ConstParamMatch) {
2475 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2476 "non-const, non-volatile qualifiers for copy assignment arg");
2477 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2478 "non-const, non-volatile qualifiers for copy assignment this");
2479 SpecialMemberOverloadResult *Result =
2480 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2481 Quals & Qualifiers::Volatile, RValueThis,
2482 ThisQuals & Qualifiers::Const,
2483 ThisQuals & Qualifiers::Volatile);
2484
2485 if (ConstParamMatch)
2486 *ConstParamMatch = Result->hasConstParamMatch();
2487
2488 return Result->getMethod();
2489}
2490
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002491/// \brief Look up the moving assignment operator for the given class.
2492CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
2493 bool RValueThis,
2494 unsigned ThisQuals) {
2495 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2496 "non-const, non-volatile qualifiers for copy assignment this");
2497 SpecialMemberOverloadResult *Result =
2498 LookupSpecialMember(Class, CXXMoveAssignment, false, false, RValueThis,
2499 ThisQuals & Qualifiers::Const,
2500 ThisQuals & Qualifiers::Volatile);
2501
2502 return Result->getMethod();
2503}
2504
Douglas Gregordb89f282010-07-01 22:47:18 +00002505/// \brief Look for the destructor of the given class.
2506///
Sean Huntc5c9b532011-06-03 21:10:40 +00002507/// During semantic analysis, this routine should be used in lieu of
2508/// CXXRecordDecl::getDestructor().
Douglas Gregordb89f282010-07-01 22:47:18 +00002509///
2510/// \returns The destructor for this class.
2511CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Sean Hunt308742c2011-06-04 04:32:43 +00002512 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2513 false, false, false,
2514 false, false)->getMethod());
Douglas Gregordb89f282010-07-01 22:47:18 +00002515}
2516
John McCall7edb5fd2010-01-26 07:16:45 +00002517void ADLResult::insert(NamedDecl *New) {
2518 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2519
2520 // If we haven't yet seen a decl for this key, or the last decl
2521 // was exactly this one, we're done.
2522 if (Old == 0 || Old == New) {
2523 Old = New;
2524 return;
2525 }
2526
2527 // Otherwise, decide which is a more recent redeclaration.
2528 FunctionDecl *OldFD, *NewFD;
2529 if (isa<FunctionTemplateDecl>(New)) {
2530 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2531 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2532 } else {
2533 OldFD = cast<FunctionDecl>(Old);
2534 NewFD = cast<FunctionDecl>(New);
2535 }
2536
2537 FunctionDecl *Cursor = NewFD;
2538 while (true) {
2539 Cursor = Cursor->getPreviousDeclaration();
2540
2541 // If we got to the end without finding OldFD, OldFD is the newer
2542 // declaration; leave things as they are.
2543 if (!Cursor) return;
2544
2545 // If we do find OldFD, then NewFD is newer.
2546 if (Cursor == OldFD) break;
2547
2548 // Otherwise, keep looking.
2549 }
2550
2551 Old = New;
2552}
2553
Sebastian Redl644be852009-10-23 19:23:15 +00002554void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002555 Expr **Args, unsigned NumArgs,
Richard Smithad762fc2011-04-14 22:09:26 +00002556 ADLResult &Result,
2557 bool StdNamespaceIsAssociated) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002558 // Find all of the associated namespaces and classes based on the
2559 // arguments we have.
2560 AssociatedNamespaceSet AssociatedNamespaces;
2561 AssociatedClassSet AssociatedClasses;
Mike Stump1eb44332009-09-09 15:08:12 +00002562 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCall6ff07852009-08-07 22:18:02 +00002563 AssociatedNamespaces,
2564 AssociatedClasses);
Richard Smithad762fc2011-04-14 22:09:26 +00002565 if (StdNamespaceIsAssociated && StdNamespace)
2566 AssociatedNamespaces.insert(getStdNamespace());
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002567
Sebastian Redl644be852009-10-23 19:23:15 +00002568 QualType T1, T2;
2569 if (Operator) {
2570 T1 = Args[0]->getType();
2571 if (NumArgs >= 2)
2572 T2 = Args[1]->getType();
2573 }
2574
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002575 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002576 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2577 // and let Y be the lookup set produced by argument dependent
2578 // lookup (defined as follows). If X contains [...] then Y is
2579 // empty. Otherwise Y is the set of declarations found in the
2580 // namespaces associated with the argument types as described
2581 // below. The set of declarations found by the lookup of the name
2582 // is the union of X and Y.
2583 //
2584 // Here, we compute Y and add its members to the overloaded
2585 // candidate set.
2586 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002587 NSEnd = AssociatedNamespaces.end();
2588 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002589 // When considering an associated namespace, the lookup is the
2590 // same as the lookup performed when the associated namespace is
2591 // used as a qualifier (3.4.3.2) except that:
2592 //
2593 // -- Any using-directives in the associated namespace are
2594 // ignored.
2595 //
John McCall6ff07852009-08-07 22:18:02 +00002596 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002597 // associated classes are visible within their respective
2598 // namespaces even if they are not visible during an ordinary
2599 // lookup (11.4).
2600 DeclContext::lookup_iterator I, E;
John McCall3f9a8a62009-08-11 06:59:38 +00002601 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall6e266892010-01-26 03:27:55 +00002602 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00002603 // If the only declaration here is an ordinary friend, consider
2604 // it only if it was declared in an associated classes.
2605 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00002606 DeclContext *LexDC = D->getLexicalDeclContext();
2607 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2608 continue;
2609 }
Mike Stump1eb44332009-09-09 15:08:12 +00002610
John McCalla113e722010-01-26 06:04:06 +00002611 if (isa<UsingShadowDecl>(D))
2612 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00002613
John McCalla113e722010-01-26 06:04:06 +00002614 if (isa<FunctionDecl>(D)) {
2615 if (Operator &&
2616 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2617 T1, T2, Context))
2618 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00002619 } else if (!isa<FunctionTemplateDecl>(D))
2620 continue;
2621
2622 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00002623 }
2624 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002625}
Douglas Gregor546be3c2009-12-30 17:04:44 +00002626
2627//----------------------------------------------------------------------------
2628// Search for all visible declarations.
2629//----------------------------------------------------------------------------
2630VisibleDeclConsumer::~VisibleDeclConsumer() { }
2631
2632namespace {
2633
2634class ShadowContextRAII;
2635
2636class VisibleDeclsRecord {
2637public:
2638 /// \brief An entry in the shadow map, which is optimized to store a
2639 /// single declaration (the common case) but can also store a list
2640 /// of declarations.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002641 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002642
2643private:
2644 /// \brief A mapping from declaration names to the declarations that have
2645 /// this name within a particular scope.
2646 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2647
2648 /// \brief A list of shadow maps, which is used to model name hiding.
2649 std::list<ShadowMap> ShadowMaps;
2650
2651 /// \brief The declaration contexts we have already visited.
2652 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2653
2654 friend class ShadowContextRAII;
2655
2656public:
2657 /// \brief Determine whether we have already visited this context
2658 /// (and, if not, note that we are going to visit that context now).
2659 bool visitedContext(DeclContext *Ctx) {
2660 return !VisitedContexts.insert(Ctx);
2661 }
2662
Douglas Gregor8071e422010-08-15 06:18:01 +00002663 bool alreadyVisitedContext(DeclContext *Ctx) {
2664 return VisitedContexts.count(Ctx);
2665 }
2666
Douglas Gregor546be3c2009-12-30 17:04:44 +00002667 /// \brief Determine whether the given declaration is hidden in the
2668 /// current scope.
2669 ///
2670 /// \returns the declaration that hides the given declaration, or
2671 /// NULL if no such declaration exists.
2672 NamedDecl *checkHidden(NamedDecl *ND);
2673
2674 /// \brief Add a declaration to the current shadow map.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002675 void add(NamedDecl *ND) {
2676 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2677 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002678};
2679
2680/// \brief RAII object that records when we've entered a shadow context.
2681class ShadowContextRAII {
2682 VisibleDeclsRecord &Visible;
2683
2684 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2685
2686public:
2687 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2688 Visible.ShadowMaps.push_back(ShadowMap());
2689 }
2690
2691 ~ShadowContextRAII() {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002692 Visible.ShadowMaps.pop_back();
2693 }
2694};
2695
2696} // end anonymous namespace
2697
Douglas Gregor546be3c2009-12-30 17:04:44 +00002698NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002699 // Look through using declarations.
2700 ND = ND->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002701
Douglas Gregor546be3c2009-12-30 17:04:44 +00002702 unsigned IDNS = ND->getIdentifierNamespace();
2703 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2704 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2705 SM != SMEnd; ++SM) {
2706 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2707 if (Pos == SM->end())
2708 continue;
2709
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002710 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00002711 IEnd = Pos->second.end();
2712 I != IEnd; ++I) {
2713 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002714 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002715 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor546be3c2009-12-30 17:04:44 +00002716 Decl::IDNS_ObjCProtocol)))
2717 continue;
2718
2719 // Protocols are in distinct namespaces from everything else.
2720 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2721 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2722 (*I)->getIdentifierNamespace() != IDNS)
2723 continue;
2724
Douglas Gregor0cc84042010-01-14 15:47:35 +00002725 // Functions and function templates in the same scope overload
2726 // rather than hide. FIXME: Look for hiding based on function
2727 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002728 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002729 ND->isFunctionOrFunctionTemplate() &&
2730 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002731 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002732
Douglas Gregor546be3c2009-12-30 17:04:44 +00002733 // We've found a declaration that hides this one.
2734 return *I;
2735 }
2736 }
2737
2738 return 0;
2739}
2740
2741static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2742 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002743 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002744 VisibleDeclConsumer &Consumer,
2745 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00002746 if (!Ctx)
2747 return;
2748
Douglas Gregor546be3c2009-12-30 17:04:44 +00002749 // Make sure we don't visit the same context twice.
2750 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2751 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002752
Douglas Gregor4923aa22010-07-02 20:37:36 +00002753 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2754 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2755
Douglas Gregor546be3c2009-12-30 17:04:44 +00002756 // Enumerate all of the results in this context.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002757 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002758 CurCtx = CurCtx->getNextContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002759 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00002760 DEnd = CurCtx->decls_end();
2761 D != DEnd; ++D) {
Douglas Gregor70c23352010-12-09 21:44:02 +00002762 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) {
Douglas Gregor55368912011-12-14 16:03:29 +00002763 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00002764 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002765 Visited.add(ND);
2766 }
Douglas Gregor70c23352010-12-09 21:44:02 +00002767 } else if (ObjCForwardProtocolDecl *ForwardProto
2768 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
2769 for (ObjCForwardProtocolDecl::protocol_iterator
2770 P = ForwardProto->protocol_begin(),
2771 PEnd = ForwardProto->protocol_end();
2772 P != PEnd;
2773 ++P) {
Douglas Gregor55368912011-12-14 16:03:29 +00002774 if (NamedDecl *ND = Result.getAcceptableDecl(*P)) {
2775 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
2776 Visited.add(ND);
Douglas Gregor70c23352010-12-09 21:44:02 +00002777 }
2778 }
Douglas Gregord98abd82011-02-16 01:39:26 +00002779 } else if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D)) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00002780 ObjCInterfaceDecl *IFace = Class->getForwardInterfaceDecl();
Douglas Gregor55368912011-12-14 16:03:29 +00002781 if (NamedDecl *ND = Result.getAcceptableDecl(IFace)) {
2782 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
2783 Visited.add(ND);
Douglas Gregord98abd82011-02-16 01:39:26 +00002784 }
Douglas Gregor70c23352010-12-09 21:44:02 +00002785 }
Douglas Gregord98abd82011-02-16 01:39:26 +00002786
Sebastian Redl410c4f22010-08-31 20:53:31 +00002787 // Visit transparent contexts and inline namespaces inside this context.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002788 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
Sebastian Redl410c4f22010-08-31 20:53:31 +00002789 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Douglas Gregor0cc84042010-01-14 15:47:35 +00002790 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002791 Consumer, Visited);
2792 }
2793 }
2794 }
2795
2796 // Traverse using directives for qualified name lookup.
2797 if (QualifiedNameLookup) {
2798 ShadowContextRAII Shadow(Visited);
2799 DeclContext::udir_iterator I, E;
2800 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002801 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002802 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002803 }
2804 }
2805
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002806 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002807 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00002808 if (!Record->hasDefinition())
2809 return;
2810
Douglas Gregor546be3c2009-12-30 17:04:44 +00002811 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2812 BEnd = Record->bases_end();
2813 B != BEnd; ++B) {
2814 QualType BaseType = B->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002815
Douglas Gregor546be3c2009-12-30 17:04:44 +00002816 // Don't look into dependent bases, because name lookup can't look
2817 // there anyway.
2818 if (BaseType->isDependentType())
2819 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002820
Douglas Gregor546be3c2009-12-30 17:04:44 +00002821 const RecordType *Record = BaseType->getAs<RecordType>();
2822 if (!Record)
2823 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002824
Douglas Gregor546be3c2009-12-30 17:04:44 +00002825 // FIXME: It would be nice to be able to determine whether referencing
2826 // a particular member would be ambiguous. For example, given
2827 //
2828 // struct A { int member; };
2829 // struct B { int member; };
2830 // struct C : A, B { };
2831 //
2832 // void f(C *c) { c->### }
2833 //
2834 // accessing 'member' would result in an ambiguity. However, we
2835 // could be smart enough to qualify the member with the base
2836 // class, e.g.,
2837 //
2838 // c->B::member
2839 //
2840 // or
2841 //
2842 // c->A::member
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002843
Douglas Gregor546be3c2009-12-30 17:04:44 +00002844 // Find results in this base class (and its bases).
2845 ShadowContextRAII Shadow(Visited);
2846 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002847 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002848 }
2849 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002850
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002851 // Traverse the contexts of Objective-C classes.
2852 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2853 // Traverse categories.
2854 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2855 Category; Category = Category->getNextClassCategory()) {
2856 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002857 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002858 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002859 }
2860
2861 // Traverse protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00002862 for (ObjCInterfaceDecl::all_protocol_iterator
2863 I = IFace->all_referenced_protocol_begin(),
2864 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002865 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002866 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002867 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002868 }
2869
2870 // Traverse the superclass.
2871 if (IFace->getSuperClass()) {
2872 ShadowContextRAII Shadow(Visited);
2873 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002874 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002875 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002876
Douglas Gregorc220a182010-04-19 18:02:19 +00002877 // If there is an implementation, traverse it. We do this to find
2878 // synthesized ivars.
2879 if (IFace->getImplementation()) {
2880 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002881 LookupVisibleDecls(IFace->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00002882 QualifiedNameLookup, true, Consumer, Visited);
2883 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002884 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2885 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2886 E = Protocol->protocol_end(); I != E; ++I) {
2887 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002888 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002889 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002890 }
2891 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2892 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2893 E = Category->protocol_end(); I != E; ++I) {
2894 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002895 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002896 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002897 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002898
Douglas Gregorc220a182010-04-19 18:02:19 +00002899 // If there is an implementation, traverse it.
2900 if (Category->getImplementation()) {
2901 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002902 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00002903 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002904 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002905 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002906}
2907
2908static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2909 UnqualUsingDirectiveSet &UDirs,
2910 VisibleDeclConsumer &Consumer,
2911 VisibleDeclsRecord &Visited) {
2912 if (!S)
2913 return;
2914
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002915 if (!S->getEntity() ||
2916 (!S->getParent() &&
Douglas Gregor8071e422010-08-15 06:18:01 +00002917 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor539c5c32010-01-07 00:31:29 +00002918 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2919 // Walk through the declarations in this Scope.
2920 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2921 D != DEnd; ++D) {
John McCalld226f652010-08-21 09:40:31 +00002922 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor55368912011-12-14 16:03:29 +00002923 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00002924 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002925 Visited.add(ND);
2926 }
2927 }
2928 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002929
Douglas Gregor711be1e2010-03-15 14:33:29 +00002930 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00002931 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00002932 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002933 // Look into this scope's declaration context, along with any of its
2934 // parent lookup contexts (e.g., enclosing classes), up to the point
2935 // where we hit the context stored in the next outer scope.
2936 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00002937 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002938
Douglas Gregordbdf5e72010-03-15 15:26:48 +00002939 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002940 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002941 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2942 if (Method->isInstanceMethod()) {
2943 // For instance methods, look for ivars in the method's interface.
2944 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2945 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregorca45da02010-11-02 20:36:02 +00002946 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002947 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Fariborz Jahanian8697d302011-08-31 22:24:06 +00002948 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorca45da02010-11-02 20:36:02 +00002949 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002950 }
2951
2952 // We've already performed all of the name lookup that we need
2953 // to for Objective-C methods; the next context will be the
2954 // outer scope.
2955 break;
2956 }
2957
Douglas Gregor546be3c2009-12-30 17:04:44 +00002958 if (Ctx->isFunctionOrMethod())
2959 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002960
2961 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002962 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002963 }
2964 } else if (!S->getParent()) {
2965 // Look into the translation unit scope. We walk through the translation
2966 // unit's declaration context, because the Scope itself won't have all of
2967 // the declarations if we loaded a precompiled header.
2968 // FIXME: We would like the translation unit's Scope object to point to the
2969 // translation unit, so we don't need this special "if" branch. However,
2970 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002971 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002972 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00002973 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002974 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002975 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002976 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002977 }
2978
Douglas Gregor546be3c2009-12-30 17:04:44 +00002979 if (Entity) {
2980 // Lookup visible declarations in any namespaces found by using
2981 // directives.
2982 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2983 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2984 for (; UI != UEnd; ++UI)
2985 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002986 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002987 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002988 }
2989
2990 // Lookup names in the parent scope.
2991 ShadowContextRAII Shadow(Visited);
2992 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2993}
2994
2995void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00002996 VisibleDeclConsumer &Consumer,
2997 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002998 // Determine the set of using directives available during
2999 // unqualified name lookup.
3000 Scope *Initial = S;
3001 UnqualUsingDirectiveSet UDirs;
3002 if (getLangOptions().CPlusPlus) {
3003 // Find the first namespace or translation-unit scope.
3004 while (S && !isNamespaceOrTranslationUnitScope(S))
3005 S = S->getParent();
3006
3007 UDirs.visitScopeChain(Initial, S);
3008 }
3009 UDirs.done();
3010
3011 // Look for visible declarations.
3012 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3013 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003014 if (!IncludeGlobalScope)
3015 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003016 ShadowContextRAII Shadow(Visited);
3017 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3018}
3019
3020void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00003021 VisibleDeclConsumer &Consumer,
3022 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003023 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3024 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003025 if (!IncludeGlobalScope)
3026 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003027 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003028 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003029 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003030}
3031
Chris Lattner4ae493c2011-02-18 02:08:43 +00003032/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara67843042011-03-05 18:21:20 +00003033/// If GnuLabelLoc is a valid source location, then this is a definition
3034/// of an __label__ label name, otherwise it is a normal label definition
3035/// or use.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003036LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara67843042011-03-05 18:21:20 +00003037 SourceLocation GnuLabelLoc) {
Chris Lattner337e5502011-02-18 01:27:55 +00003038 // Do a lookup to see if we have a label with this name already.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003039 NamedDecl *Res = 0;
Abramo Bagnara67843042011-03-05 18:21:20 +00003040
3041 if (GnuLabelLoc.isValid()) {
3042 // Local label definitions always shadow existing labels.
3043 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3044 Scope *S = CurScope;
3045 PushOnScopeChains(Res, S, true);
3046 return cast<LabelDecl>(Res);
3047 }
3048
3049 // Not a GNU local label.
3050 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3051 // If we found a label, check to see if it is in the same context as us.
3052 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattner337e5502011-02-18 01:27:55 +00003053 if (Res && Res->getDeclContext() != CurContext)
3054 Res = 0;
Chris Lattner337e5502011-02-18 01:27:55 +00003055 if (Res == 0) {
3056 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara67843042011-03-05 18:21:20 +00003057 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3058 Scope *S = CurScope->getFnParent();
Chris Lattnerfebb5b82011-02-18 21:16:39 +00003059 assert(S && "Not in a function?");
3060 PushOnScopeChains(Res, S, true);
Chris Lattner337e5502011-02-18 01:27:55 +00003061 }
Chris Lattner337e5502011-02-18 01:27:55 +00003062 return cast<LabelDecl>(Res);
3063}
3064
3065//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003066// Typo correction
Chris Lattner337e5502011-02-18 01:27:55 +00003067//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003068
3069namespace {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003070
3071typedef llvm::StringMap<TypoCorrection, llvm::BumpPtrAllocator> TypoResultsMap;
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003072typedef std::map<unsigned, TypoResultsMap *> TypoEditDistanceMap;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003073
3074static const unsigned MaxTypoDistanceResultSets = 5;
3075
Douglas Gregor546be3c2009-12-30 17:04:44 +00003076class TypoCorrectionConsumer : public VisibleDeclConsumer {
3077 /// \brief The name written that is a typo in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003078 StringRef Typo;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003079
3080 /// \brief The results found that have the smallest edit distance
3081 /// found (so far) with the typo name.
Douglas Gregore24b5752010-10-14 20:34:08 +00003082 ///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003083 /// The pointer value being set to the current DeclContext indicates
3084 /// whether there is a keyword with this name.
3085 TypoEditDistanceMap BestResults;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003086
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003087 /// \brief The worst of the best N edit distances found so far.
3088 unsigned MaxEditDistance;
3089
3090 Sema &SemaRef;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003091
Douglas Gregor546be3c2009-12-30 17:04:44 +00003092public:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003093 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003094 : Typo(Typo->getName()),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003095 MaxEditDistance((std::numeric_limits<unsigned>::max)()),
3096 SemaRef(SemaRef) { }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003097
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003098 ~TypoCorrectionConsumer() {
3099 for (TypoEditDistanceMap::iterator I = BestResults.begin(),
3100 IEnd = BestResults.end();
3101 I != IEnd;
3102 ++I)
3103 delete I->second;
3104 }
3105
Erik Verbruggend1205962011-10-06 07:27:49 +00003106 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3107 bool InBaseClass);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003108 void FoundName(StringRef Name);
3109 void addKeywordResult(StringRef Keyword);
3110 void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003111 NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003112 void addCorrection(TypoCorrection Correction);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003113
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003114 typedef TypoResultsMap::iterator result_iterator;
3115 typedef TypoEditDistanceMap::iterator distance_iterator;
3116 distance_iterator begin() { return BestResults.begin(); }
3117 distance_iterator end() { return BestResults.end(); }
3118 void erase(distance_iterator I) { BestResults.erase(I); }
Douglas Gregore24b5752010-10-14 20:34:08 +00003119 unsigned size() const { return BestResults.size(); }
3120 bool empty() const { return BestResults.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003121
Chris Lattner5f9e2722011-07-23 10:55:15 +00003122 TypoCorrection &operator[](StringRef Name) {
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003123 return (*BestResults.begin()->second)[Name];
Douglas Gregor7b824e82010-10-15 13:35:25 +00003124 }
3125
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003126 unsigned getMaxEditDistance() const {
3127 return MaxEditDistance;
3128 }
3129
3130 unsigned getBestEditDistance() {
3131 return (BestResults.empty()) ? MaxEditDistance : BestResults.begin()->first;
3132 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003133};
3134
3135}
3136
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003137void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggend1205962011-10-06 07:27:49 +00003138 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003139 // Don't consider hidden names for typo correction.
3140 if (Hiding)
3141 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003142
Douglas Gregor546be3c2009-12-30 17:04:44 +00003143 // Only consider entities with identifiers for names, ignoring
3144 // special names (constructors, overloaded operators, selectors,
3145 // etc.).
3146 IdentifierInfo *Name = ND->getIdentifier();
3147 if (!Name)
3148 return;
3149
Douglas Gregor95f42922010-10-14 22:11:03 +00003150 FoundName(Name->getName());
3151}
3152
Chris Lattner5f9e2722011-07-23 10:55:15 +00003153void TypoCorrectionConsumer::FoundName(StringRef Name) {
Douglas Gregor362a8f22010-10-19 19:39:10 +00003154 // Use a simple length-based heuristic to determine the minimum possible
3155 // edit distance. If the minimum isn't good enough, bail out early.
3156 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003157 if (MinED > MaxEditDistance || (MinED && Typo.size() / MinED < 3))
Douglas Gregor362a8f22010-10-19 19:39:10 +00003158 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003159
Douglas Gregora1194772010-10-19 22:14:33 +00003160 // Compute an upper bound on the allowable edit distance, so that the
3161 // edit-distance algorithm can short-circuit.
Jay Foadf1cc1d02011-04-23 09:06:00 +00003162 unsigned UpperBound =
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003163 std::min(unsigned((Typo.size() + 2) / 3), MaxEditDistance);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003164
Douglas Gregor546be3c2009-12-30 17:04:44 +00003165 // Compute the edit distance between the typo and the name of this
3166 // entity. If this edit distance is not worse than the best edit
3167 // distance we've seen so far, add it to the list of results.
Douglas Gregora1194772010-10-19 22:14:33 +00003168 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003169
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003170 if (ED > MaxEditDistance) {
Douglas Gregore24b5752010-10-14 20:34:08 +00003171 // This result is worse than the best results we've seen so far;
3172 // ignore it.
3173 return;
3174 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003175
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003176 addName(Name, NULL, ED);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003177}
3178
Chris Lattner5f9e2722011-07-23 10:55:15 +00003179void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00003180 // Compute the edit distance between the typo and this keyword.
3181 // If this edit distance is not worse than the best edit
3182 // distance we've seen so far, add it to the list of results.
3183 unsigned ED = Typo.edit_distance(Keyword);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003184 if (ED > MaxEditDistance) {
Douglas Gregore24b5752010-10-14 20:34:08 +00003185 // This result is worse than the best results we've seen so far;
3186 // ignore it.
3187 return;
3188 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003189
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003190 addName(Keyword, NULL, ED, NULL, true);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003191}
3192
Chris Lattner5f9e2722011-07-23 10:55:15 +00003193void TypoCorrectionConsumer::addName(StringRef Name,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003194 NamedDecl *ND,
3195 unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003196 NestedNameSpecifier *NNS,
3197 bool isKeyword) {
3198 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
3199 if (isKeyword) TC.makeKeyword();
3200 addCorrection(TC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003201}
3202
3203void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003204 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003205 TypoResultsMap *& Map = BestResults[Correction.getEditDistance()];
3206 if (!Map)
3207 Map = new TypoResultsMap;
Chandler Carruth55620532011-06-28 22:48:40 +00003208
3209 TypoCorrection &CurrentCorrection = (*Map)[Name];
3210 if (!CurrentCorrection ||
3211 // FIXME: The following should be rolled up into an operator< on
3212 // TypoCorrection with a more principled definition.
3213 CurrentCorrection.isKeyword() < Correction.isKeyword() ||
3214 Correction.getAsString(SemaRef.getLangOptions()) <
3215 CurrentCorrection.getAsString(SemaRef.getLangOptions()))
3216 CurrentCorrection = Correction;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003217
3218 while (BestResults.size() > MaxTypoDistanceResultSets) {
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003219 TypoEditDistanceMap::iterator Last = BestResults.end();
3220 --Last;
3221 delete Last->second;
3222 BestResults.erase(Last);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003223 }
3224}
3225
3226namespace {
3227
3228class SpecifierInfo {
3229 public:
3230 DeclContext* DeclCtx;
3231 NestedNameSpecifier* NameSpecifier;
3232 unsigned EditDistance;
3233
3234 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3235 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3236};
3237
Chris Lattner5f9e2722011-07-23 10:55:15 +00003238typedef SmallVector<DeclContext*, 4> DeclContextList;
3239typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003240
3241class NamespaceSpecifierSet {
3242 ASTContext &Context;
3243 DeclContextList CurContextChain;
3244 bool isSorted;
3245
3246 SpecifierInfoList Specifiers;
3247 llvm::SmallSetVector<unsigned, 4> Distances;
3248 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3249
3250 /// \brief Helper for building the list of DeclContexts between the current
3251 /// context and the top of the translation unit
3252 static DeclContextList BuildContextChain(DeclContext *Start);
3253
3254 void SortNamespaces();
3255
3256 public:
3257 explicit NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext)
Benjamin Kramerc5bb9d42011-07-05 09:46:31 +00003258 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
3259 isSorted(true) {}
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003260
3261 /// \brief Add the namespace to the set, computing the corresponding
3262 /// NestedNameSpecifier and its distance in the process.
3263 void AddNamespace(NamespaceDecl *ND);
3264
3265 typedef SpecifierInfoList::iterator iterator;
3266 iterator begin() {
3267 if (!isSorted) SortNamespaces();
3268 return Specifiers.begin();
3269 }
3270 iterator end() { return Specifiers.end(); }
3271};
3272
3273}
3274
3275DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003276 assert(Start && "Bulding a context chain from a null context");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003277 DeclContextList Chain;
3278 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3279 DC = DC->getLookupParent()) {
3280 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3281 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3282 !(ND && ND->isAnonymousNamespace()))
3283 Chain.push_back(DC->getPrimaryContext());
3284 }
3285 return Chain;
3286}
3287
3288void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003289 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003290 sortedDistances.append(Distances.begin(), Distances.end());
3291
3292 if (sortedDistances.size() > 1)
3293 std::sort(sortedDistances.begin(), sortedDistances.end());
3294
3295 Specifiers.clear();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003296 for (SmallVector<unsigned, 4>::iterator DI = sortedDistances.begin(),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003297 DIEnd = sortedDistances.end();
3298 DI != DIEnd; ++DI) {
3299 SpecifierInfoList &SpecList = DistanceMap[*DI];
3300 Specifiers.append(SpecList.begin(), SpecList.end());
3301 }
3302
3303 isSorted = true;
3304}
3305
3306void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003307 DeclContext *Ctx = cast<DeclContext>(ND);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003308 NestedNameSpecifier *NNS = NULL;
3309 unsigned NumSpecifiers = 0;
3310 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
3311
3312 // Eliminate common elements from the two DeclContext chains
3313 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3314 CEnd = CurContextChain.rend();
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003315 C != CEnd && !NamespaceDeclChain.empty() &&
3316 NamespaceDeclChain.back() == *C; ++C) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003317 NamespaceDeclChain.pop_back();
3318 }
3319
3320 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3321 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3322 CEnd = NamespaceDeclChain.rend();
3323 C != CEnd; ++C) {
3324 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3325 if (ND) {
3326 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3327 ++NumSpecifiers;
3328 }
3329 }
3330
3331 isSorted = false;
3332 Distances.insert(NumSpecifiers);
3333 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
Douglas Gregoraaf87162010-04-14 20:04:41 +00003334}
3335
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003336/// \brief Perform name lookup for a possible result for typo correction.
3337static void LookupPotentialTypoResult(Sema &SemaRef,
3338 LookupResult &Res,
3339 IdentifierInfo *Name,
3340 Scope *S, CXXScopeSpec *SS,
3341 DeclContext *MemberContext,
3342 bool EnteringContext,
3343 Sema::CorrectTypoContext CTC) {
3344 Res.suppressDiagnostics();
3345 Res.clear();
3346 Res.setLookupName(Name);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003347 if (MemberContext) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003348 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
3349 if (CTC == Sema::CTC_ObjCIvarLookup) {
3350 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3351 Res.addDecl(Ivar);
3352 Res.resolveKind();
3353 return;
3354 }
3355 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003356
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003357 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3358 Res.addDecl(Prop);
3359 Res.resolveKind();
3360 return;
3361 }
3362 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003363
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003364 SemaRef.LookupQualifiedName(Res, MemberContext);
3365 return;
3366 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003367
3368 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003369 EnteringContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003370
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003371 // Fake ivar lookup; this should really be part of
3372 // LookupParsedName.
3373 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3374 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003375 (Res.empty() ||
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003376 (Res.isSingleResult() &&
3377 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003378 if (ObjCIvarDecl *IV
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003379 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3380 Res.addDecl(IV);
3381 Res.resolveKind();
3382 }
3383 }
3384 }
3385}
3386
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003387/// \brief Add keywords to the consumer as possible typo corrections.
3388static void AddKeywordsToConsumer(Sema &SemaRef,
3389 TypoCorrectionConsumer &Consumer,
3390 Scope *S, Sema::CorrectTypoContext CTC) {
3391 // Add context-dependent keywords.
3392 bool WantTypeSpecifiers = false;
3393 bool WantExpressionKeywords = false;
3394 bool WantCXXNamedCasts = false;
3395 bool WantRemainingKeywords = false;
3396 switch (CTC) {
3397 case Sema::CTC_Unknown:
3398 WantTypeSpecifiers = true;
3399 WantExpressionKeywords = true;
3400 WantCXXNamedCasts = true;
3401 WantRemainingKeywords = true;
3402
3403 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
3404 if (Method->getClassInterface() &&
3405 Method->getClassInterface()->getSuperClass())
3406 Consumer.addKeywordResult("super");
3407
3408 break;
3409
3410 case Sema::CTC_NoKeywords:
3411 break;
3412
3413 case Sema::CTC_Type:
3414 WantTypeSpecifiers = true;
3415 break;
3416
3417 case Sema::CTC_ObjCMessageReceiver:
3418 Consumer.addKeywordResult("super");
3419 // Fall through to handle message receivers like expressions.
3420
3421 case Sema::CTC_Expression:
3422 if (SemaRef.getLangOptions().CPlusPlus)
3423 WantTypeSpecifiers = true;
3424 WantExpressionKeywords = true;
3425 // Fall through to get C++ named casts.
3426
3427 case Sema::CTC_CXXCasts:
3428 WantCXXNamedCasts = true;
3429 break;
3430
3431 case Sema::CTC_ObjCPropertyLookup:
3432 // FIXME: Add "isa"?
3433 break;
3434
3435 case Sema::CTC_MemberLookup:
3436 if (SemaRef.getLangOptions().CPlusPlus)
3437 Consumer.addKeywordResult("template");
3438 break;
3439
3440 case Sema::CTC_ObjCIvarLookup:
3441 break;
3442 }
3443
3444 if (WantTypeSpecifiers) {
3445 // Add type-specifier keywords to the set of results.
3446 const char *CTypeSpecs[] = {
3447 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor07f4a062011-07-01 21:27:45 +00003448 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003449 "_Complex", "_Imaginary",
3450 // storage-specifiers as well
3451 "extern", "inline", "static", "typedef"
3452 };
3453
3454 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3455 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3456 Consumer.addKeywordResult(CTypeSpecs[I]);
3457
3458 if (SemaRef.getLangOptions().C99)
3459 Consumer.addKeywordResult("restrict");
3460 if (SemaRef.getLangOptions().Bool || SemaRef.getLangOptions().CPlusPlus)
3461 Consumer.addKeywordResult("bool");
Douglas Gregor07f4a062011-07-01 21:27:45 +00003462 else if (SemaRef.getLangOptions().C99)
3463 Consumer.addKeywordResult("_Bool");
3464
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003465 if (SemaRef.getLangOptions().CPlusPlus) {
3466 Consumer.addKeywordResult("class");
3467 Consumer.addKeywordResult("typename");
3468 Consumer.addKeywordResult("wchar_t");
3469
3470 if (SemaRef.getLangOptions().CPlusPlus0x) {
3471 Consumer.addKeywordResult("char16_t");
3472 Consumer.addKeywordResult("char32_t");
3473 Consumer.addKeywordResult("constexpr");
3474 Consumer.addKeywordResult("decltype");
3475 Consumer.addKeywordResult("thread_local");
3476 }
3477 }
3478
3479 if (SemaRef.getLangOptions().GNUMode)
3480 Consumer.addKeywordResult("typeof");
3481 }
3482
3483 if (WantCXXNamedCasts && SemaRef.getLangOptions().CPlusPlus) {
3484 Consumer.addKeywordResult("const_cast");
3485 Consumer.addKeywordResult("dynamic_cast");
3486 Consumer.addKeywordResult("reinterpret_cast");
3487 Consumer.addKeywordResult("static_cast");
3488 }
3489
3490 if (WantExpressionKeywords) {
3491 Consumer.addKeywordResult("sizeof");
3492 if (SemaRef.getLangOptions().Bool || SemaRef.getLangOptions().CPlusPlus) {
3493 Consumer.addKeywordResult("false");
3494 Consumer.addKeywordResult("true");
3495 }
3496
3497 if (SemaRef.getLangOptions().CPlusPlus) {
3498 const char *CXXExprs[] = {
3499 "delete", "new", "operator", "throw", "typeid"
3500 };
3501 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3502 for (unsigned I = 0; I != NumCXXExprs; ++I)
3503 Consumer.addKeywordResult(CXXExprs[I]);
3504
3505 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3506 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3507 Consumer.addKeywordResult("this");
3508
3509 if (SemaRef.getLangOptions().CPlusPlus0x) {
3510 Consumer.addKeywordResult("alignof");
3511 Consumer.addKeywordResult("nullptr");
3512 }
3513 }
3514 }
3515
3516 if (WantRemainingKeywords) {
3517 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3518 // Statements.
3519 const char *CStmts[] = {
3520 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3521 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3522 for (unsigned I = 0; I != NumCStmts; ++I)
3523 Consumer.addKeywordResult(CStmts[I]);
3524
3525 if (SemaRef.getLangOptions().CPlusPlus) {
3526 Consumer.addKeywordResult("catch");
3527 Consumer.addKeywordResult("try");
3528 }
3529
3530 if (S && S->getBreakParent())
3531 Consumer.addKeywordResult("break");
3532
3533 if (S && S->getContinueParent())
3534 Consumer.addKeywordResult("continue");
3535
3536 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3537 Consumer.addKeywordResult("case");
3538 Consumer.addKeywordResult("default");
3539 }
3540 } else {
3541 if (SemaRef.getLangOptions().CPlusPlus) {
3542 Consumer.addKeywordResult("namespace");
3543 Consumer.addKeywordResult("template");
3544 }
3545
3546 if (S && S->isClassScope()) {
3547 Consumer.addKeywordResult("explicit");
3548 Consumer.addKeywordResult("friend");
3549 Consumer.addKeywordResult("mutable");
3550 Consumer.addKeywordResult("private");
3551 Consumer.addKeywordResult("protected");
3552 Consumer.addKeywordResult("public");
3553 Consumer.addKeywordResult("virtual");
3554 }
3555 }
3556
3557 if (SemaRef.getLangOptions().CPlusPlus) {
3558 Consumer.addKeywordResult("using");
3559
3560 if (SemaRef.getLangOptions().CPlusPlus0x)
3561 Consumer.addKeywordResult("static_assert");
3562 }
3563 }
3564}
3565
Douglas Gregor546be3c2009-12-30 17:04:44 +00003566/// \brief Try to "correct" a typo in the source code by finding
3567/// visible declarations whose names are similar to the name that was
3568/// present in the source code.
3569///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003570/// \param TypoName the \c DeclarationNameInfo structure that contains
3571/// the name that was present in the source code along with its location.
3572///
3573/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003574///
3575/// \param S the scope in which name lookup occurs.
3576///
3577/// \param SS the nested-name-specifier that precedes the name we're
3578/// looking for, if present.
3579///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003580/// \param MemberContext if non-NULL, the context in which to look for
3581/// a member access expression.
3582///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003583/// \param EnteringContext whether we're entering the context described by
Douglas Gregorbb092ba2009-12-31 05:20:13 +00003584/// the nested-name-specifier SS.
3585///
Douglas Gregoraaf87162010-04-14 20:04:41 +00003586/// \param CTC The context in which typo correction occurs, which impacts the
3587/// set of keywords permitted.
3588///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003589/// \param OPT when non-NULL, the search for visible declarations will
3590/// also walk the protocols in the qualified interfaces of \p OPT.
3591///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003592/// \returns a \c TypoCorrection containing the corrected name if the typo
3593/// along with information such as the \c NamedDecl where the corrected name
3594/// was declared, and any additional \c NestedNameSpecifier needed to access
3595/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3596TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3597 Sema::LookupNameKind LookupKind,
3598 Scope *S, CXXScopeSpec *SS,
3599 DeclContext *MemberContext,
3600 bool EnteringContext,
3601 CorrectTypoContext CTC,
3602 const ObjCObjectPointerType *OPT) {
Douglas Gregora0068fc2010-07-09 17:35:33 +00003603 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003604 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003605
Francois Pichet4d604d62011-12-03 15:55:29 +00003606 // In Microsoft mode, don't perform typo correction in a template member
3607 // function dependent context because it interferes with the "lookup into
3608 // dependent bases of class templates" feature.
3609 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
3610 isa<CXXMethodDecl>(CurContext))
3611 return TypoCorrection();
3612
Douglas Gregor546be3c2009-12-30 17:04:44 +00003613 // We only attempt to correct typos for identifiers.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003614 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003615 if (!Typo)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003616 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003617
3618 // If the scope specifier itself was invalid, don't try to correct
3619 // typos.
3620 if (SS && SS->isInvalid())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003621 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003622
3623 // Never try to correct typos during template deduction or
3624 // instantiation.
3625 if (!ActiveTemplateInstantiations.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003626 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003627
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003628 NamespaceSpecifierSet Namespaces(Context, CurContext);
3629
3630 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003631
Douglas Gregoraaf87162010-04-14 20:04:41 +00003632 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003633 bool IsUnqualifiedLookup = false;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003634 if (MemberContext) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003635 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003636
3637 // Look in qualified interfaces.
3638 if (OPT) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003639 for (ObjCObjectPointerType::qual_iterator
3640 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003641 I != E; ++I)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003642 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003643 }
3644 } else if (SS && SS->isSet()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003645 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
3646 if (!DC)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003647 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003648
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003649 // Provide a stop gap for files that are just seriously broken. Trying
3650 // to correct all typos can turn into a HUGE performance penalty, causing
3651 // some files to take minutes to get rejected by the parser.
3652 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003653 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003654 ++TyposCorrected;
3655
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003656 LookupVisibleDecls(DC, LookupKind, Consumer);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003657 } else {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003658 IsUnqualifiedLookup = true;
3659 UnqualifiedTyposCorrectedMap::iterator Cached
3660 = UnqualifiedTyposCorrected.find(Typo);
3661 if (Cached == UnqualifiedTyposCorrected.end()) {
3662 // Provide a stop gap for files that are just seriously broken. Trying
3663 // to correct all typos can turn into a HUGE performance penalty, causing
3664 // some files to take minutes to get rejected by the parser.
3665 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003666 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003667
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003668 // For unqualified lookup, look through all of the names that we have
3669 // seen in this translation unit.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003670 for (IdentifierTable::iterator I = Context.Idents.begin(),
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003671 IEnd = Context.Idents.end();
3672 I != IEnd; ++I)
3673 Consumer.FoundName(I->getKey());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003674
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003675 // Walk through identifiers in external identifier sources.
3676 if (IdentifierInfoLookup *External
Douglas Gregor95f42922010-10-14 22:11:03 +00003677 = Context.Idents.getExternalIdentifierLookup()) {
Ted Kremenek7a054b12010-11-07 06:11:33 +00003678 llvm::OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003679 do {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003680 StringRef Name = Iter->Next();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003681 if (Name.empty())
3682 break;
Douglas Gregor95f42922010-10-14 22:11:03 +00003683
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003684 Consumer.FoundName(Name);
3685 } while (true);
3686 }
3687 } else {
3688 // Use the cached value, unless it's a keyword. In the keyword case, we'll
3689 // end up adding the keyword below.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003690 if (!Cached->second)
3691 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003692
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003693 if (!Cached->second.isKeyword())
3694 Consumer.addCorrection(Cached->second);
Douglas Gregor95f42922010-10-14 22:11:03 +00003695 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003696 }
3697
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003698 AddKeywordsToConsumer(*this, Consumer, S, CTC);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003699
Douglas Gregoraaf87162010-04-14 20:04:41 +00003700 // If we haven't found anything, we're done.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003701 if (Consumer.empty()) {
3702 // If this was an unqualified lookup, note that no correction was found.
3703 if (IsUnqualifiedLookup)
3704 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003705
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003706 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003707 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003708
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003709 // Make sure that the user typed at least 3 characters for each correction
Douglas Gregore24b5752010-10-14 20:34:08 +00003710 // made. Otherwise, we don't even both looking at the results.
3711 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003712 if (ED > 0 && Typo->getName().size() / ED < 3) {
3713 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregor157a3ff2010-10-27 14:20:34 +00003714 if (IsUnqualifiedLookup)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003715 (void)UnqualifiedTyposCorrected[Typo];
3716
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003717 return TypoCorrection();
3718 }
3719
3720 // Build the NestedNameSpecifiers for the KnownNamespaces
3721 if (getLangOptions().CPlusPlus) {
3722 // Load any externally-known namespaces.
3723 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003724 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003725 LoadedExternalKnownNamespaces = true;
3726 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
3727 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
3728 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
3729 }
3730
3731 for (llvm::DenseMap<NamespaceDecl*, bool>::iterator
3732 KNI = KnownNamespaces.begin(),
3733 KNIEnd = KnownNamespaces.end();
3734 KNI != KNIEnd; ++KNI)
3735 Namespaces.AddNamespace(KNI->first);
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003736 }
Douglas Gregore24b5752010-10-14 20:34:08 +00003737
3738 // Weed out any names that could not be found by name lookup.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003739 llvm::SmallPtrSet<IdentifierInfo*, 16> QualifiedResults;
3740 LookupResult TmpRes(*this, TypoName, LookupKind);
3741 TmpRes.suppressDiagnostics();
3742 while (!Consumer.empty()) {
3743 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3744 unsigned ED = DI->first;
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003745 for (TypoCorrectionConsumer::result_iterator I = DI->second->begin(),
3746 IEnd = DI->second->end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003747 I != IEnd; /* Increment in loop. */) {
3748 // If the item already has been looked up or is a keyword, keep it
3749 if (I->second.isResolved()) {
3750 ++I;
3751 continue;
Douglas Gregore24b5752010-10-14 20:34:08 +00003752 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003753
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003754 // Perform name lookup on this name.
3755 IdentifierInfo *Name = I->second.getCorrectionAsIdentifierInfo();
3756 LookupPotentialTypoResult(*this, TmpRes, Name, S, SS, MemberContext,
3757 EnteringContext, CTC);
3758
3759 switch (TmpRes.getResultKind()) {
3760 case LookupResult::NotFound:
3761 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00003762 case LookupResult::FoundUnresolvedValue:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003763 QualifiedResults.insert(Name);
3764 // We didn't find this name in our scope, or didn't like what we found;
3765 // ignore it.
3766 {
3767 TypoCorrectionConsumer::result_iterator Next = I;
3768 ++Next;
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003769 DI->second->erase(I);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003770 I = Next;
3771 }
3772 break;
3773
3774 case LookupResult::Ambiguous:
3775 // We don't deal with ambiguities.
3776 return TypoCorrection();
3777
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003778 case LookupResult::FoundOverloaded: {
3779 // Store all of the Decls for overloaded symbols
3780 for (LookupResult::iterator TRD = TmpRes.begin(),
3781 TRDEnd = TmpRes.end();
3782 TRD != TRDEnd; ++TRD)
3783 I->second.addCorrectionDecl(*TRD);
3784 ++I;
3785 break;
3786 }
3787
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003788 case LookupResult::Found:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003789 I->second.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
3790 ++I;
3791 break;
3792 }
Douglas Gregore24b5752010-10-14 20:34:08 +00003793 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003794
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003795 if (DI->second->empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003796 Consumer.erase(DI);
3797 else if (!getLangOptions().CPlusPlus || QualifiedResults.empty() || !ED)
3798 // If there are results in the closest possible bucket, stop
3799 break;
3800
3801 // Only perform the qualified lookups for C++
3802 if (getLangOptions().CPlusPlus) {
3803 TmpRes.suppressDiagnostics();
3804 for (llvm::SmallPtrSet<IdentifierInfo*,
3805 16>::iterator QRI = QualifiedResults.begin(),
3806 QRIEnd = QualifiedResults.end();
3807 QRI != QRIEnd; ++QRI) {
3808 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
3809 NIEnd = Namespaces.end();
3810 NI != NIEnd; ++NI) {
3811 DeclContext *Ctx = NI->DeclCtx;
3812 unsigned QualifiedED = ED + NI->EditDistance;
3813
3814 // Stop searching once the namespaces are too far away to create
3815 // acceptable corrections for this identifier (since the namespaces
3816 // are sorted in ascending order by edit distance)
3817 if (QualifiedED > Consumer.getMaxEditDistance()) break;
3818
3819 TmpRes.clear();
3820 TmpRes.setLookupName(*QRI);
3821 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
3822
3823 switch (TmpRes.getResultKind()) {
3824 case LookupResult::Found:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003825 Consumer.addName((*QRI)->getName(), TmpRes.getAsSingle<NamedDecl>(),
3826 QualifiedED, NI->NameSpecifier);
3827 break;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003828 case LookupResult::FoundOverloaded: {
3829 TypoCorrection corr(&Context.Idents.get((*QRI)->getName()), NULL,
3830 NI->NameSpecifier, QualifiedED);
3831 for (LookupResult::iterator TRD = TmpRes.begin(),
3832 TRDEnd = TmpRes.end();
3833 TRD != TRDEnd; ++TRD)
3834 corr.addCorrectionDecl(*TRD);
3835 Consumer.addCorrection(corr);
3836 break;
3837 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003838 case LookupResult::NotFound:
3839 case LookupResult::NotFoundInCurrentInstantiation:
3840 case LookupResult::Ambiguous:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00003841 case LookupResult::FoundUnresolvedValue:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003842 break;
3843 }
3844 }
3845 }
3846 }
3847
3848 QualifiedResults.clear();
3849 }
3850
3851 // No corrections remain...
3852 if (Consumer.empty()) return TypoCorrection();
3853
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003854 TypoResultsMap &BestResults = *Consumer.begin()->second;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003855 ED = Consumer.begin()->first;
3856
3857 if (ED > 0 && Typo->getName().size() / ED < 3) {
3858 // If this was an unqualified lookup, note that no correction was found.
3859 if (IsUnqualifiedLookup)
3860 (void)UnqualifiedTyposCorrected[Typo];
3861
3862 return TypoCorrection();
3863 }
3864
3865 // If we have multiple possible corrections, eliminate the ones where we
3866 // added namespace qualifiers to try to resolve the ambiguity (and to favor
3867 // corrections without additional namespace qualifiers)
3868 if (getLangOptions().CPlusPlus && BestResults.size() > 1) {
3869 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003870 for (TypoCorrectionConsumer::result_iterator I = DI->second->begin(),
3871 IEnd = DI->second->end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003872 I != IEnd; /* Increment in loop. */) {
3873 if (I->second.getCorrectionSpecifier() != NULL) {
3874 TypoCorrectionConsumer::result_iterator Cur = I;
3875 ++I;
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003876 DI->second->erase(Cur);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003877 } else ++I;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003878 }
Douglas Gregoraaf87162010-04-14 20:04:41 +00003879 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003880
Douglas Gregore24b5752010-10-14 20:34:08 +00003881 // If only a single name remains, return that result.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003882 if (BestResults.size() == 1) {
3883 const llvm::StringMapEntry<TypoCorrection> &Correction = *(BestResults.begin());
3884 const TypoCorrection &Result = Correction.second;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003885
Douglas Gregor53e4b552010-10-26 17:18:00 +00003886 // Don't correct to a keyword that's the same as the typo; the keyword
3887 // wasn't actually in scope.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003888 if (ED == 0 && Result.isKeyword()) return TypoCorrection();
3889
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003890 // Record the correction for unqualified lookup.
3891 if (IsUnqualifiedLookup)
3892 UnqualifiedTyposCorrected[Typo] = Result;
3893
3894 return Result;
3895 }
3896 else if (BestResults.size() > 1 && CTC == CTC_ObjCMessageReceiver
3897 && BestResults["super"].isKeyword()) {
3898 // Prefer 'super' when we're completing in a message-receiver
3899 // context.
3900
3901 // Don't correct to a keyword that's the same as the typo; the keyword
3902 // wasn't actually in scope.
3903 if (ED == 0) return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003904
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003905 // Record the correction for unqualified lookup.
3906 if (IsUnqualifiedLookup)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003907 UnqualifiedTyposCorrected[Typo] = BestResults["super"];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003908
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003909 return BestResults["super"];
Douglas Gregor7b824e82010-10-15 13:35:25 +00003910 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003911
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003912 if (IsUnqualifiedLookup)
3913 (void)UnqualifiedTyposCorrected[Typo];
3914
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003915 return TypoCorrection();
3916}
3917
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003918void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
3919 if (!CDecl) return;
3920
3921 if (isKeyword())
3922 CorrectionDecls.clear();
3923
3924 CorrectionDecls.push_back(CDecl);
3925
3926 if (!CorrectionName)
3927 CorrectionName = CDecl->getDeclName();
3928}
3929
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003930std::string TypoCorrection::getAsString(const LangOptions &LO) const {
3931 if (CorrectionNameSpec) {
3932 std::string tmpBuffer;
3933 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
3934 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
3935 return PrefixOStream.str() + CorrectionName.getAsString();
3936 }
3937
3938 return CorrectionName.getAsString();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003939}