blob: 7df049815a53527daaa9f5e3a7ac1407e0e1458d [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
John McCall7453ed42009-11-22 00:44:51 +0000324/// Resolves the result kind of this lookup.
John McCall7d384dd2009-11-18 07:57:50 +0000325void LookupResult::resolveKind() {
John McCallf36e02d2009-10-09 21:13:30 +0000326 unsigned N = Decls.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000327
John McCallf36e02d2009-10-09 21:13:30 +0000328 // Fast case: no possible ambiguity.
John McCall68263142009-11-18 22:49:29 +0000329 if (N == 0) {
John McCalldc5c7862010-01-15 21:27:01 +0000330 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall68263142009-11-18 22:49:29 +0000331 return;
332 }
333
John McCall7453ed42009-11-22 00:44:51 +0000334 // If there's a single decl, we need to examine it to decide what
335 // kind of lookup this is.
John McCall7ba107a2009-11-18 02:36:19 +0000336 if (N == 1) {
Douglas Gregor2b147f02010-04-25 21:15:30 +0000337 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
338 if (isa<FunctionTemplateDecl>(D))
John McCall7453ed42009-11-22 00:44:51 +0000339 ResultKind = FoundOverloaded;
Douglas Gregor2b147f02010-04-25 21:15:30 +0000340 else if (isa<UnresolvedUsingValueDecl>(D))
John McCall7ba107a2009-11-18 02:36:19 +0000341 ResultKind = FoundUnresolvedValue;
342 return;
343 }
John McCallf36e02d2009-10-09 21:13:30 +0000344
John McCall6e247262009-10-10 05:48:19 +0000345 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000346 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000347
John McCallf36e02d2009-10-09 21:13:30 +0000348 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000349 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000350
John McCallf36e02d2009-10-09 21:13:30 +0000351 bool Ambiguous = false;
352 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000353 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000354
355 unsigned UniqueTagIndex = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000356
John McCallf36e02d2009-10-09 21:13:30 +0000357 unsigned I = 0;
358 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000359 NamedDecl *D = Decls[I]->getUnderlyingDecl();
360 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000361
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000362 // Redeclarations of types via typedef can occur both within a scope
363 // and, through using declarations and directives, across scopes. There is
364 // no ambiguity if they all refer to the same type, so unique based on the
365 // canonical type.
366 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
367 if (!TD->getDeclContext()->isRecord()) {
368 QualType T = SemaRef.Context.getTypeDeclType(TD);
369 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
370 // The type is not unique; pull something off the back and continue
371 // at this index.
372 Decls[I] = Decls[--N];
373 continue;
374 }
375 }
376 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000377
John McCall314be4e2009-11-17 07:50:12 +0000378 if (!Unique.insert(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000379 // If it's not unique, pull something off the back (and
380 // continue at this index).
381 Decls[I] = Decls[--N];
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000382 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000383 }
384
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000385 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000386
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000387 if (isa<UnresolvedUsingValueDecl>(D)) {
388 HasUnresolved = true;
389 } else if (isa<TagDecl>(D)) {
390 if (HasTag)
391 Ambiguous = true;
392 UniqueTagIndex = I;
393 HasTag = true;
394 } else if (isa<FunctionTemplateDecl>(D)) {
395 HasFunction = true;
396 HasFunctionTemplate = true;
397 } else if (isa<FunctionDecl>(D)) {
398 HasFunction = true;
399 } else {
400 if (HasNonFunction)
401 Ambiguous = true;
402 HasNonFunction = true;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000403 }
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000404 I++;
Mike Stump1eb44332009-09-09 15:08:12 +0000405 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000406
John McCallf36e02d2009-10-09 21:13:30 +0000407 // C++ [basic.scope.hiding]p2:
408 // A class name or enumeration name can be hidden by the name of
409 // an object, function, or enumerator declared in the same
410 // scope. If a class or enumeration name and an object, function,
411 // or enumerator are declared in the same scope (in any order)
412 // with the same name, the class or enumeration name is hidden
413 // wherever the object, function, or enumerator name is visible.
414 // But it's still an error if there are distinct tag types found,
415 // even if they're not visible. (ref?)
John McCallfda8e122009-12-03 00:58:24 +0000416 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregor77a1a882010-10-23 16:06:17 +0000417 (HasFunction || HasNonFunction || HasUnresolved)) {
418 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
419 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
420 Decls[UniqueTagIndex] = Decls[--N];
421 else
422 Ambiguous = true;
423 }
Anders Carlsson8b50d012009-06-26 03:37:05 +0000424
John McCallf36e02d2009-10-09 21:13:30 +0000425 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000426
John McCallfda8e122009-12-03 00:58:24 +0000427 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000428 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000429
John McCallf36e02d2009-10-09 21:13:30 +0000430 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000431 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000432 else if (HasUnresolved)
433 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000434 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000435 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000436 else
John McCalla24dc2e2009-11-17 02:14:36 +0000437 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000438}
439
John McCall7d384dd2009-11-18 07:57:50 +0000440void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall6b2accb2010-02-10 09:31:12 +0000441 CXXBasePaths::const_paths_iterator I, E;
John McCallf36e02d2009-10-09 21:13:30 +0000442 DeclContext::lookup_iterator DI, DE;
443 for (I = P.begin(), E = P.end(); I != E; ++I)
444 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
445 addDecl(*DI);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000446}
447
John McCall7d384dd2009-11-18 07:57:50 +0000448void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000449 Paths = new CXXBasePaths;
450 Paths->swap(P);
451 addDeclsFromBasePaths(*Paths);
452 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000453 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000454}
455
John McCall7d384dd2009-11-18 07:57:50 +0000456void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000457 Paths = new CXXBasePaths;
458 Paths->swap(P);
459 addDeclsFromBasePaths(*Paths);
460 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000461 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000462}
463
Chris Lattner5f9e2722011-07-23 10:55:15 +0000464void LookupResult::print(raw_ostream &Out) {
John McCallf36e02d2009-10-09 21:13:30 +0000465 Out << Decls.size() << " result(s)";
466 if (isAmbiguous()) Out << ", ambiguous";
467 if (Paths) Out << ", base paths present";
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000468
John McCallf36e02d2009-10-09 21:13:30 +0000469 for (iterator I = begin(), E = end(); I != E; ++I) {
470 Out << "\n";
471 (*I)->print(Out, 2);
472 }
473}
474
Douglas Gregor85910982010-02-12 05:48:04 +0000475/// \brief Lookup a builtin function, when name lookup would otherwise
476/// fail.
477static bool LookupBuiltin(Sema &S, LookupResult &R) {
478 Sema::LookupNameKind NameKind = R.getLookupKind();
479
480 // If we didn't find a use of this identifier, and if the identifier
481 // corresponds to a compiler builtin, create the decl object for the builtin
482 // now, injecting it into translation unit scope, and return it.
483 if (NameKind == Sema::LookupOrdinaryName ||
484 NameKind == Sema::LookupRedeclarationWithLinkage) {
485 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
486 if (II) {
487 // If this is a builtin on this (or all) targets, create the decl.
488 if (unsigned BuiltinID = II->getBuiltinID()) {
489 // In C++, we don't have any predefined library functions like
490 // 'malloc'. Instead, we'll just error.
491 if (S.getLangOptions().CPlusPlus &&
492 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
493 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000494
495 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
496 BuiltinID, S.TUScope,
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000497 R.isForRedeclaration(),
498 R.getNameLoc())) {
Douglas Gregor85910982010-02-12 05:48:04 +0000499 R.addDecl(D);
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000500 return true;
501 }
502
503 if (R.isForRedeclaration()) {
504 // If we're redeclaring this function anyway, forget that
505 // this was a builtin at all.
506 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
507 }
508
509 return false;
Douglas Gregor85910982010-02-12 05:48:04 +0000510 }
511 }
512 }
513
514 return false;
515}
516
Douglas Gregor4923aa22010-07-02 20:37:36 +0000517/// \brief Determine whether we can declare a special member function within
518/// the class at this point.
519static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
520 const CXXRecordDecl *Class) {
John McCallb3b50a82010-08-11 23:52:36 +0000521 // Don't do it if the class is invalid.
522 if (Class->isInvalidDecl())
523 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000524
Douglas Gregor4923aa22010-07-02 20:37:36 +0000525 // We need to have a definition for the class.
526 if (!Class->getDefinition() || Class->isDependentContext())
527 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000528
Douglas Gregor4923aa22010-07-02 20:37:36 +0000529 // We can't be in the middle of defining the class.
530 if (const RecordType *RecordTy
531 = Context.getTypeDeclType(Class)->getAs<RecordType>())
532 return !RecordTy->isBeingDefined();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000533
Douglas Gregor4923aa22010-07-02 20:37:36 +0000534 return false;
535}
536
537void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregor22584312010-07-02 23:41:54 +0000538 if (!CanDeclareSpecialMemberFunction(Context, Class))
539 return;
Douglas Gregor18274032010-07-03 00:47:00 +0000540
541 // If the default constructor has not yet been declared, do so now.
Sean Huntcdee3fe2011-05-11 22:34:38 +0000542 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +0000543 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000544
Douglas Gregor22584312010-07-02 23:41:54 +0000545 // If the copy constructor has not yet been declared, do so now.
546 if (!Class->hasDeclaredCopyConstructor())
547 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000548
Douglas Gregora376d102010-07-02 21:50:04 +0000549 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000550 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +0000551 DeclareImplicitCopyAssignment(Class);
552
Douglas Gregor4923aa22010-07-02 20:37:36 +0000553 // If the destructor has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000554 if (!Class->hasDeclaredDestructor())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000555 DeclareImplicitDestructor(Class);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000556}
557
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000558/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregora376d102010-07-02 21:50:04 +0000559/// special member function.
560static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
561 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000562 case DeclarationName::CXXConstructorName:
Douglas Gregora376d102010-07-02 21:50:04 +0000563 case DeclarationName::CXXDestructorName:
564 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000565
Douglas Gregora376d102010-07-02 21:50:04 +0000566 case DeclarationName::CXXOperatorName:
567 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000568
Douglas Gregora376d102010-07-02 21:50:04 +0000569 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000570 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000571 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000572
Douglas Gregora376d102010-07-02 21:50:04 +0000573 return false;
574}
575
576/// \brief If there are any implicit member functions with the given name
577/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000578static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregora376d102010-07-02 21:50:04 +0000579 DeclarationName Name,
580 const DeclContext *DC) {
581 if (!DC)
582 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000583
Douglas Gregora376d102010-07-02 21:50:04 +0000584 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000585 case DeclarationName::CXXConstructorName:
586 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor18274032010-07-03 00:47:00 +0000587 if (Record->getDefinition() &&
588 CanDeclareSpecialMemberFunction(S.Context, Record)) {
Sean Huntcdee3fe2011-05-11 22:34:38 +0000589 if (Record->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +0000590 S.DeclareImplicitDefaultConstructor(
591 const_cast<CXXRecordDecl *>(Record));
592 if (!Record->hasDeclaredCopyConstructor())
593 S.DeclareImplicitCopyConstructor(const_cast<CXXRecordDecl *>(Record));
594 }
Douglas Gregor22584312010-07-02 23:41:54 +0000595 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000596
Douglas Gregora376d102010-07-02 21:50:04 +0000597 case DeclarationName::CXXDestructorName:
598 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
599 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
600 CanDeclareSpecialMemberFunction(S.Context, Record))
601 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregora376d102010-07-02 21:50:04 +0000602 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000603
Douglas Gregora376d102010-07-02 21:50:04 +0000604 case DeclarationName::CXXOperatorName:
605 if (Name.getCXXOverloadedOperator() != OO_Equal)
606 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000607
Douglas Gregora376d102010-07-02 21:50:04 +0000608 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
609 if (Record->getDefinition() && !Record->hasDeclaredCopyAssignment() &&
610 CanDeclareSpecialMemberFunction(S.Context, Record))
611 S.DeclareImplicitCopyAssignment(const_cast<CXXRecordDecl *>(Record));
612 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000613
Douglas Gregora376d102010-07-02 21:50:04 +0000614 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000615 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000616 }
617}
Douglas Gregor4923aa22010-07-02 20:37:36 +0000618
John McCallf36e02d2009-10-09 21:13:30 +0000619// Adds all qualifying matches for a name within a decl context to the
620// given lookup result. Returns true if any matches were found.
Douglas Gregor85910982010-02-12 05:48:04 +0000621static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000622 bool Found = false;
623
Douglas Gregor4923aa22010-07-02 20:37:36 +0000624 // Lazily declare C++ special member functions.
Douglas Gregora376d102010-07-02 21:50:04 +0000625 if (S.getLangOptions().CPlusPlus)
626 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000627
Douglas Gregor4923aa22010-07-02 20:37:36 +0000628 // Perform lookup into this declaration context.
John McCalld7be78a2009-11-10 07:01:13 +0000629 DeclContext::lookup_const_iterator I, E;
Douglas Gregor48026d22010-01-11 18:40:55 +0000630 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall46460a62010-01-20 21:53:11 +0000631 NamedDecl *D = *I;
632 if (R.isAcceptableDecl(D)) {
633 R.addDecl(D);
Douglas Gregor48026d22010-01-11 18:40:55 +0000634 Found = true;
635 }
636 }
John McCallf36e02d2009-10-09 21:13:30 +0000637
Douglas Gregor85910982010-02-12 05:48:04 +0000638 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
639 return true;
640
Douglas Gregor48026d22010-01-11 18:40:55 +0000641 if (R.getLookupName().getNameKind()
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000642 != DeclarationName::CXXConversionFunctionName ||
643 R.getLookupName().getCXXNameType()->isDependentType() ||
644 !isa<CXXRecordDecl>(DC))
645 return Found;
646
647 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000648 // A specialization of a conversion function template is not found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000649 // name lookup. Instead, any conversion function templates visible in the
650 // context of the use are considered. [...]
651 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
652 if (!Record->isDefinition())
653 return Found;
654
655 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000656 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000657 UEnd = Unresolved->end(); U != UEnd; ++U) {
658 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
659 if (!ConvTemplate)
660 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000661
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000662 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000663 // add the conversion function template. When we deduce template
664 // arguments for specializations, we'll end up unifying the return
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000665 // type of the new declaration with the type of the function template.
666 if (R.isForRedeclaration()) {
667 R.addDecl(ConvTemplate);
668 Found = true;
669 continue;
670 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000671
Douglas Gregor48026d22010-01-11 18:40:55 +0000672 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000673 // [...] For each such operator, if argument deduction succeeds
674 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000675 // name lookup.
676 //
677 // When referencing a conversion function for any purpose other than
678 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000679 // result), perform template argument deduction and place the
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000680 // specialization into the result set. We do this to avoid forcing all
681 // callers to perform special deduction for conversion functions.
John McCall2a7fb272010-08-25 05:32:35 +0000682 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000683 FunctionDecl *Specialization = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000684
685 const FunctionProtoType *ConvProto
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000686 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
687 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3f477a12010-01-12 01:17:50 +0000688
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000689 // Compute the type of the function that we would expect the conversion
690 // function to have, if it were to match the name given.
691 // FIXME: Calling convention!
John McCalle23cf432010-12-14 08:05:40 +0000692 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
693 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
Sebastian Redl8b5b4092011-03-06 10:52:04 +0000694 EPI.ExceptionSpecType = EST_None;
John McCalle23cf432010-12-14 08:05:40 +0000695 EPI.NumExceptions = 0;
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000696 QualType ExpectedType
697 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
John McCalle23cf432010-12-14 08:05:40 +0000698 0, 0, EPI);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000699
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000700 // Perform template argument deduction against the type that we would
701 // expect the function to have.
702 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
703 Specialization, Info)
704 == Sema::TDK_Success) {
705 R.addDecl(Specialization);
706 Found = true;
Douglas Gregor48026d22010-01-11 18:40:55 +0000707 }
708 }
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000709
John McCallf36e02d2009-10-09 21:13:30 +0000710 return Found;
711}
712
John McCalld7be78a2009-11-10 07:01:13 +0000713// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000714static bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000715CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregor85910982010-02-12 05:48:04 +0000716 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000717
718 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
719
John McCalld7be78a2009-11-10 07:01:13 +0000720 // Perform direct name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +0000721 bool Found = LookupDirect(S, R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000722
John McCalld7be78a2009-11-10 07:01:13 +0000723 // Perform direct name lookup into the namespaces nominated by the
724 // using directives whose common ancestor is this namespace.
725 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
726 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000727
John McCalld7be78a2009-11-10 07:01:13 +0000728 for (; UI != UEnd; ++UI)
Douglas Gregor85910982010-02-12 05:48:04 +0000729 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000730 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000731
732 R.resolveKind();
733
734 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000735}
736
737static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000738 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000739 return Ctx->isFileContext();
740 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000741}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000742
Douglas Gregor711be1e2010-03-15 14:33:29 +0000743// Find the next outer declaration context from this scope. This
744// routine actually returns the semantic outer context, which may
745// differ from the lexical context (encoded directly in the Scope
746// stack) when we are parsing a member of a class template. In this
747// case, the second element of the pair will be true, to indicate that
748// name lookup should continue searching in this semantic context when
749// it leaves the current template parameter scope.
750static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
751 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
752 DeclContext *Lexical = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000753 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor711be1e2010-03-15 14:33:29 +0000754 OuterS = OuterS->getParent()) {
755 if (OuterS->getEntity()) {
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000756 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor711be1e2010-03-15 14:33:29 +0000757 break;
758 }
759 }
760
761 // C++ [temp.local]p8:
762 // In the definition of a member of a class template that appears
763 // outside of the namespace containing the class template
764 // definition, the name of a template-parameter hides the name of
765 // a member of this namespace.
766 //
767 // Example:
768 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000769 // namespace N {
770 // class C { };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000771 //
772 // template<class T> class B {
773 // void f(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000774 // };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000775 // }
776 //
777 // template<class C> void N::B<C>::f(C) {
778 // C b; // C is the template parameter, not N::C
779 // }
780 //
781 // In this example, the lexical context we return is the
782 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000783 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor711be1e2010-03-15 14:33:29 +0000784 !S->getParent()->isTemplateParamScope())
785 return std::make_pair(Lexical, false);
786
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000787 // Find the outermost template parameter scope.
Douglas Gregor711be1e2010-03-15 14:33:29 +0000788 // For the example, this is the scope for the template parameters of
789 // template<class C>.
790 Scope *OutermostTemplateScope = S->getParent();
791 while (OutermostTemplateScope->getParent() &&
792 OutermostTemplateScope->getParent()->isTemplateParamScope())
793 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000794
Douglas Gregor711be1e2010-03-15 14:33:29 +0000795 // Find the namespace context in which the original scope occurs. In
796 // the example, this is namespace N.
797 DeclContext *Semantic = DC;
798 while (!Semantic->isFileContext())
799 Semantic = Semantic->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000800
Douglas Gregor711be1e2010-03-15 14:33:29 +0000801 // Find the declaration context just outside of the template
802 // parameter scope. This is the context in which the template is
803 // being lexically declaration (a namespace context). In the
804 // example, this is the global scope.
805 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
806 Lexical->Encloses(Semantic))
807 return std::make_pair(Semantic, true);
808
809 return std::make_pair(Lexical, false);
Douglas Gregore942bbe2009-09-10 16:57:35 +0000810}
811
John McCalla24dc2e2009-11-17 02:14:36 +0000812bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCall1d7c5282009-12-18 10:40:03 +0000813 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000814
815 DeclarationName Name = R.getLookupName();
816
Douglas Gregora376d102010-07-02 21:50:04 +0000817 // If this is the name of an implicitly-declared special member function,
818 // go through the scope stack to implicitly declare
819 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
820 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
821 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
822 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
823 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000824
Douglas Gregora376d102010-07-02 21:50:04 +0000825 // Implicitly declare member functions with the name we're looking for, if in
826 // fact we are in a scope where it matters.
827
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000828 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000829 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000830 I = IdResolver.begin(Name),
831 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000832
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000833 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000834 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000835 // ...During unqualified name lookup (3.4.1), the names appear as if
836 // they were declared in the nearest enclosing namespace which contains
837 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000838 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000839 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000840 //
841 // For example:
842 // namespace A { int i; }
843 // void foo() {
844 // int i;
845 // {
846 // using namespace A;
847 // ++i; // finds local 'i', A::i appears at global scope
848 // }
849 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000850 //
Douglas Gregor711be1e2010-03-15 14:33:29 +0000851 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000852 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregord2235f62010-05-20 20:58:56 +0000853 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
854
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000855 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000856 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000857 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000858 if (R.isAcceptableDecl(*I)) {
John McCallf36e02d2009-10-09 21:13:30 +0000859 Found = true;
860 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000861 }
862 }
John McCallf36e02d2009-10-09 21:13:30 +0000863 if (Found) {
864 R.resolveKind();
Douglas Gregord2235f62010-05-20 20:58:56 +0000865 if (S->isClassScope())
866 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
867 R.setNamingClass(Record);
John McCallf36e02d2009-10-09 21:13:30 +0000868 return true;
869 }
870
Douglas Gregor711be1e2010-03-15 14:33:29 +0000871 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
872 S->getParent() && !S->getParent()->isTemplateParamScope()) {
873 // We've just searched the last template parameter scope and
874 // found nothing, so look into the the contexts between the
875 // lexical and semantic declaration contexts returned by
876 // findOuterContext(). This implements the name lookup behavior
877 // of C++ [temp.local]p8.
878 Ctx = OutsideOfTemplateParamDC;
879 OutsideOfTemplateParamDC = 0;
880 }
881
882 if (Ctx) {
883 DeclContext *OuterCtx;
884 bool SearchAfterTemplateScope;
885 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
886 if (SearchAfterTemplateScope)
887 OutsideOfTemplateParamDC = OuterCtx;
888
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000889 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-02-19 16:08:35 +0000890 // We do not directly look into transparent contexts, since
891 // those entities will be found in the nearest enclosing
892 // non-transparent context.
893 if (Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000894 continue;
Douglas Gregor36262b82010-02-19 16:08:35 +0000895
896 // We do not look directly into function or method contexts,
897 // since all of the local variables and parameters of the
898 // function/method are present within the Scope.
899 if (Ctx->isFunctionOrMethod()) {
900 // If we have an Objective-C instance method, look for ivars
901 // in the corresponding interface.
902 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
903 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
904 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
905 ObjCInterfaceDecl *ClassDeclared;
906 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000907 Name.getAsIdentifierInfo(),
Douglas Gregor36262b82010-02-19 16:08:35 +0000908 ClassDeclared)) {
909 if (R.isAcceptableDecl(Ivar)) {
910 R.addDecl(Ivar);
911 R.resolveKind();
912 return true;
913 }
914 }
915 }
916 }
917
918 continue;
919 }
920
Douglas Gregore942bbe2009-09-10 16:57:35 +0000921 // Perform qualified name lookup into this context.
922 // FIXME: In some cases, we know that every name that could be found by
923 // this qualified name lookup will also be on the identifier chain. For
924 // example, inside a class without any base classes, we never need to
925 // perform qualified lookup because all of the members are on top of the
926 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000927 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +0000928 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +0000929 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000930 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000931 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000932
John McCalld7be78a2009-11-10 07:01:13 +0000933 // Stop if we ran out of scopes.
934 // FIXME: This really, really shouldn't be happening.
935 if (!S) return false;
936
Argyrios Kyrtzidis78f59112010-10-29 16:12:50 +0000937 // If we are looking for members, no need to look into global/namespace scope.
938 if (R.getLookupKind() == LookupMemberName)
939 return false;
940
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000941 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000942 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +0000943 //
Mike Stump390b4cc2009-05-16 07:39:55 +0000944 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
945 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000946
John McCalld7be78a2009-11-10 07:01:13 +0000947 UnqualUsingDirectiveSet UDirs;
948 UDirs.visitScopeChain(Initial, S);
949 UDirs.done();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000950
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000951 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000952 // Unqualified name lookup in C++ requires looking into scopes
953 // that aren't strictly lexical, and therefore we walk through the
954 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000955
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000956 for (; S; S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000957 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000958 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000959 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000960 if (R.isAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000961 // We found something. Look for anything else in our scope
962 // with this same name and in an acceptable identifier
963 // namespace, so that we can construct an overload set if we
964 // need to.
John McCallf36e02d2009-10-09 21:13:30 +0000965 Found = true;
966 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000967 }
968 }
969
Douglas Gregor00b4b032010-05-14 04:53:42 +0000970 if (Found && S->isTemplateParamScope()) {
John McCallf36e02d2009-10-09 21:13:30 +0000971 R.resolveKind();
972 return true;
973 }
974
Douglas Gregor00b4b032010-05-14 04:53:42 +0000975 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
976 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
977 S->getParent() && !S->getParent()->isTemplateParamScope()) {
978 // We've just searched the last template parameter scope and
979 // found nothing, so look into the the contexts between the
980 // lexical and semantic declaration contexts returned by
981 // findOuterContext(). This implements the name lookup behavior
982 // of C++ [temp.local]p8.
983 Ctx = OutsideOfTemplateParamDC;
984 OutsideOfTemplateParamDC = 0;
985 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000986
Douglas Gregor00b4b032010-05-14 04:53:42 +0000987 if (Ctx) {
988 DeclContext *OuterCtx;
989 bool SearchAfterTemplateScope;
990 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
991 if (SearchAfterTemplateScope)
992 OutsideOfTemplateParamDC = OuterCtx;
993
994 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
995 // We do not directly look into transparent contexts, since
996 // those entities will be found in the nearest enclosing
997 // non-transparent context.
998 if (Ctx->isTransparentContext())
999 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001000
Douglas Gregor00b4b032010-05-14 04:53:42 +00001001 // If we have a context, and it's not a context stashed in the
1002 // template parameter scope for an out-of-line definition, also
1003 // look into that context.
1004 if (!(Found && S && S->isTemplateParamScope())) {
1005 assert(Ctx->isFileContext() &&
1006 "We should have been looking only at file context here already.");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001007
Douglas Gregor00b4b032010-05-14 04:53:42 +00001008 // Look into context considering using-directives.
1009 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1010 Found = true;
1011 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001012
Douglas Gregor00b4b032010-05-14 04:53:42 +00001013 if (Found) {
1014 R.resolveKind();
1015 return true;
1016 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001017
Douglas Gregor00b4b032010-05-14 04:53:42 +00001018 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1019 return false;
1020 }
1021 }
1022
Douglas Gregor1df0ee92010-02-05 07:07:10 +00001023 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +00001024 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001025 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001026
John McCallf36e02d2009-10-09 21:13:30 +00001027 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001028}
1029
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001030/// @brief Perform unqualified name lookup starting from a given
1031/// scope.
1032///
1033/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1034/// used to find names within the current scope. For example, 'x' in
1035/// @code
1036/// int x;
1037/// int f() {
1038/// return x; // unqualified name look finds 'x' in the global scope
1039/// }
1040/// @endcode
1041///
1042/// Different lookup criteria can find different names. For example, a
1043/// particular scope can have both a struct and a function of the same
1044/// name, and each can be found by certain lookup criteria. For more
1045/// information about lookup criteria, see the documentation for the
1046/// class LookupCriteria.
1047///
1048/// @param S The scope from which unqualified name lookup will
1049/// begin. If the lookup criteria permits, name lookup may also search
1050/// in the parent scopes.
1051///
1052/// @param Name The name of the entity that we are searching for.
1053///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001054/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001055/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001056/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001057///
1058/// @returns The result of name lookup, which includes zero or more
1059/// declarations and possibly additional information used to diagnose
1060/// ambiguities.
John McCalla24dc2e2009-11-17 02:14:36 +00001061bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1062 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +00001063 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001064
John McCalla24dc2e2009-11-17 02:14:36 +00001065 LookupNameKind NameKind = R.getLookupKind();
1066
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001067 if (!getLangOptions().CPlusPlus) {
1068 // Unqualified name lookup in C/Objective-C is purely lexical, so
1069 // search in the declarations attached to the name.
John McCall1d7c5282009-12-18 10:40:03 +00001070 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001071 // Find the nearest non-transparent declaration scope.
1072 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001073 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001074 static_cast<DeclContext *>(S->getEntity())
1075 ->isTransparentContext()))
1076 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001077 }
1078
John McCall1d7c5282009-12-18 10:40:03 +00001079 unsigned IDNS = R.getIdentifierNamespace();
1080
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001081 // Scan up the scope chain looking for a decl that matches this
1082 // identifier that is in the appropriate namespace. This search
1083 // should not take long, as shadowing of names is uncommon, and
1084 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001085 bool LeftStartingScope = false;
1086
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001087 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +00001088 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001089 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001090 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001091 if (NameKind == LookupRedeclarationWithLinkage) {
1092 // Determine whether this (or a previous) declaration is
1093 // out-of-scope.
John McCalld226f652010-08-21 09:40:31 +00001094 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001095 LeftStartingScope = true;
1096
1097 // If we found something outside of our starting scope that
1098 // does not have linkage, skip it.
1099 if (LeftStartingScope && !((*I)->hasLinkage()))
1100 continue;
1101 }
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001102 else if (NameKind == LookupObjCImplicitSelfParam &&
1103 !isa<ImplicitParamDecl>(*I))
1104 continue;
1105
John McCallf36e02d2009-10-09 21:13:30 +00001106 R.addDecl(*I);
1107
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001108 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00001109 // If this declaration has the "overloadable" attribute, we
1110 // might have a set of overloaded functions.
1111
1112 // Figure out what scope the identifier is in.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001113 while (!(S->getFlags() & Scope::DeclScope) ||
John McCalld226f652010-08-21 09:40:31 +00001114 !S->isDeclScope(*I))
Douglas Gregorf9201e02009-02-11 23:02:49 +00001115 S = S->getParent();
1116
1117 // Find the last declaration in this scope (with the same
1118 // name, naturally).
1119 IdentifierResolver::iterator LastI = I;
1120 for (++LastI; LastI != IEnd; ++LastI) {
John McCalld226f652010-08-21 09:40:31 +00001121 if (!S->isDeclScope(*LastI))
Douglas Gregorf9201e02009-02-11 23:02:49 +00001122 break;
John McCallf36e02d2009-10-09 21:13:30 +00001123 R.addDecl(*LastI);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001124 }
Douglas Gregorf9201e02009-02-11 23:02:49 +00001125 }
1126
John McCallf36e02d2009-10-09 21:13:30 +00001127 R.resolveKind();
1128
1129 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +00001130 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001131 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001132 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +00001133 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +00001134 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001135 }
1136
1137 // If we didn't find a use of this identifier, and if the identifier
1138 // corresponds to a compiler builtin, create the decl object for the builtin
1139 // now, injecting it into translation unit scope, and return it.
Axel Naumann42151d52011-04-13 13:19:46 +00001140 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1141 return true;
Douglas Gregor3e41d602009-02-13 23:20:09 +00001142
Axel Naumannf8291a12011-02-24 16:47:47 +00001143 // If we didn't find a use of this identifier, the ExternalSource
1144 // may be able to handle the situation.
1145 // Note: some lookup failures are expected!
1146 // See e.g. R.isForRedeclaration().
1147 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001148}
1149
John McCall6e247262009-10-10 05:48:19 +00001150/// @brief Perform qualified name lookup in the namespaces nominated by
1151/// using directives by the given context.
1152///
1153/// C++98 [namespace.qual]p2:
1154/// Given X::m (where X is a user-declared namespace), or given ::m
1155/// (where X is the global namespace), let S be the set of all
1156/// declarations of m in X and in the transitive closure of all
1157/// namespaces nominated by using-directives in X and its used
1158/// namespaces, except that using-directives are ignored in any
1159/// namespace, including X, directly containing one or more
1160/// declarations of m. No namespace is searched more than once in
1161/// the lookup of a name. If S is the empty set, the program is
1162/// ill-formed. Otherwise, if S has exactly one member, or if the
1163/// context of the reference is a using-declaration
1164/// (namespace.udecl), S is the required set of declarations of
1165/// m. Otherwise if the use of m is not one that allows a unique
1166/// declaration to be chosen from S, the program is ill-formed.
1167/// C++98 [namespace.qual]p5:
1168/// During the lookup of a qualified namespace member name, if the
1169/// lookup finds more than one declaration of the member, and if one
1170/// declaration introduces a class name or enumeration name and the
1171/// other declarations either introduce the same object, the same
1172/// enumerator or a set of functions, the non-type name hides the
1173/// class or enumeration name if and only if the declarations are
1174/// from the same namespace; otherwise (the declarations are from
1175/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +00001176static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +00001177 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +00001178 assert(StartDC->isFileContext() && "start context is not a file context");
1179
1180 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1181 DeclContext::udir_iterator E = StartDC->using_directives_end();
1182
1183 if (I == E) return false;
1184
1185 // We have at least added all these contexts to the queue.
1186 llvm::DenseSet<DeclContext*> Visited;
1187 Visited.insert(StartDC);
1188
1189 // We have not yet looked into these namespaces, much less added
1190 // their "using-children" to the queue.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001191 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6e247262009-10-10 05:48:19 +00001192
1193 // We have already looked into the initial namespace; seed the queue
1194 // with its using-children.
1195 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001196 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6e247262009-10-10 05:48:19 +00001197 if (Visited.insert(ND).second)
1198 Queue.push_back(ND);
1199 }
1200
1201 // The easiest way to implement the restriction in [namespace.qual]p5
1202 // is to check whether any of the individual results found a tag
1203 // and, if so, to declare an ambiguity if the final result is not
1204 // a tag.
1205 bool FoundTag = false;
1206 bool FoundNonTag = false;
1207
John McCall7d384dd2009-11-18 07:57:50 +00001208 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001209
1210 bool Found = false;
1211 while (!Queue.empty()) {
1212 NamespaceDecl *ND = Queue.back();
1213 Queue.pop_back();
1214
1215 // We go through some convolutions here to avoid copying results
1216 // between LookupResults.
1217 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001218 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001219 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001220
1221 if (FoundDirect) {
1222 // First do any local hiding.
1223 DirectR.resolveKind();
1224
1225 // If the local result is a tag, remember that.
1226 if (DirectR.isSingleTagDecl())
1227 FoundTag = true;
1228 else
1229 FoundNonTag = true;
1230
1231 // Append the local results to the total results if necessary.
1232 if (UseLocal) {
1233 R.addAllDecls(LocalR);
1234 LocalR.clear();
1235 }
1236 }
1237
1238 // If we find names in this namespace, ignore its using directives.
1239 if (FoundDirect) {
1240 Found = true;
1241 continue;
1242 }
1243
1244 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1245 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1246 if (Visited.insert(Nom).second)
1247 Queue.push_back(Nom);
1248 }
1249 }
1250
1251 if (Found) {
1252 if (FoundTag && FoundNonTag)
1253 R.setAmbiguousQualifiedTagHiding();
1254 else
1255 R.resolveKind();
1256 }
1257
1258 return Found;
1259}
1260
Douglas Gregor8071e422010-08-15 06:18:01 +00001261/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001262static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor8071e422010-08-15 06:18:01 +00001263 CXXBasePath &Path,
1264 void *Name) {
1265 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001266
Douglas Gregor8071e422010-08-15 06:18:01 +00001267 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1268 Path.Decls = BaseRecord->lookup(N);
1269 return Path.Decls.first != Path.Decls.second;
1270}
1271
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001272/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001273/// static members, nested types, and enumerators.
1274template<typename InputIterator>
1275static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1276 Decl *D = (*First)->getUnderlyingDecl();
1277 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1278 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001279
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001280 if (isa<CXXMethodDecl>(D)) {
1281 // Determine whether all of the methods are static.
1282 bool AllMethodsAreStatic = true;
1283 for(; First != Last; ++First) {
1284 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001285
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001286 if (!isa<CXXMethodDecl>(D)) {
1287 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1288 break;
1289 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001290
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001291 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1292 AllMethodsAreStatic = false;
1293 break;
1294 }
1295 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001296
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001297 if (AllMethodsAreStatic)
1298 return true;
1299 }
1300
1301 return false;
1302}
1303
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001304/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001305///
1306/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1307/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001308/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001309///
1310/// Different lookup criteria can find different names. For example, a
1311/// particular scope can have both a struct and a function of the same
1312/// name, and each can be found by certain lookup criteria. For more
1313/// information about lookup criteria, see the documentation for the
1314/// class LookupCriteria.
1315///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001316/// \param R captures both the lookup criteria and any lookup results found.
1317///
1318/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001319/// search. If the lookup criteria permits, name lookup may also search
1320/// in the parent contexts or (for C++ classes) base classes.
1321///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001322/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001323/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001324///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001325/// \returns true if lookup succeeded, false if it failed.
1326bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1327 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001328 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001329
John McCalla24dc2e2009-11-17 02:14:36 +00001330 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001331 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001332
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001333 // Make sure that the declaration context is complete.
1334 assert((!isa<TagDecl>(LookupCtx) ||
1335 LookupCtx->isDependentContext() ||
1336 cast<TagDecl>(LookupCtx)->isDefinition() ||
1337 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1338 ->isBeingDefined()) &&
1339 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001340
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001341 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001342 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001343 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001344 if (isa<CXXRecordDecl>(LookupCtx))
1345 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001346 return true;
1347 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001348
John McCall6e247262009-10-10 05:48:19 +00001349 // Don't descend into implied contexts for redeclarations.
1350 // C++98 [namespace.qual]p6:
1351 // In a declaration for a namespace member in which the
1352 // declarator-id is a qualified-id, given that the qualified-id
1353 // for the namespace member has the form
1354 // nested-name-specifier unqualified-id
1355 // the unqualified-id shall name a member of the namespace
1356 // designated by the nested-name-specifier.
1357 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001358 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001359 return false;
1360
John McCalla24dc2e2009-11-17 02:14:36 +00001361 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001362 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001363 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001364
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001365 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001366 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001367 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor025291b2010-07-01 00:21:21 +00001368 if (!LookupRec || !LookupRec->getDefinition())
John McCallf36e02d2009-10-09 21:13:30 +00001369 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001370
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001371 // If we're performing qualified name lookup into a dependent class,
1372 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001373 // dependent base classes, then we either have to delay lookup until
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001374 // template instantiation time (at which point all bases will be available)
1375 // or we have to fail.
1376 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1377 LookupRec->hasAnyDependentBases()) {
1378 R.setNotFoundInCurrentInstantiation();
1379 return false;
1380 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001381
Douglas Gregor7176fff2009-01-15 00:26:24 +00001382 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001383 CXXBasePaths Paths;
1384 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001385
1386 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001387 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001388 switch (R.getLookupKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001389 case LookupObjCImplicitSelfParam:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001390 case LookupOrdinaryName:
1391 case LookupMemberName:
1392 case LookupRedeclarationWithLinkage:
1393 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1394 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001395
Douglas Gregora8f32e02009-10-06 17:59:45 +00001396 case LookupTagName:
1397 BaseCallback = &CXXRecordDecl::FindTagMember;
1398 break;
John McCall9f54ad42009-12-10 09:41:52 +00001399
Douglas Gregor8071e422010-08-15 06:18:01 +00001400 case LookupAnyName:
1401 BaseCallback = &LookupAnyMember;
1402 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001403
John McCall9f54ad42009-12-10 09:41:52 +00001404 case LookupUsingDeclName:
1405 // This lookup is for redeclarations only.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001406
Douglas Gregora8f32e02009-10-06 17:59:45 +00001407 case LookupOperatorName:
1408 case LookupNamespaceName:
1409 case LookupObjCProtocolName:
Chris Lattner337e5502011-02-18 01:27:55 +00001410 case LookupLabel:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001411 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001412 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001413
Douglas Gregora8f32e02009-10-06 17:59:45 +00001414 case LookupNestedNameSpecifierName:
1415 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1416 break;
1417 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001418
John McCalla24dc2e2009-11-17 02:14:36 +00001419 if (!LookupRec->lookupInBases(BaseCallback,
1420 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001421 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001422
John McCall92f88312010-01-23 00:46:32 +00001423 R.setNamingClass(LookupRec);
1424
Douglas Gregor7176fff2009-01-15 00:26:24 +00001425 // C++ [class.member.lookup]p2:
1426 // [...] If the resulting set of declarations are not all from
1427 // sub-objects of the same type, or the set has a nonstatic member
1428 // and includes members from distinct sub-objects, there is an
1429 // ambiguity and the program is ill-formed. Otherwise that set is
1430 // the result of the lookup.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001431 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001432 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001433 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001434
Douglas Gregora8f32e02009-10-06 17:59:45 +00001435 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001436 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001437 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001438
John McCall46460a62010-01-20 21:53:11 +00001439 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1440 // across all paths.
1441 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001442
Douglas Gregor7176fff2009-01-15 00:26:24 +00001443 // Determine whether we're looking at a distinct sub-object or not.
1444 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001445 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001446 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1447 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001448 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001449 }
1450
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001451 if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001452 != Context.getCanonicalType(PathElement.Base->getType())) {
1453 // We found members of the given name in two subobjects of
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001454 // different types. If the declaration sets aren't the same, this
1455 // this lookup is ambiguous.
1456 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1457 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1458 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1459 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001460
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001461 while (FirstD != FirstPath->Decls.second &&
1462 CurrentD != Path->Decls.second) {
1463 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1464 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1465 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001466
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001467 ++FirstD;
1468 ++CurrentD;
1469 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001470
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001471 if (FirstD == FirstPath->Decls.second &&
1472 CurrentD == Path->Decls.second)
1473 continue;
1474 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001475
John McCallf36e02d2009-10-09 21:13:30 +00001476 R.setAmbiguousBaseSubobjectTypes(Paths);
1477 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001478 }
1479
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001480 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001481 // We have a different subobject of the same type.
1482
1483 // C++ [class.member.lookup]p5:
1484 // A static member, a nested type or an enumerator defined in
1485 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001486 // has more than one base class subobject of type T.
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001487 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
Douglas Gregor7176fff2009-01-15 00:26:24 +00001488 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001489
Douglas Gregor7176fff2009-01-15 00:26:24 +00001490 // We have found a nonstatic member name in multiple, distinct
1491 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001492 R.setAmbiguousBaseSubobjects(Paths);
1493 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001494 }
1495 }
1496
1497 // Lookup in a base class succeeded; return these results.
1498
John McCallf36e02d2009-10-09 21:13:30 +00001499 DeclContext::lookup_iterator I, E;
John McCall92f88312010-01-23 00:46:32 +00001500 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1501 NamedDecl *D = *I;
1502 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1503 D->getAccess());
1504 R.addDecl(D, AS);
1505 }
John McCallf36e02d2009-10-09 21:13:30 +00001506 R.resolveKind();
1507 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001508}
1509
1510/// @brief Performs name lookup for a name that was parsed in the
1511/// source code, and may contain a C++ scope specifier.
1512///
1513/// This routine is a convenience routine meant to be called from
1514/// contexts that receive a name and an optional C++ scope specifier
1515/// (e.g., "N::M::x"). It will then perform either qualified or
1516/// unqualified name lookup (with LookupQualifiedName or LookupName,
1517/// respectively) on the given name and return those results.
1518///
1519/// @param S The scope from which unqualified name lookup will
1520/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001521///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001522/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001523///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001524/// @param EnteringContext Indicates whether we are going to enter the
1525/// context of the scope-specifier SS (if present).
1526///
John McCallf36e02d2009-10-09 21:13:30 +00001527/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001528bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001529 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001530 if (SS && SS->isInvalid()) {
1531 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001532 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001533 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001534 }
Mike Stump1eb44332009-09-09 15:08:12 +00001535
Douglas Gregor495c35d2009-08-25 22:51:20 +00001536 if (SS && SS->isSet()) {
1537 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001538 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001539 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001540 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001541 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001542
John McCalla24dc2e2009-11-17 02:14:36 +00001543 R.setContextRange(SS->getRange());
1544
1545 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001546 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001547
Douglas Gregor495c35d2009-08-25 22:51:20 +00001548 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001549 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001550 // Name lookup can't find anything in this case.
John McCallf36e02d2009-10-09 21:13:30 +00001551 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001552 }
1553
Mike Stump1eb44332009-09-09 15:08:12 +00001554 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001555 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001556}
1557
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001558
Douglas Gregor7176fff2009-01-15 00:26:24 +00001559/// @brief Produce a diagnostic describing the ambiguity that resulted
1560/// from name lookup.
1561///
1562/// @param Result The ambiguous name lookup result.
Mike Stump1eb44332009-09-09 15:08:12 +00001563///
Douglas Gregor7176fff2009-01-15 00:26:24 +00001564/// @param Name The name of the entity that name lookup was
1565/// searching for.
1566///
1567/// @param NameLoc The location of the name within the source code.
1568///
1569/// @param LookupRange A source range that provides more
1570/// source-location information concerning the lookup itself. For
1571/// example, this range might highlight a nested-name-specifier that
1572/// precedes the name.
1573///
1574/// @returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001575bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001576 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1577
John McCalla24dc2e2009-11-17 02:14:36 +00001578 DeclarationName Name = Result.getLookupName();
1579 SourceLocation NameLoc = Result.getNameLoc();
1580 SourceRange LookupRange = Result.getContextRange();
1581
John McCall6e247262009-10-10 05:48:19 +00001582 switch (Result.getAmbiguityKind()) {
1583 case LookupResult::AmbiguousBaseSubobjects: {
1584 CXXBasePaths *Paths = Result.getBasePaths();
1585 QualType SubobjectType = Paths->front().back().Base->getType();
1586 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1587 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1588 << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001589
John McCall6e247262009-10-10 05:48:19 +00001590 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1591 while (isa<CXXMethodDecl>(*Found) &&
1592 cast<CXXMethodDecl>(*Found)->isStatic())
1593 ++Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001594
John McCall6e247262009-10-10 05:48:19 +00001595 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001596
John McCall6e247262009-10-10 05:48:19 +00001597 return true;
1598 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001599
John McCall6e247262009-10-10 05:48:19 +00001600 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001601 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1602 << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001603
John McCall6e247262009-10-10 05:48:19 +00001604 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001605 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001606 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1607 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001608 Path != PathEnd; ++Path) {
1609 Decl *D = *Path->Decls.first;
1610 if (DeclsPrinted.insert(D).second)
1611 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1612 }
1613
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001614 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001615 }
1616
John McCall6e247262009-10-10 05:48:19 +00001617 case LookupResult::AmbiguousTagHiding: {
1618 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001619
John McCall6e247262009-10-10 05:48:19 +00001620 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1621
1622 LookupResult::iterator DI, DE = Result.end();
1623 for (DI = Result.begin(); DI != DE; ++DI)
1624 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1625 TagDecls.insert(TD);
1626 Diag(TD->getLocation(), diag::note_hidden_tag);
1627 }
1628
1629 for (DI = Result.begin(); DI != DE; ++DI)
1630 if (!isa<TagDecl>(*DI))
1631 Diag((*DI)->getLocation(), diag::note_hiding_object);
1632
1633 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001634 LookupResult::Filter F = Result.makeFilter();
1635 while (F.hasNext()) {
1636 if (TagDecls.count(F.next()))
1637 F.erase();
1638 }
1639 F.done();
John McCall6e247262009-10-10 05:48:19 +00001640
1641 return true;
1642 }
1643
1644 case LookupResult::AmbiguousReference: {
1645 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001646
John McCall6e247262009-10-10 05:48:19 +00001647 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1648 for (; DI != DE; ++DI)
1649 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001650
John McCall6e247262009-10-10 05:48:19 +00001651 return true;
1652 }
1653 }
1654
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001655 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001656 return true;
1657}
Douglas Gregorfa047642009-02-04 00:32:51 +00001658
John McCallc7e04da2010-05-28 18:45:08 +00001659namespace {
1660 struct AssociatedLookup {
1661 AssociatedLookup(Sema &S,
1662 Sema::AssociatedNamespaceSet &Namespaces,
1663 Sema::AssociatedClassSet &Classes)
1664 : S(S), Namespaces(Namespaces), Classes(Classes) {
1665 }
1666
1667 Sema &S;
1668 Sema::AssociatedNamespaceSet &Namespaces;
1669 Sema::AssociatedClassSet &Classes;
1670 };
1671}
1672
Mike Stump1eb44332009-09-09 15:08:12 +00001673static void
John McCallc7e04da2010-05-28 18:45:08 +00001674addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCall6ff07852009-08-07 22:18:02 +00001675
Douglas Gregor54022952010-04-30 07:08:38 +00001676static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1677 DeclContext *Ctx) {
1678 // Add the associated namespace for this class.
1679
1680 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1681 // be a locally scoped record.
1682
Sebastian Redl410c4f22010-08-31 20:53:31 +00001683 // We skip out of inline namespaces. The innermost non-inline namespace
1684 // contains all names of all its nested inline namespaces anyway, so we can
1685 // replace the entire inline namespace tree with its root.
1686 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1687 Ctx->isInlineNamespace())
Douglas Gregor54022952010-04-30 07:08:38 +00001688 Ctx = Ctx->getParent();
1689
John McCall6ff07852009-08-07 22:18:02 +00001690 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001691 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001692}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001693
Mike Stump1eb44332009-09-09 15:08:12 +00001694// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001695// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001696static void
John McCallc7e04da2010-05-28 18:45:08 +00001697addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1698 const TemplateArgument &Arg) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001699 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001700 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001701 switch (Arg.getKind()) {
1702 case TemplateArgument::Null:
1703 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001704
Douglas Gregor69be8d62009-07-08 07:51:57 +00001705 case TemplateArgument::Type:
1706 // [...] the namespaces and classes associated with the types of the
1707 // template arguments provided for template type parameters (excluding
1708 // template template parameters)
John McCallc7e04da2010-05-28 18:45:08 +00001709 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor69be8d62009-07-08 07:51:57 +00001710 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001711
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001712 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001713 case TemplateArgument::TemplateExpansion: {
Mike Stump1eb44332009-09-09 15:08:12 +00001714 // [...] the namespaces in which any template template arguments are
1715 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001716 // template template arguments are defined.
Douglas Gregora7fc9012011-01-05 18:58:31 +00001717 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump1eb44332009-09-09 15:08:12 +00001718 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001719 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001720 DeclContext *Ctx = ClassTemplate->getDeclContext();
1721 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001722 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001723 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001724 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001725 }
1726 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001727 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001728
Douglas Gregor788cd062009-11-11 01:00:40 +00001729 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001730 case TemplateArgument::Integral:
1731 case TemplateArgument::Expression:
Mike Stump1eb44332009-09-09 15:08:12 +00001732 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001733 // associated namespaces. ]
1734 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001735
Douglas Gregor69be8d62009-07-08 07:51:57 +00001736 case TemplateArgument::Pack:
1737 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1738 PEnd = Arg.pack_end();
1739 P != PEnd; ++P)
John McCallc7e04da2010-05-28 18:45:08 +00001740 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001741 break;
1742 }
1743}
1744
Douglas Gregorfa047642009-02-04 00:32:51 +00001745// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001746// argument-dependent lookup with an argument of class type
1747// (C++ [basic.lookup.koenig]p2).
1748static void
John McCallc7e04da2010-05-28 18:45:08 +00001749addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1750 CXXRecordDecl *Class) {
1751
1752 // Just silently ignore anything whose name is __va_list_tag.
1753 if (Class->getDeclName() == Result.S.VAListTagName)
1754 return;
1755
Douglas Gregorfa047642009-02-04 00:32:51 +00001756 // C++ [basic.lookup.koenig]p2:
1757 // [...]
1758 // -- If T is a class type (including unions), its associated
1759 // classes are: the class itself; the class of which it is a
1760 // member, if any; and its direct and indirect base
1761 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001762 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001763
1764 // Add the class of which it is a member, if any.
1765 DeclContext *Ctx = Class->getDeclContext();
1766 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001767 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001768 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001769 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001770
Douglas Gregorfa047642009-02-04 00:32:51 +00001771 // Add the class itself. If we've already seen this class, we don't
1772 // need to visit base classes.
John McCallc7e04da2010-05-28 18:45:08 +00001773 if (!Result.Classes.insert(Class))
Douglas Gregorfa047642009-02-04 00:32:51 +00001774 return;
1775
Mike Stump1eb44332009-09-09 15:08:12 +00001776 // -- If T is a template-id, its associated namespaces and classes are
1777 // the namespace in which the template is defined; for member
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001778 // templates, the member template's class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001779 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001780 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001781 // namespaces in which any template template arguments are defined; and
1782 // the classes in which any member templates used as template template
1783 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001784 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001785 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001786 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1787 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1788 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001789 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001790 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001791 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001792
Douglas Gregor69be8d62009-07-08 07:51:57 +00001793 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1794 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallc7e04da2010-05-28 18:45:08 +00001795 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001796 }
Mike Stump1eb44332009-09-09 15:08:12 +00001797
John McCall86ff3082010-02-04 22:26:26 +00001798 // Only recurse into base classes for complete types.
1799 if (!Class->hasDefinition()) {
1800 // FIXME: we might need to instantiate templates here
1801 return;
1802 }
1803
Douglas Gregorfa047642009-02-04 00:32:51 +00001804 // Add direct and indirect base classes along with their associated
1805 // namespaces.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001806 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregorfa047642009-02-04 00:32:51 +00001807 Bases.push_back(Class);
1808 while (!Bases.empty()) {
1809 // Pop this class off the stack.
1810 Class = Bases.back();
1811 Bases.pop_back();
1812
1813 // Visit the base classes.
1814 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1815 BaseEnd = Class->bases_end();
1816 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001817 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001818 // In dependent contexts, we do ADL twice, and the first time around,
1819 // the base type might be a dependent TemplateSpecializationType, or a
1820 // TemplateTypeParmType. If that happens, simply ignore it.
1821 // FIXME: If we want to support export, we probably need to add the
1822 // namespace of the template in a TemplateSpecializationType, or even
1823 // the classes and namespaces of known non-dependent arguments.
1824 if (!BaseType)
1825 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001826 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001827 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001828 // Find the associated namespace for this base class.
1829 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallc7e04da2010-05-28 18:45:08 +00001830 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001831
1832 // Make sure we visit the bases of this base class.
1833 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1834 Bases.push_back(BaseDecl);
1835 }
1836 }
1837 }
1838}
1839
1840// \brief Add the associated classes and namespaces for
1841// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001842// (C++ [basic.lookup.koenig]p2).
1843static void
John McCallc7e04da2010-05-28 18:45:08 +00001844addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001845 // C++ [basic.lookup.koenig]p2:
1846 //
1847 // For each argument type T in the function call, there is a set
1848 // of zero or more associated namespaces and a set of zero or more
1849 // associated classes to be considered. The sets of namespaces and
1850 // classes is determined entirely by the types of the function
1851 // arguments (and the namespace of any template template
1852 // argument). Typedef names and using-declarations used to specify
1853 // the types do not contribute to this set. The sets of namespaces
1854 // and classes are determined in the following way:
Douglas Gregorfa047642009-02-04 00:32:51 +00001855
Chris Lattner5f9e2722011-07-23 10:55:15 +00001856 SmallVector<const Type *, 16> Queue;
John McCallfa4edcf2010-05-28 06:08:54 +00001857 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1858
Douglas Gregorfa047642009-02-04 00:32:51 +00001859 while (true) {
John McCallfa4edcf2010-05-28 06:08:54 +00001860 switch (T->getTypeClass()) {
1861
1862#define TYPE(Class, Base)
1863#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1864#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1865#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1866#define ABSTRACT_TYPE(Class, Base)
1867#include "clang/AST/TypeNodes.def"
1868 // T is canonical. We can also ignore dependent types because
1869 // we don't need to do ADL at the definition point, but if we
1870 // wanted to implement template export (or if we find some other
1871 // use for associated classes and namespaces...) this would be
1872 // wrong.
Douglas Gregorfa047642009-02-04 00:32:51 +00001873 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00001874
John McCallfa4edcf2010-05-28 06:08:54 +00001875 // -- If T is a pointer to U or an array of U, its associated
1876 // namespaces and classes are those associated with U.
1877 case Type::Pointer:
1878 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1879 continue;
1880 case Type::ConstantArray:
1881 case Type::IncompleteArray:
1882 case Type::VariableArray:
1883 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1884 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001885
John McCallfa4edcf2010-05-28 06:08:54 +00001886 // -- If T is a fundamental type, its associated sets of
1887 // namespaces and classes are both empty.
1888 case Type::Builtin:
1889 break;
1890
1891 // -- If T is a class type (including unions), its associated
1892 // classes are: the class itself; the class of which it is a
1893 // member, if any; and its direct and indirect base
1894 // classes. Its associated namespaces are the namespaces in
1895 // which its associated classes are defined.
1896 case Type::Record: {
1897 CXXRecordDecl *Class
1898 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001899 addAssociatedClassesAndNamespaces(Result, Class);
John McCallfa4edcf2010-05-28 06:08:54 +00001900 break;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001901 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00001902
John McCallfa4edcf2010-05-28 06:08:54 +00001903 // -- If T is an enumeration type, its associated namespace is
1904 // the namespace in which it is defined. If it is class
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001905 // member, its associated class is the member's class; else
John McCallfa4edcf2010-05-28 06:08:54 +00001906 // it has no associated class.
1907 case Type::Enum: {
1908 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001909
John McCallfa4edcf2010-05-28 06:08:54 +00001910 DeclContext *Ctx = Enum->getDeclContext();
1911 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001912 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001913
John McCallfa4edcf2010-05-28 06:08:54 +00001914 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001915 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001916
John McCallfa4edcf2010-05-28 06:08:54 +00001917 break;
1918 }
1919
1920 // -- If T is a function type, its associated namespaces and
1921 // classes are those associated with the function parameter
1922 // types and those associated with the return type.
1923 case Type::FunctionProto: {
1924 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1925 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1926 ArgEnd = Proto->arg_type_end();
1927 Arg != ArgEnd; ++Arg)
1928 Queue.push_back(Arg->getTypePtr());
1929 // fallthrough
1930 }
1931 case Type::FunctionNoProto: {
1932 const FunctionType *FnType = cast<FunctionType>(T);
1933 T = FnType->getResultType().getTypePtr();
1934 continue;
1935 }
1936
1937 // -- If T is a pointer to a member function of a class X, its
1938 // associated namespaces and classes are those associated
1939 // with the function parameter types and return type,
1940 // together with those associated with X.
1941 //
1942 // -- If T is a pointer to a data member of class X, its
1943 // associated namespaces and classes are those associated
1944 // with the member type together with those associated with
1945 // X.
1946 case Type::MemberPointer: {
1947 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1948
1949 // Queue up the class type into which this points.
1950 Queue.push_back(MemberPtr->getClass());
1951
1952 // And directly continue with the pointee type.
1953 T = MemberPtr->getPointeeType().getTypePtr();
1954 continue;
1955 }
1956
1957 // As an extension, treat this like a normal pointer.
1958 case Type::BlockPointer:
1959 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1960 continue;
1961
1962 // References aren't covered by the standard, but that's such an
1963 // obvious defect that we cover them anyway.
1964 case Type::LValueReference:
1965 case Type::RValueReference:
1966 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1967 continue;
1968
1969 // These are fundamental types.
1970 case Type::Vector:
1971 case Type::ExtVector:
1972 case Type::Complex:
1973 break;
1974
Douglas Gregorf25760e2011-04-12 01:02:45 +00001975 // If T is an Objective-C object or interface type, or a pointer to an
1976 // object or interface type, the associated namespace is the global
1977 // namespace.
John McCallfa4edcf2010-05-28 06:08:54 +00001978 case Type::ObjCObject:
1979 case Type::ObjCInterface:
1980 case Type::ObjCObjectPointer:
Douglas Gregorf25760e2011-04-12 01:02:45 +00001981 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCallfa4edcf2010-05-28 06:08:54 +00001982 break;
1983 }
1984
1985 if (Queue.empty()) break;
1986 T = Queue.back();
1987 Queue.pop_back();
Douglas Gregorfa047642009-02-04 00:32:51 +00001988 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001989}
1990
1991/// \brief Find the associated classes and namespaces for
1992/// argument-dependent lookup for a call with the given set of
1993/// arguments.
1994///
1995/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00001996/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00001997/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001998void
Douglas Gregorfa047642009-02-04 00:32:51 +00001999Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
2000 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00002001 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002002 AssociatedNamespaces.clear();
2003 AssociatedClasses.clear();
2004
John McCallc7e04da2010-05-28 18:45:08 +00002005 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
2006
Douglas Gregorfa047642009-02-04 00:32:51 +00002007 // C++ [basic.lookup.koenig]p2:
2008 // For each argument type T in the function call, there is a set
2009 // of zero or more associated namespaces and a set of zero or more
2010 // associated classes to be considered. The sets of namespaces and
2011 // classes is determined entirely by the types of the function
2012 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00002013 // argument).
Douglas Gregorfa047642009-02-04 00:32:51 +00002014 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
2015 Expr *Arg = Args[ArgIdx];
2016
2017 if (Arg->getType() != Context.OverloadTy) {
John McCallc7e04da2010-05-28 18:45:08 +00002018 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002019 continue;
2020 }
2021
2022 // [...] In addition, if the argument is the name or address of a
2023 // set of overloaded functions and/or function templates, its
2024 // associated classes and namespaces are the union of those
2025 // associated with each of the members of the set: the namespace
2026 // in which the function or function template is defined and the
2027 // classes and namespaces associated with its (non-dependent)
2028 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00002029 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00002030 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCall2de56d12010-08-25 11:45:40 +00002031 if (unaryOp->getOpcode() == UO_AddrOf)
John McCallba135432009-11-21 08:51:07 +00002032 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002033
John McCallc7e04da2010-05-28 18:45:08 +00002034 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2035 if (!ULE) continue;
John McCallba135432009-11-21 08:51:07 +00002036
John McCallc7e04da2010-05-28 18:45:08 +00002037 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2038 I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00002039 // Look through any using declarations to find the underlying function.
2040 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002041
Chandler Carruthbd647292009-12-29 06:17:27 +00002042 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2043 if (!FDecl)
2044 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002045
2046 // Add the classes and namespaces associated with the parameter
2047 // types and return type of this function.
John McCallc7e04da2010-05-28 18:45:08 +00002048 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002049 }
2050 }
2051}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002052
2053/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2054/// an acceptable non-member overloaded operator for a call whose
2055/// arguments have types T1 (and, if non-empty, T2). This routine
2056/// implements the check in C++ [over.match.oper]p3b2 concerning
2057/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00002058static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002059IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2060 QualType T1, QualType T2,
2061 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00002062 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2063 return true;
2064
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002065 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2066 return true;
2067
John McCall183700f2009-09-21 23:43:11 +00002068 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002069 if (Proto->getNumArgs() < 1)
2070 return false;
2071
2072 if (T1->isEnumeralType()) {
2073 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002074 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002075 return true;
2076 }
2077
2078 if (Proto->getNumArgs() < 2)
2079 return false;
2080
2081 if (!T2.isNull() && T2->isEnumeralType()) {
2082 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002083 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002084 return true;
2085 }
2086
2087 return false;
2088}
2089
John McCall7d384dd2009-11-18 07:57:50 +00002090NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002091 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00002092 LookupNameKind NameKind,
2093 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002094 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00002095 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00002096 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00002097}
2098
Douglas Gregor6e378de2009-04-23 23:18:26 +00002099/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002100ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002101 SourceLocation IdLoc) {
2102 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2103 LookupObjCProtocolName);
Douglas Gregor6e378de2009-04-23 23:18:26 +00002104 return cast_or_null<ObjCProtocolDecl>(D);
2105}
2106
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002107void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00002108 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00002109 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002110 // C++ [over.match.oper]p3:
2111 // -- The set of non-member candidates is the result of the
2112 // unqualified lookup of operator@ in the context of the
2113 // expression according to the usual rules for name lookup in
2114 // unqualified function calls (3.4.2) except that all member
2115 // functions are ignored. However, if no operand has a class
2116 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00002117 // that have a first parameter of type T1 or "reference to
2118 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002119 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00002120 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002121 // when T2 is an enumeration type, are candidate functions.
2122 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00002123 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2124 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002125
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002126 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2127
John McCallf36e02d2009-10-09 21:13:30 +00002128 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002129 return;
2130
2131 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2132 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002133 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2134 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002135 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002136 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00002137 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002138 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00002139 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00002140 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00002141 // later?
2142 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002143 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00002144 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002145 }
2146}
2147
Sean Huntc39b6bc2011-06-24 02:11:39 +00002148Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Sean Hunt308742c2011-06-04 04:32:43 +00002149 CXXSpecialMember SM,
2150 bool ConstArg,
2151 bool VolatileArg,
2152 bool RValueThis,
2153 bool ConstThis,
2154 bool VolatileThis) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002155 RD = RD->getDefinition();
2156 assert((RD && !RD->isBeingDefined()) &&
Sean Hunt308742c2011-06-04 04:32:43 +00002157 "doing special member lookup into record that isn't fully complete");
2158 if (RValueThis || ConstThis || VolatileThis)
2159 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2160 "constructors and destructors always have unqualified lvalue this");
2161 if (ConstArg || VolatileArg)
2162 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2163 "parameter-less special members can't have qualified arguments");
2164
2165 llvm::FoldingSetNodeID ID;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002166 ID.AddPointer(RD);
Sean Hunt308742c2011-06-04 04:32:43 +00002167 ID.AddInteger(SM);
2168 ID.AddInteger(ConstArg);
2169 ID.AddInteger(VolatileArg);
2170 ID.AddInteger(RValueThis);
2171 ID.AddInteger(ConstThis);
2172 ID.AddInteger(VolatileThis);
2173
2174 void *InsertPoint;
2175 SpecialMemberOverloadResult *Result =
2176 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2177
2178 // This was already cached
2179 if (Result)
2180 return Result;
2181
Sean Hunt30543582011-06-07 00:11:58 +00002182 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2183 Result = new (Result) SpecialMemberOverloadResult(ID);
Sean Hunt308742c2011-06-04 04:32:43 +00002184 SpecialMemberCache.InsertNode(Result, InsertPoint);
2185
2186 if (SM == CXXDestructor) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002187 if (!RD->hasDeclaredDestructor())
2188 DeclareImplicitDestructor(RD);
2189 CXXDestructorDecl *DD = RD->getDestructor();
Sean Hunt308742c2011-06-04 04:32:43 +00002190 assert(DD && "record without a destructor");
2191 Result->setMethod(DD);
2192 Result->setSuccess(DD->isDeleted());
2193 Result->setConstParamMatch(false);
2194 return Result;
2195 }
2196
Sean Huntb320e0c2011-06-10 03:50:41 +00002197 // Prepare for overload resolution. Here we construct a synthetic argument
2198 // if necessary and make sure that implicit functions are declared.
Sean Huntc39b6bc2011-06-24 02:11:39 +00002199 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Sean Huntb320e0c2011-06-10 03:50:41 +00002200 DeclarationName Name;
2201 Expr *Arg = 0;
2202 unsigned NumArgs;
2203
2204 if (SM == CXXDefaultConstructor) {
2205 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2206 NumArgs = 0;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002207 if (RD->needsImplicitDefaultConstructor())
2208 DeclareImplicitDefaultConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002209 } else {
2210 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2211 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002212 if (!RD->hasDeclaredCopyConstructor())
2213 DeclareImplicitCopyConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002214 // TODO: Move constructors
2215 } else {
2216 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002217 if (!RD->hasDeclaredCopyAssignment())
2218 DeclareImplicitCopyAssignment(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002219 // TODO: Move assignment
2220 }
2221
2222 QualType ArgType = CanTy;
2223 if (ConstArg)
2224 ArgType.addConst();
2225 if (VolatileArg)
2226 ArgType.addVolatile();
2227
2228 // This isn't /really/ specified by the standard, but it's implied
2229 // we should be working from an RValue in the case of move to ensure
2230 // that we prefer to bind to rvalue references, and an LValue in the
2231 // case of copy to ensure we don't bind to rvalue references.
2232 // Possibly an XValue is actually correct in the case of move, but
2233 // there is no semantic difference for class types in this restricted
2234 // case.
2235 ExprValueKind VK;
Sean Huntab183df2011-06-22 22:13:13 +00002236 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Sean Huntb320e0c2011-06-10 03:50:41 +00002237 VK = VK_LValue;
2238 else
2239 VK = VK_RValue;
2240
2241 NumArgs = 1;
2242 Arg = new (Context) OpaqueValueExpr(SourceLocation(), ArgType, VK);
2243 }
2244
2245 // Create the object argument
2246 QualType ThisTy = CanTy;
2247 if (ConstThis)
2248 ThisTy.addConst();
2249 if (VolatileThis)
2250 ThisTy.addVolatile();
Sean Hunt4cc12c62011-06-23 00:26:20 +00002251 Expr::Classification Classification =
Sean Huntb320e0c2011-06-10 03:50:41 +00002252 (new (Context) OpaqueValueExpr(SourceLocation(), ThisTy,
2253 RValueThis ? VK_RValue : VK_LValue))->
2254 Classify(Context);
2255
2256 // Now we perform lookup on the name we computed earlier and do overload
2257 // resolution. Lookup is only performed directly into the class since there
2258 // will always be a (possibly implicit) declaration to shadow any others.
2259 OverloadCandidateSet OCS((SourceLocation()));
2260 DeclContext::lookup_iterator I, E;
2261 Result->setConstParamMatch(false);
2262
Sean Huntc39b6bc2011-06-24 02:11:39 +00002263 llvm::tie(I, E) = RD->lookup(Name);
Sean Huntb320e0c2011-06-10 03:50:41 +00002264 assert((I != E) &&
2265 "lookup for a constructor or assignment operator was empty");
2266 for ( ; I != E; ++I) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002267 Decl *Cand = *I;
Sean Hunt4cc12c62011-06-23 00:26:20 +00002268
Sean Huntc39b6bc2011-06-24 02:11:39 +00002269 if (Cand->isInvalidDecl())
Sean Huntb320e0c2011-06-10 03:50:41 +00002270 continue;
2271
Sean Huntc39b6bc2011-06-24 02:11:39 +00002272 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2273 // FIXME: [namespace.udecl]p15 says that we should only consider a
2274 // using declaration here if it does not match a declaration in the
2275 // derived class. We do not implement this correctly in other cases
2276 // either.
2277 Cand = U->getTargetDecl();
2278
2279 if (Cand->isInvalidDecl())
2280 continue;
2281 }
2282
2283 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002284 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Sean Huntc39b6bc2011-06-24 02:11:39 +00002285 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Sean Hunt4cc12c62011-06-23 00:26:20 +00002286 Classification, &Arg, NumArgs, OCS, true);
2287 else
2288 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public), &Arg,
2289 NumArgs, OCS, true);
Sean Huntb320e0c2011-06-10 03:50:41 +00002290
2291 // Here we're looking for a const parameter to speed up creation of
2292 // implicit copy methods.
2293 if ((SM == CXXCopyAssignment && M->isCopyAssignmentOperator()) ||
2294 (SM == CXXCopyConstructor &&
2295 cast<CXXConstructorDecl>(M)->isCopyConstructor())) {
2296 QualType ArgType = M->getType()->getAs<FunctionProtoType>()->getArgType(0);
Sean Hunt661c67a2011-06-21 23:42:56 +00002297 if (!ArgType->isReferenceType() ||
2298 ArgType->getPointeeType().isConstQualified())
Sean Huntb320e0c2011-06-10 03:50:41 +00002299 Result->setConstParamMatch(true);
2300 }
Sean Hunt431a1cb2011-06-22 02:58:46 +00002301 } else if (FunctionTemplateDecl *Tmpl =
Sean Huntc39b6bc2011-06-24 02:11:39 +00002302 dyn_cast<FunctionTemplateDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002303 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2304 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Sean Huntc39b6bc2011-06-24 02:11:39 +00002305 RD, 0, ThisTy, Classification, &Arg, NumArgs,
Sean Hunt4cc12c62011-06-23 00:26:20 +00002306 OCS, true);
2307 else
2308 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
2309 0, &Arg, NumArgs, OCS, true);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002310 } else {
2311 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Sean Huntb320e0c2011-06-10 03:50:41 +00002312 }
2313 }
2314
2315 OverloadCandidateSet::iterator Best;
2316 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2317 case OR_Success:
2318 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2319 Result->setSuccess(true);
2320 break;
2321
2322 case OR_Deleted:
2323 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2324 Result->setSuccess(false);
2325 break;
2326
2327 case OR_Ambiguous:
2328 case OR_No_Viable_Function:
2329 Result->setMethod(0);
2330 Result->setSuccess(false);
2331 break;
2332 }
2333
2334 return Result;
2335}
2336
2337/// \brief Look up the default constructor for the given class.
2338CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Sean Huntc530d172011-06-10 04:44:37 +00002339 SpecialMemberOverloadResult *Result =
Sean Huntb320e0c2011-06-10 03:50:41 +00002340 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2341 false, false);
2342
2343 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Sean Hunt308742c2011-06-04 04:32:43 +00002344}
2345
Sean Hunt661c67a2011-06-21 23:42:56 +00002346/// \brief Look up the copying constructor for the given class.
2347CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
2348 unsigned Quals,
2349 bool *ConstParamMatch) {
Sean Huntc530d172011-06-10 04:44:37 +00002350 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2351 "non-const, non-volatile qualifiers for copy ctor arg");
2352 SpecialMemberOverloadResult *Result =
2353 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2354 Quals & Qualifiers::Volatile, false, false, false);
2355
2356 if (ConstParamMatch)
2357 *ConstParamMatch = Result->hasConstParamMatch();
2358
2359 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2360}
2361
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002362/// \brief Look up the constructors for the given class.
2363DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002364 // If the implicit constructors have not yet been declared, do so now.
Douglas Gregor18274032010-07-03 00:47:00 +00002365 if (CanDeclareSpecialMemberFunction(Context, Class)) {
Sean Huntcdee3fe2011-05-11 22:34:38 +00002366 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002367 DeclareImplicitDefaultConstructor(Class);
2368 if (!Class->hasDeclaredCopyConstructor())
2369 DeclareImplicitCopyConstructor(Class);
2370 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002371
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002372 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2373 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2374 return Class->lookup(Name);
2375}
2376
Sean Hunt661c67a2011-06-21 23:42:56 +00002377/// \brief Look up the copying assignment operator for the given class.
2378CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2379 unsigned Quals, bool RValueThis,
2380 unsigned ThisQuals,
2381 bool *ConstParamMatch) {
2382 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2383 "non-const, non-volatile qualifiers for copy assignment arg");
2384 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2385 "non-const, non-volatile qualifiers for copy assignment this");
2386 SpecialMemberOverloadResult *Result =
2387 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2388 Quals & Qualifiers::Volatile, RValueThis,
2389 ThisQuals & Qualifiers::Const,
2390 ThisQuals & Qualifiers::Volatile);
2391
2392 if (ConstParamMatch)
2393 *ConstParamMatch = Result->hasConstParamMatch();
2394
2395 return Result->getMethod();
2396}
2397
Douglas Gregordb89f282010-07-01 22:47:18 +00002398/// \brief Look for the destructor of the given class.
2399///
Sean Huntc5c9b532011-06-03 21:10:40 +00002400/// During semantic analysis, this routine should be used in lieu of
2401/// CXXRecordDecl::getDestructor().
Douglas Gregordb89f282010-07-01 22:47:18 +00002402///
2403/// \returns The destructor for this class.
2404CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Sean Hunt308742c2011-06-04 04:32:43 +00002405 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2406 false, false, false,
2407 false, false)->getMethod());
Douglas Gregordb89f282010-07-01 22:47:18 +00002408}
2409
John McCall7edb5fd2010-01-26 07:16:45 +00002410void ADLResult::insert(NamedDecl *New) {
2411 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2412
2413 // If we haven't yet seen a decl for this key, or the last decl
2414 // was exactly this one, we're done.
2415 if (Old == 0 || Old == New) {
2416 Old = New;
2417 return;
2418 }
2419
2420 // Otherwise, decide which is a more recent redeclaration.
2421 FunctionDecl *OldFD, *NewFD;
2422 if (isa<FunctionTemplateDecl>(New)) {
2423 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2424 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2425 } else {
2426 OldFD = cast<FunctionDecl>(Old);
2427 NewFD = cast<FunctionDecl>(New);
2428 }
2429
2430 FunctionDecl *Cursor = NewFD;
2431 while (true) {
2432 Cursor = Cursor->getPreviousDeclaration();
2433
2434 // If we got to the end without finding OldFD, OldFD is the newer
2435 // declaration; leave things as they are.
2436 if (!Cursor) return;
2437
2438 // If we do find OldFD, then NewFD is newer.
2439 if (Cursor == OldFD) break;
2440
2441 // Otherwise, keep looking.
2442 }
2443
2444 Old = New;
2445}
2446
Sebastian Redl644be852009-10-23 19:23:15 +00002447void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002448 Expr **Args, unsigned NumArgs,
Richard Smithad762fc2011-04-14 22:09:26 +00002449 ADLResult &Result,
2450 bool StdNamespaceIsAssociated) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002451 // Find all of the associated namespaces and classes based on the
2452 // arguments we have.
2453 AssociatedNamespaceSet AssociatedNamespaces;
2454 AssociatedClassSet AssociatedClasses;
Mike Stump1eb44332009-09-09 15:08:12 +00002455 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCall6ff07852009-08-07 22:18:02 +00002456 AssociatedNamespaces,
2457 AssociatedClasses);
Richard Smithad762fc2011-04-14 22:09:26 +00002458 if (StdNamespaceIsAssociated && StdNamespace)
2459 AssociatedNamespaces.insert(getStdNamespace());
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002460
Sebastian Redl644be852009-10-23 19:23:15 +00002461 QualType T1, T2;
2462 if (Operator) {
2463 T1 = Args[0]->getType();
2464 if (NumArgs >= 2)
2465 T2 = Args[1]->getType();
2466 }
2467
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002468 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002469 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2470 // and let Y be the lookup set produced by argument dependent
2471 // lookup (defined as follows). If X contains [...] then Y is
2472 // empty. Otherwise Y is the set of declarations found in the
2473 // namespaces associated with the argument types as described
2474 // below. The set of declarations found by the lookup of the name
2475 // is the union of X and Y.
2476 //
2477 // Here, we compute Y and add its members to the overloaded
2478 // candidate set.
2479 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002480 NSEnd = AssociatedNamespaces.end();
2481 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002482 // When considering an associated namespace, the lookup is the
2483 // same as the lookup performed when the associated namespace is
2484 // used as a qualifier (3.4.3.2) except that:
2485 //
2486 // -- Any using-directives in the associated namespace are
2487 // ignored.
2488 //
John McCall6ff07852009-08-07 22:18:02 +00002489 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002490 // associated classes are visible within their respective
2491 // namespaces even if they are not visible during an ordinary
2492 // lookup (11.4).
2493 DeclContext::lookup_iterator I, E;
John McCall3f9a8a62009-08-11 06:59:38 +00002494 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall6e266892010-01-26 03:27:55 +00002495 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00002496 // If the only declaration here is an ordinary friend, consider
2497 // it only if it was declared in an associated classes.
2498 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00002499 DeclContext *LexDC = D->getLexicalDeclContext();
2500 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2501 continue;
2502 }
Mike Stump1eb44332009-09-09 15:08:12 +00002503
John McCalla113e722010-01-26 06:04:06 +00002504 if (isa<UsingShadowDecl>(D))
2505 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00002506
John McCalla113e722010-01-26 06:04:06 +00002507 if (isa<FunctionDecl>(D)) {
2508 if (Operator &&
2509 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2510 T1, T2, Context))
2511 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00002512 } else if (!isa<FunctionTemplateDecl>(D))
2513 continue;
2514
2515 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00002516 }
2517 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002518}
Douglas Gregor546be3c2009-12-30 17:04:44 +00002519
2520//----------------------------------------------------------------------------
2521// Search for all visible declarations.
2522//----------------------------------------------------------------------------
2523VisibleDeclConsumer::~VisibleDeclConsumer() { }
2524
2525namespace {
2526
2527class ShadowContextRAII;
2528
2529class VisibleDeclsRecord {
2530public:
2531 /// \brief An entry in the shadow map, which is optimized to store a
2532 /// single declaration (the common case) but can also store a list
2533 /// of declarations.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002534 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002535
2536private:
2537 /// \brief A mapping from declaration names to the declarations that have
2538 /// this name within a particular scope.
2539 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2540
2541 /// \brief A list of shadow maps, which is used to model name hiding.
2542 std::list<ShadowMap> ShadowMaps;
2543
2544 /// \brief The declaration contexts we have already visited.
2545 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2546
2547 friend class ShadowContextRAII;
2548
2549public:
2550 /// \brief Determine whether we have already visited this context
2551 /// (and, if not, note that we are going to visit that context now).
2552 bool visitedContext(DeclContext *Ctx) {
2553 return !VisitedContexts.insert(Ctx);
2554 }
2555
Douglas Gregor8071e422010-08-15 06:18:01 +00002556 bool alreadyVisitedContext(DeclContext *Ctx) {
2557 return VisitedContexts.count(Ctx);
2558 }
2559
Douglas Gregor546be3c2009-12-30 17:04:44 +00002560 /// \brief Determine whether the given declaration is hidden in the
2561 /// current scope.
2562 ///
2563 /// \returns the declaration that hides the given declaration, or
2564 /// NULL if no such declaration exists.
2565 NamedDecl *checkHidden(NamedDecl *ND);
2566
2567 /// \brief Add a declaration to the current shadow map.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002568 void add(NamedDecl *ND) {
2569 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2570 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002571};
2572
2573/// \brief RAII object that records when we've entered a shadow context.
2574class ShadowContextRAII {
2575 VisibleDeclsRecord &Visible;
2576
2577 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2578
2579public:
2580 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2581 Visible.ShadowMaps.push_back(ShadowMap());
2582 }
2583
2584 ~ShadowContextRAII() {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002585 Visible.ShadowMaps.pop_back();
2586 }
2587};
2588
2589} // end anonymous namespace
2590
Douglas Gregor546be3c2009-12-30 17:04:44 +00002591NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002592 // Look through using declarations.
2593 ND = ND->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002594
Douglas Gregor546be3c2009-12-30 17:04:44 +00002595 unsigned IDNS = ND->getIdentifierNamespace();
2596 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2597 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2598 SM != SMEnd; ++SM) {
2599 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2600 if (Pos == SM->end())
2601 continue;
2602
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002603 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00002604 IEnd = Pos->second.end();
2605 I != IEnd; ++I) {
2606 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002607 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002608 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor546be3c2009-12-30 17:04:44 +00002609 Decl::IDNS_ObjCProtocol)))
2610 continue;
2611
2612 // Protocols are in distinct namespaces from everything else.
2613 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2614 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2615 (*I)->getIdentifierNamespace() != IDNS)
2616 continue;
2617
Douglas Gregor0cc84042010-01-14 15:47:35 +00002618 // Functions and function templates in the same scope overload
2619 // rather than hide. FIXME: Look for hiding based on function
2620 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002621 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002622 ND->isFunctionOrFunctionTemplate() &&
2623 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002624 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002625
Douglas Gregor546be3c2009-12-30 17:04:44 +00002626 // We've found a declaration that hides this one.
2627 return *I;
2628 }
2629 }
2630
2631 return 0;
2632}
2633
2634static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2635 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002636 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002637 VisibleDeclConsumer &Consumer,
2638 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00002639 if (!Ctx)
2640 return;
2641
Douglas Gregor546be3c2009-12-30 17:04:44 +00002642 // Make sure we don't visit the same context twice.
2643 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2644 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002645
Douglas Gregor4923aa22010-07-02 20:37:36 +00002646 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2647 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2648
Douglas Gregor546be3c2009-12-30 17:04:44 +00002649 // Enumerate all of the results in this context.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002650 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002651 CurCtx = CurCtx->getNextContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002652 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00002653 DEnd = CurCtx->decls_end();
2654 D != DEnd; ++D) {
Douglas Gregor70c23352010-12-09 21:44:02 +00002655 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002656 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002657 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002658 Visited.add(ND);
2659 }
Douglas Gregor70c23352010-12-09 21:44:02 +00002660 } else if (ObjCForwardProtocolDecl *ForwardProto
2661 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
2662 for (ObjCForwardProtocolDecl::protocol_iterator
2663 P = ForwardProto->protocol_begin(),
2664 PEnd = ForwardProto->protocol_end();
2665 P != PEnd;
2666 ++P) {
2667 if (Result.isAcceptableDecl(*P)) {
2668 Consumer.FoundDecl(*P, Visited.checkHidden(*P), InBaseClass);
2669 Visited.add(*P);
2670 }
2671 }
Douglas Gregord98abd82011-02-16 01:39:26 +00002672 } else if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D)) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00002673 ObjCInterfaceDecl *IFace = Class->getForwardInterfaceDecl();
Douglas Gregord98abd82011-02-16 01:39:26 +00002674 if (Result.isAcceptableDecl(IFace)) {
2675 Consumer.FoundDecl(IFace, Visited.checkHidden(IFace), InBaseClass);
2676 Visited.add(IFace);
2677 }
Douglas Gregor70c23352010-12-09 21:44:02 +00002678 }
Douglas Gregord98abd82011-02-16 01:39:26 +00002679
Sebastian Redl410c4f22010-08-31 20:53:31 +00002680 // Visit transparent contexts and inline namespaces inside this context.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002681 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
Sebastian Redl410c4f22010-08-31 20:53:31 +00002682 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Douglas Gregor0cc84042010-01-14 15:47:35 +00002683 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002684 Consumer, Visited);
2685 }
2686 }
2687 }
2688
2689 // Traverse using directives for qualified name lookup.
2690 if (QualifiedNameLookup) {
2691 ShadowContextRAII Shadow(Visited);
2692 DeclContext::udir_iterator I, E;
2693 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002694 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002695 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002696 }
2697 }
2698
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002699 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002700 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00002701 if (!Record->hasDefinition())
2702 return;
2703
Douglas Gregor546be3c2009-12-30 17:04:44 +00002704 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2705 BEnd = Record->bases_end();
2706 B != BEnd; ++B) {
2707 QualType BaseType = B->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002708
Douglas Gregor546be3c2009-12-30 17:04:44 +00002709 // Don't look into dependent bases, because name lookup can't look
2710 // there anyway.
2711 if (BaseType->isDependentType())
2712 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002713
Douglas Gregor546be3c2009-12-30 17:04:44 +00002714 const RecordType *Record = BaseType->getAs<RecordType>();
2715 if (!Record)
2716 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002717
Douglas Gregor546be3c2009-12-30 17:04:44 +00002718 // FIXME: It would be nice to be able to determine whether referencing
2719 // a particular member would be ambiguous. For example, given
2720 //
2721 // struct A { int member; };
2722 // struct B { int member; };
2723 // struct C : A, B { };
2724 //
2725 // void f(C *c) { c->### }
2726 //
2727 // accessing 'member' would result in an ambiguity. However, we
2728 // could be smart enough to qualify the member with the base
2729 // class, e.g.,
2730 //
2731 // c->B::member
2732 //
2733 // or
2734 //
2735 // c->A::member
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002736
Douglas Gregor546be3c2009-12-30 17:04:44 +00002737 // Find results in this base class (and its bases).
2738 ShadowContextRAII Shadow(Visited);
2739 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002740 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002741 }
2742 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002743
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002744 // Traverse the contexts of Objective-C classes.
2745 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2746 // Traverse categories.
2747 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2748 Category; Category = Category->getNextClassCategory()) {
2749 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002750 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002751 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002752 }
2753
2754 // Traverse protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00002755 for (ObjCInterfaceDecl::all_protocol_iterator
2756 I = IFace->all_referenced_protocol_begin(),
2757 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002758 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002759 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002760 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002761 }
2762
2763 // Traverse the superclass.
2764 if (IFace->getSuperClass()) {
2765 ShadowContextRAII Shadow(Visited);
2766 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002767 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002768 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002769
Douglas Gregorc220a182010-04-19 18:02:19 +00002770 // If there is an implementation, traverse it. We do this to find
2771 // synthesized ivars.
2772 if (IFace->getImplementation()) {
2773 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002774 LookupVisibleDecls(IFace->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00002775 QualifiedNameLookup, true, Consumer, Visited);
2776 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002777 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2778 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2779 E = Protocol->protocol_end(); I != E; ++I) {
2780 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002781 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002782 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002783 }
2784 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2785 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2786 E = Category->protocol_end(); I != E; ++I) {
2787 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002788 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002789 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002790 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002791
Douglas Gregorc220a182010-04-19 18:02:19 +00002792 // If there is an implementation, traverse it.
2793 if (Category->getImplementation()) {
2794 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002795 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00002796 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002797 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002798 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002799}
2800
2801static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2802 UnqualUsingDirectiveSet &UDirs,
2803 VisibleDeclConsumer &Consumer,
2804 VisibleDeclsRecord &Visited) {
2805 if (!S)
2806 return;
2807
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002808 if (!S->getEntity() ||
2809 (!S->getParent() &&
Douglas Gregor8071e422010-08-15 06:18:01 +00002810 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor539c5c32010-01-07 00:31:29 +00002811 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2812 // Walk through the declarations in this Scope.
2813 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2814 D != DEnd; ++D) {
John McCalld226f652010-08-21 09:40:31 +00002815 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor539c5c32010-01-07 00:31:29 +00002816 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002817 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002818 Visited.add(ND);
2819 }
2820 }
2821 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002822
Douglas Gregor711be1e2010-03-15 14:33:29 +00002823 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00002824 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00002825 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002826 // Look into this scope's declaration context, along with any of its
2827 // parent lookup contexts (e.g., enclosing classes), up to the point
2828 // where we hit the context stored in the next outer scope.
2829 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00002830 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002831
Douglas Gregordbdf5e72010-03-15 15:26:48 +00002832 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002833 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002834 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2835 if (Method->isInstanceMethod()) {
2836 // For instance methods, look for ivars in the method's interface.
2837 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2838 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregorca45da02010-11-02 20:36:02 +00002839 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002840 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Douglas Gregor62021192010-02-04 23:42:48 +00002841 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002842
Douglas Gregorca45da02010-11-02 20:36:02 +00002843 // Look for properties from which we can synthesize ivars, if
2844 // permitted.
2845 if (Result.getSema().getLangOptions().ObjCNonFragileABI2 &&
2846 IFace->getImplementation() &&
2847 Result.getLookupKind() == Sema::LookupOrdinaryName) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002848 for (ObjCInterfaceDecl::prop_iterator
Douglas Gregorca45da02010-11-02 20:36:02 +00002849 P = IFace->prop_begin(),
2850 PEnd = IFace->prop_end();
2851 P != PEnd; ++P) {
2852 if (Result.getSema().canSynthesizeProvisionalIvar(*P) &&
2853 !IFace->lookupInstanceVariable((*P)->getIdentifier())) {
2854 Consumer.FoundDecl(*P, Visited.checkHidden(*P), false);
2855 Visited.add(*P);
2856 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002857 }
2858 }
Douglas Gregorca45da02010-11-02 20:36:02 +00002859 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002860 }
2861
2862 // We've already performed all of the name lookup that we need
2863 // to for Objective-C methods; the next context will be the
2864 // outer scope.
2865 break;
2866 }
2867
Douglas Gregor546be3c2009-12-30 17:04:44 +00002868 if (Ctx->isFunctionOrMethod())
2869 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002870
2871 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002872 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002873 }
2874 } else if (!S->getParent()) {
2875 // Look into the translation unit scope. We walk through the translation
2876 // unit's declaration context, because the Scope itself won't have all of
2877 // the declarations if we loaded a precompiled header.
2878 // FIXME: We would like the translation unit's Scope object to point to the
2879 // translation unit, so we don't need this special "if" branch. However,
2880 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002881 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002882 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00002883 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002884 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002885 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002886 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002887 }
2888
Douglas Gregor546be3c2009-12-30 17:04:44 +00002889 if (Entity) {
2890 // Lookup visible declarations in any namespaces found by using
2891 // directives.
2892 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2893 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2894 for (; UI != UEnd; ++UI)
2895 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002896 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002897 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002898 }
2899
2900 // Lookup names in the parent scope.
2901 ShadowContextRAII Shadow(Visited);
2902 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2903}
2904
2905void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00002906 VisibleDeclConsumer &Consumer,
2907 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002908 // Determine the set of using directives available during
2909 // unqualified name lookup.
2910 Scope *Initial = S;
2911 UnqualUsingDirectiveSet UDirs;
2912 if (getLangOptions().CPlusPlus) {
2913 // Find the first namespace or translation-unit scope.
2914 while (S && !isNamespaceOrTranslationUnitScope(S))
2915 S = S->getParent();
2916
2917 UDirs.visitScopeChain(Initial, S);
2918 }
2919 UDirs.done();
2920
2921 // Look for visible declarations.
2922 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2923 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00002924 if (!IncludeGlobalScope)
2925 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00002926 ShadowContextRAII Shadow(Visited);
2927 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2928}
2929
2930void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00002931 VisibleDeclConsumer &Consumer,
2932 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002933 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2934 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00002935 if (!IncludeGlobalScope)
2936 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00002937 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002938 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002939 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002940}
2941
Chris Lattner4ae493c2011-02-18 02:08:43 +00002942/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara67843042011-03-05 18:21:20 +00002943/// If GnuLabelLoc is a valid source location, then this is a definition
2944/// of an __label__ label name, otherwise it is a normal label definition
2945/// or use.
Chris Lattner4ae493c2011-02-18 02:08:43 +00002946LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara67843042011-03-05 18:21:20 +00002947 SourceLocation GnuLabelLoc) {
Chris Lattner337e5502011-02-18 01:27:55 +00002948 // Do a lookup to see if we have a label with this name already.
Chris Lattner4ae493c2011-02-18 02:08:43 +00002949 NamedDecl *Res = 0;
Abramo Bagnara67843042011-03-05 18:21:20 +00002950
2951 if (GnuLabelLoc.isValid()) {
2952 // Local label definitions always shadow existing labels.
2953 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
2954 Scope *S = CurScope;
2955 PushOnScopeChains(Res, S, true);
2956 return cast<LabelDecl>(Res);
2957 }
2958
2959 // Not a GNU local label.
2960 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
2961 // If we found a label, check to see if it is in the same context as us.
2962 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattner337e5502011-02-18 01:27:55 +00002963 if (Res && Res->getDeclContext() != CurContext)
2964 Res = 0;
Chris Lattner337e5502011-02-18 01:27:55 +00002965 if (Res == 0) {
2966 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara67843042011-03-05 18:21:20 +00002967 Res = LabelDecl::Create(Context, CurContext, Loc, II);
2968 Scope *S = CurScope->getFnParent();
Chris Lattnerfebb5b82011-02-18 21:16:39 +00002969 assert(S && "Not in a function?");
2970 PushOnScopeChains(Res, S, true);
Chris Lattner337e5502011-02-18 01:27:55 +00002971 }
Chris Lattner337e5502011-02-18 01:27:55 +00002972 return cast<LabelDecl>(Res);
2973}
2974
2975//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00002976// Typo correction
Chris Lattner337e5502011-02-18 01:27:55 +00002977//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00002978
2979namespace {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002980
2981typedef llvm::StringMap<TypoCorrection, llvm::BumpPtrAllocator> TypoResultsMap;
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00002982typedef std::map<unsigned, TypoResultsMap *> TypoEditDistanceMap;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002983
2984static const unsigned MaxTypoDistanceResultSets = 5;
2985
Douglas Gregor546be3c2009-12-30 17:04:44 +00002986class TypoCorrectionConsumer : public VisibleDeclConsumer {
2987 /// \brief The name written that is a typo in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002988 StringRef Typo;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002989
2990 /// \brief The results found that have the smallest edit distance
2991 /// found (so far) with the typo name.
Douglas Gregore24b5752010-10-14 20:34:08 +00002992 ///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002993 /// The pointer value being set to the current DeclContext indicates
2994 /// whether there is a keyword with this name.
2995 TypoEditDistanceMap BestResults;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002996
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002997 /// \brief The worst of the best N edit distances found so far.
2998 unsigned MaxEditDistance;
2999
3000 Sema &SemaRef;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003001
Douglas Gregor546be3c2009-12-30 17:04:44 +00003002public:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003003 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003004 : Typo(Typo->getName()),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003005 MaxEditDistance((std::numeric_limits<unsigned>::max)()),
3006 SemaRef(SemaRef) { }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003007
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003008 ~TypoCorrectionConsumer() {
3009 for (TypoEditDistanceMap::iterator I = BestResults.begin(),
3010 IEnd = BestResults.end();
3011 I != IEnd;
3012 ++I)
3013 delete I->second;
3014 }
3015
Douglas Gregor0cc84042010-01-14 15:47:35 +00003016 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003017 void FoundName(StringRef Name);
3018 void addKeywordResult(StringRef Keyword);
3019 void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003020 NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003021 void addCorrection(TypoCorrection Correction);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003022
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003023 typedef TypoResultsMap::iterator result_iterator;
3024 typedef TypoEditDistanceMap::iterator distance_iterator;
3025 distance_iterator begin() { return BestResults.begin(); }
3026 distance_iterator end() { return BestResults.end(); }
3027 void erase(distance_iterator I) { BestResults.erase(I); }
Douglas Gregore24b5752010-10-14 20:34:08 +00003028 unsigned size() const { return BestResults.size(); }
3029 bool empty() const { return BestResults.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003030
Chris Lattner5f9e2722011-07-23 10:55:15 +00003031 TypoCorrection &operator[](StringRef Name) {
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003032 return (*BestResults.begin()->second)[Name];
Douglas Gregor7b824e82010-10-15 13:35:25 +00003033 }
3034
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003035 unsigned getMaxEditDistance() const {
3036 return MaxEditDistance;
3037 }
3038
3039 unsigned getBestEditDistance() {
3040 return (BestResults.empty()) ? MaxEditDistance : BestResults.begin()->first;
3041 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003042};
3043
3044}
3045
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003046void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003047 bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003048 // Don't consider hidden names for typo correction.
3049 if (Hiding)
3050 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003051
Douglas Gregor546be3c2009-12-30 17:04:44 +00003052 // Only consider entities with identifiers for names, ignoring
3053 // special names (constructors, overloaded operators, selectors,
3054 // etc.).
3055 IdentifierInfo *Name = ND->getIdentifier();
3056 if (!Name)
3057 return;
3058
Douglas Gregor95f42922010-10-14 22:11:03 +00003059 FoundName(Name->getName());
3060}
3061
Chris Lattner5f9e2722011-07-23 10:55:15 +00003062void TypoCorrectionConsumer::FoundName(StringRef Name) {
Douglas Gregor362a8f22010-10-19 19:39:10 +00003063 // Use a simple length-based heuristic to determine the minimum possible
3064 // edit distance. If the minimum isn't good enough, bail out early.
3065 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003066 if (MinED > MaxEditDistance || (MinED && Typo.size() / MinED < 3))
Douglas Gregor362a8f22010-10-19 19:39:10 +00003067 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003068
Douglas Gregora1194772010-10-19 22:14:33 +00003069 // Compute an upper bound on the allowable edit distance, so that the
3070 // edit-distance algorithm can short-circuit.
Jay Foadf1cc1d02011-04-23 09:06:00 +00003071 unsigned UpperBound =
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003072 std::min(unsigned((Typo.size() + 2) / 3), MaxEditDistance);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003073
Douglas Gregor546be3c2009-12-30 17:04:44 +00003074 // Compute the edit distance between the typo and the name of this
3075 // entity. If this edit distance is not worse than the best edit
3076 // distance we've seen so far, add it to the list of results.
Douglas Gregora1194772010-10-19 22:14:33 +00003077 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003078
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003079 if (ED > MaxEditDistance) {
Douglas Gregore24b5752010-10-14 20:34:08 +00003080 // This result is worse than the best results we've seen so far;
3081 // ignore it.
3082 return;
3083 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003084
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003085 addName(Name, NULL, ED);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003086}
3087
Chris Lattner5f9e2722011-07-23 10:55:15 +00003088void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00003089 // Compute the edit distance between the typo and this keyword.
3090 // If this edit distance is not worse than the best edit
3091 // distance we've seen so far, add it to the list of results.
3092 unsigned ED = Typo.edit_distance(Keyword);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003093 if (ED > MaxEditDistance) {
Douglas Gregore24b5752010-10-14 20:34:08 +00003094 // This result is worse than the best results we've seen so far;
3095 // ignore it.
3096 return;
3097 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003098
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003099 addName(Keyword, NULL, ED, NULL, true);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003100}
3101
Chris Lattner5f9e2722011-07-23 10:55:15 +00003102void TypoCorrectionConsumer::addName(StringRef Name,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003103 NamedDecl *ND,
3104 unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003105 NestedNameSpecifier *NNS,
3106 bool isKeyword) {
3107 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
3108 if (isKeyword) TC.makeKeyword();
3109 addCorrection(TC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003110}
3111
3112void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003113 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003114 TypoResultsMap *& Map = BestResults[Correction.getEditDistance()];
3115 if (!Map)
3116 Map = new TypoResultsMap;
Chandler Carruth55620532011-06-28 22:48:40 +00003117
3118 TypoCorrection &CurrentCorrection = (*Map)[Name];
3119 if (!CurrentCorrection ||
3120 // FIXME: The following should be rolled up into an operator< on
3121 // TypoCorrection with a more principled definition.
3122 CurrentCorrection.isKeyword() < Correction.isKeyword() ||
3123 Correction.getAsString(SemaRef.getLangOptions()) <
3124 CurrentCorrection.getAsString(SemaRef.getLangOptions()))
3125 CurrentCorrection = Correction;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003126
3127 while (BestResults.size() > MaxTypoDistanceResultSets) {
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003128 TypoEditDistanceMap::iterator Last = BestResults.end();
3129 --Last;
3130 delete Last->second;
3131 BestResults.erase(Last);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003132 }
3133}
3134
3135namespace {
3136
3137class SpecifierInfo {
3138 public:
3139 DeclContext* DeclCtx;
3140 NestedNameSpecifier* NameSpecifier;
3141 unsigned EditDistance;
3142
3143 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3144 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3145};
3146
Chris Lattner5f9e2722011-07-23 10:55:15 +00003147typedef SmallVector<DeclContext*, 4> DeclContextList;
3148typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003149
3150class NamespaceSpecifierSet {
3151 ASTContext &Context;
3152 DeclContextList CurContextChain;
3153 bool isSorted;
3154
3155 SpecifierInfoList Specifiers;
3156 llvm::SmallSetVector<unsigned, 4> Distances;
3157 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3158
3159 /// \brief Helper for building the list of DeclContexts between the current
3160 /// context and the top of the translation unit
3161 static DeclContextList BuildContextChain(DeclContext *Start);
3162
3163 void SortNamespaces();
3164
3165 public:
3166 explicit NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext)
Benjamin Kramerc5bb9d42011-07-05 09:46:31 +00003167 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
3168 isSorted(true) {}
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003169
3170 /// \brief Add the namespace to the set, computing the corresponding
3171 /// NestedNameSpecifier and its distance in the process.
3172 void AddNamespace(NamespaceDecl *ND);
3173
3174 typedef SpecifierInfoList::iterator iterator;
3175 iterator begin() {
3176 if (!isSorted) SortNamespaces();
3177 return Specifiers.begin();
3178 }
3179 iterator end() { return Specifiers.end(); }
3180};
3181
3182}
3183
3184DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003185 assert(Start && "Bulding a context chain from a null context");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003186 DeclContextList Chain;
3187 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3188 DC = DC->getLookupParent()) {
3189 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3190 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3191 !(ND && ND->isAnonymousNamespace()))
3192 Chain.push_back(DC->getPrimaryContext());
3193 }
3194 return Chain;
3195}
3196
3197void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003198 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003199 sortedDistances.append(Distances.begin(), Distances.end());
3200
3201 if (sortedDistances.size() > 1)
3202 std::sort(sortedDistances.begin(), sortedDistances.end());
3203
3204 Specifiers.clear();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003205 for (SmallVector<unsigned, 4>::iterator DI = sortedDistances.begin(),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003206 DIEnd = sortedDistances.end();
3207 DI != DIEnd; ++DI) {
3208 SpecifierInfoList &SpecList = DistanceMap[*DI];
3209 Specifiers.append(SpecList.begin(), SpecList.end());
3210 }
3211
3212 isSorted = true;
3213}
3214
3215void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003216 DeclContext *Ctx = cast<DeclContext>(ND);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003217 NestedNameSpecifier *NNS = NULL;
3218 unsigned NumSpecifiers = 0;
3219 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
3220
3221 // Eliminate common elements from the two DeclContext chains
3222 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3223 CEnd = CurContextChain.rend();
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003224 C != CEnd && !NamespaceDeclChain.empty() &&
3225 NamespaceDeclChain.back() == *C; ++C) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003226 NamespaceDeclChain.pop_back();
3227 }
3228
3229 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3230 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3231 CEnd = NamespaceDeclChain.rend();
3232 C != CEnd; ++C) {
3233 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3234 if (ND) {
3235 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3236 ++NumSpecifiers;
3237 }
3238 }
3239
3240 isSorted = false;
3241 Distances.insert(NumSpecifiers);
3242 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
Douglas Gregoraaf87162010-04-14 20:04:41 +00003243}
3244
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003245/// \brief Perform name lookup for a possible result for typo correction.
3246static void LookupPotentialTypoResult(Sema &SemaRef,
3247 LookupResult &Res,
3248 IdentifierInfo *Name,
3249 Scope *S, CXXScopeSpec *SS,
3250 DeclContext *MemberContext,
3251 bool EnteringContext,
3252 Sema::CorrectTypoContext CTC) {
3253 Res.suppressDiagnostics();
3254 Res.clear();
3255 Res.setLookupName(Name);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003256 if (MemberContext) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003257 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
3258 if (CTC == Sema::CTC_ObjCIvarLookup) {
3259 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3260 Res.addDecl(Ivar);
3261 Res.resolveKind();
3262 return;
3263 }
3264 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003265
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003266 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3267 Res.addDecl(Prop);
3268 Res.resolveKind();
3269 return;
3270 }
3271 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003272
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003273 SemaRef.LookupQualifiedName(Res, MemberContext);
3274 return;
3275 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003276
3277 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003278 EnteringContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003279
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003280 // Fake ivar lookup; this should really be part of
3281 // LookupParsedName.
3282 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3283 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003284 (Res.empty() ||
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003285 (Res.isSingleResult() &&
3286 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003287 if (ObjCIvarDecl *IV
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003288 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3289 Res.addDecl(IV);
3290 Res.resolveKind();
3291 }
3292 }
3293 }
3294}
3295
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003296/// \brief Add keywords to the consumer as possible typo corrections.
3297static void AddKeywordsToConsumer(Sema &SemaRef,
3298 TypoCorrectionConsumer &Consumer,
3299 Scope *S, Sema::CorrectTypoContext CTC) {
3300 // Add context-dependent keywords.
3301 bool WantTypeSpecifiers = false;
3302 bool WantExpressionKeywords = false;
3303 bool WantCXXNamedCasts = false;
3304 bool WantRemainingKeywords = false;
3305 switch (CTC) {
3306 case Sema::CTC_Unknown:
3307 WantTypeSpecifiers = true;
3308 WantExpressionKeywords = true;
3309 WantCXXNamedCasts = true;
3310 WantRemainingKeywords = true;
3311
3312 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
3313 if (Method->getClassInterface() &&
3314 Method->getClassInterface()->getSuperClass())
3315 Consumer.addKeywordResult("super");
3316
3317 break;
3318
3319 case Sema::CTC_NoKeywords:
3320 break;
3321
3322 case Sema::CTC_Type:
3323 WantTypeSpecifiers = true;
3324 break;
3325
3326 case Sema::CTC_ObjCMessageReceiver:
3327 Consumer.addKeywordResult("super");
3328 // Fall through to handle message receivers like expressions.
3329
3330 case Sema::CTC_Expression:
3331 if (SemaRef.getLangOptions().CPlusPlus)
3332 WantTypeSpecifiers = true;
3333 WantExpressionKeywords = true;
3334 // Fall through to get C++ named casts.
3335
3336 case Sema::CTC_CXXCasts:
3337 WantCXXNamedCasts = true;
3338 break;
3339
3340 case Sema::CTC_ObjCPropertyLookup:
3341 // FIXME: Add "isa"?
3342 break;
3343
3344 case Sema::CTC_MemberLookup:
3345 if (SemaRef.getLangOptions().CPlusPlus)
3346 Consumer.addKeywordResult("template");
3347 break;
3348
3349 case Sema::CTC_ObjCIvarLookup:
3350 break;
3351 }
3352
3353 if (WantTypeSpecifiers) {
3354 // Add type-specifier keywords to the set of results.
3355 const char *CTypeSpecs[] = {
3356 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor07f4a062011-07-01 21:27:45 +00003357 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003358 "_Complex", "_Imaginary",
3359 // storage-specifiers as well
3360 "extern", "inline", "static", "typedef"
3361 };
3362
3363 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3364 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3365 Consumer.addKeywordResult(CTypeSpecs[I]);
3366
3367 if (SemaRef.getLangOptions().C99)
3368 Consumer.addKeywordResult("restrict");
3369 if (SemaRef.getLangOptions().Bool || SemaRef.getLangOptions().CPlusPlus)
3370 Consumer.addKeywordResult("bool");
Douglas Gregor07f4a062011-07-01 21:27:45 +00003371 else if (SemaRef.getLangOptions().C99)
3372 Consumer.addKeywordResult("_Bool");
3373
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003374 if (SemaRef.getLangOptions().CPlusPlus) {
3375 Consumer.addKeywordResult("class");
3376 Consumer.addKeywordResult("typename");
3377 Consumer.addKeywordResult("wchar_t");
3378
3379 if (SemaRef.getLangOptions().CPlusPlus0x) {
3380 Consumer.addKeywordResult("char16_t");
3381 Consumer.addKeywordResult("char32_t");
3382 Consumer.addKeywordResult("constexpr");
3383 Consumer.addKeywordResult("decltype");
3384 Consumer.addKeywordResult("thread_local");
3385 }
3386 }
3387
3388 if (SemaRef.getLangOptions().GNUMode)
3389 Consumer.addKeywordResult("typeof");
3390 }
3391
3392 if (WantCXXNamedCasts && SemaRef.getLangOptions().CPlusPlus) {
3393 Consumer.addKeywordResult("const_cast");
3394 Consumer.addKeywordResult("dynamic_cast");
3395 Consumer.addKeywordResult("reinterpret_cast");
3396 Consumer.addKeywordResult("static_cast");
3397 }
3398
3399 if (WantExpressionKeywords) {
3400 Consumer.addKeywordResult("sizeof");
3401 if (SemaRef.getLangOptions().Bool || SemaRef.getLangOptions().CPlusPlus) {
3402 Consumer.addKeywordResult("false");
3403 Consumer.addKeywordResult("true");
3404 }
3405
3406 if (SemaRef.getLangOptions().CPlusPlus) {
3407 const char *CXXExprs[] = {
3408 "delete", "new", "operator", "throw", "typeid"
3409 };
3410 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3411 for (unsigned I = 0; I != NumCXXExprs; ++I)
3412 Consumer.addKeywordResult(CXXExprs[I]);
3413
3414 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3415 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3416 Consumer.addKeywordResult("this");
3417
3418 if (SemaRef.getLangOptions().CPlusPlus0x) {
3419 Consumer.addKeywordResult("alignof");
3420 Consumer.addKeywordResult("nullptr");
3421 }
3422 }
3423 }
3424
3425 if (WantRemainingKeywords) {
3426 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3427 // Statements.
3428 const char *CStmts[] = {
3429 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3430 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3431 for (unsigned I = 0; I != NumCStmts; ++I)
3432 Consumer.addKeywordResult(CStmts[I]);
3433
3434 if (SemaRef.getLangOptions().CPlusPlus) {
3435 Consumer.addKeywordResult("catch");
3436 Consumer.addKeywordResult("try");
3437 }
3438
3439 if (S && S->getBreakParent())
3440 Consumer.addKeywordResult("break");
3441
3442 if (S && S->getContinueParent())
3443 Consumer.addKeywordResult("continue");
3444
3445 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3446 Consumer.addKeywordResult("case");
3447 Consumer.addKeywordResult("default");
3448 }
3449 } else {
3450 if (SemaRef.getLangOptions().CPlusPlus) {
3451 Consumer.addKeywordResult("namespace");
3452 Consumer.addKeywordResult("template");
3453 }
3454
3455 if (S && S->isClassScope()) {
3456 Consumer.addKeywordResult("explicit");
3457 Consumer.addKeywordResult("friend");
3458 Consumer.addKeywordResult("mutable");
3459 Consumer.addKeywordResult("private");
3460 Consumer.addKeywordResult("protected");
3461 Consumer.addKeywordResult("public");
3462 Consumer.addKeywordResult("virtual");
3463 }
3464 }
3465
3466 if (SemaRef.getLangOptions().CPlusPlus) {
3467 Consumer.addKeywordResult("using");
3468
3469 if (SemaRef.getLangOptions().CPlusPlus0x)
3470 Consumer.addKeywordResult("static_assert");
3471 }
3472 }
3473}
3474
Douglas Gregor546be3c2009-12-30 17:04:44 +00003475/// \brief Try to "correct" a typo in the source code by finding
3476/// visible declarations whose names are similar to the name that was
3477/// present in the source code.
3478///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003479/// \param TypoName the \c DeclarationNameInfo structure that contains
3480/// the name that was present in the source code along with its location.
3481///
3482/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003483///
3484/// \param S the scope in which name lookup occurs.
3485///
3486/// \param SS the nested-name-specifier that precedes the name we're
3487/// looking for, if present.
3488///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003489/// \param MemberContext if non-NULL, the context in which to look for
3490/// a member access expression.
3491///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003492/// \param EnteringContext whether we're entering the context described by
Douglas Gregorbb092ba2009-12-31 05:20:13 +00003493/// the nested-name-specifier SS.
3494///
Douglas Gregoraaf87162010-04-14 20:04:41 +00003495/// \param CTC The context in which typo correction occurs, which impacts the
3496/// set of keywords permitted.
3497///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003498/// \param OPT when non-NULL, the search for visible declarations will
3499/// also walk the protocols in the qualified interfaces of \p OPT.
3500///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003501/// \returns a \c TypoCorrection containing the corrected name if the typo
3502/// along with information such as the \c NamedDecl where the corrected name
3503/// was declared, and any additional \c NestedNameSpecifier needed to access
3504/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3505TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3506 Sema::LookupNameKind LookupKind,
3507 Scope *S, CXXScopeSpec *SS,
3508 DeclContext *MemberContext,
3509 bool EnteringContext,
3510 CorrectTypoContext CTC,
3511 const ObjCObjectPointerType *OPT) {
Douglas Gregora0068fc2010-07-09 17:35:33 +00003512 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003513 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003514
Douglas Gregor546be3c2009-12-30 17:04:44 +00003515 // We only attempt to correct typos for identifiers.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003516 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003517 if (!Typo)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003518 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003519
3520 // If the scope specifier itself was invalid, don't try to correct
3521 // typos.
3522 if (SS && SS->isInvalid())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003523 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003524
3525 // Never try to correct typos during template deduction or
3526 // instantiation.
3527 if (!ActiveTemplateInstantiations.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003528 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003529
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003530 NamespaceSpecifierSet Namespaces(Context, CurContext);
3531
3532 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003533
Douglas Gregoraaf87162010-04-14 20:04:41 +00003534 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003535 bool IsUnqualifiedLookup = false;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003536 if (MemberContext) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003537 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003538
3539 // Look in qualified interfaces.
3540 if (OPT) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003541 for (ObjCObjectPointerType::qual_iterator
3542 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003543 I != E; ++I)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003544 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003545 }
3546 } else if (SS && SS->isSet()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003547 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
3548 if (!DC)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003549 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003550
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003551 // Provide a stop gap for files that are just seriously broken. Trying
3552 // to correct all typos can turn into a HUGE performance penalty, causing
3553 // some files to take minutes to get rejected by the parser.
3554 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003555 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003556 ++TyposCorrected;
3557
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003558 LookupVisibleDecls(DC, LookupKind, Consumer);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003559 } else {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003560 IsUnqualifiedLookup = true;
3561 UnqualifiedTyposCorrectedMap::iterator Cached
3562 = UnqualifiedTyposCorrected.find(Typo);
3563 if (Cached == UnqualifiedTyposCorrected.end()) {
3564 // Provide a stop gap for files that are just seriously broken. Trying
3565 // to correct all typos can turn into a HUGE performance penalty, causing
3566 // some files to take minutes to get rejected by the parser.
3567 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003568 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003569
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003570 // For unqualified lookup, look through all of the names that we have
3571 // seen in this translation unit.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003572 for (IdentifierTable::iterator I = Context.Idents.begin(),
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003573 IEnd = Context.Idents.end();
3574 I != IEnd; ++I)
3575 Consumer.FoundName(I->getKey());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003576
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003577 // Walk through identifiers in external identifier sources.
3578 if (IdentifierInfoLookup *External
Douglas Gregor95f42922010-10-14 22:11:03 +00003579 = Context.Idents.getExternalIdentifierLookup()) {
Ted Kremenek7a054b12010-11-07 06:11:33 +00003580 llvm::OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003581 do {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003582 StringRef Name = Iter->Next();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003583 if (Name.empty())
3584 break;
Douglas Gregor95f42922010-10-14 22:11:03 +00003585
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003586 Consumer.FoundName(Name);
3587 } while (true);
3588 }
3589 } else {
3590 // Use the cached value, unless it's a keyword. In the keyword case, we'll
3591 // end up adding the keyword below.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003592 if (!Cached->second)
3593 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003594
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003595 if (!Cached->second.isKeyword())
3596 Consumer.addCorrection(Cached->second);
Douglas Gregor95f42922010-10-14 22:11:03 +00003597 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003598 }
3599
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003600 AddKeywordsToConsumer(*this, Consumer, S, CTC);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003601
Douglas Gregoraaf87162010-04-14 20:04:41 +00003602 // If we haven't found anything, we're done.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003603 if (Consumer.empty()) {
3604 // If this was an unqualified lookup, note that no correction was found.
3605 if (IsUnqualifiedLookup)
3606 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003607
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003608 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003609 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003610
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003611 // Make sure that the user typed at least 3 characters for each correction
Douglas Gregore24b5752010-10-14 20:34:08 +00003612 // made. Otherwise, we don't even both looking at the results.
3613 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003614 if (ED > 0 && Typo->getName().size() / ED < 3) {
3615 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregor157a3ff2010-10-27 14:20:34 +00003616 if (IsUnqualifiedLookup)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003617 (void)UnqualifiedTyposCorrected[Typo];
3618
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003619 return TypoCorrection();
3620 }
3621
3622 // Build the NestedNameSpecifiers for the KnownNamespaces
3623 if (getLangOptions().CPlusPlus) {
3624 // Load any externally-known namespaces.
3625 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003626 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003627 LoadedExternalKnownNamespaces = true;
3628 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
3629 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
3630 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
3631 }
3632
3633 for (llvm::DenseMap<NamespaceDecl*, bool>::iterator
3634 KNI = KnownNamespaces.begin(),
3635 KNIEnd = KnownNamespaces.end();
3636 KNI != KNIEnd; ++KNI)
3637 Namespaces.AddNamespace(KNI->first);
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003638 }
Douglas Gregore24b5752010-10-14 20:34:08 +00003639
3640 // Weed out any names that could not be found by name lookup.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003641 llvm::SmallPtrSet<IdentifierInfo*, 16> QualifiedResults;
3642 LookupResult TmpRes(*this, TypoName, LookupKind);
3643 TmpRes.suppressDiagnostics();
3644 while (!Consumer.empty()) {
3645 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3646 unsigned ED = DI->first;
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003647 for (TypoCorrectionConsumer::result_iterator I = DI->second->begin(),
3648 IEnd = DI->second->end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003649 I != IEnd; /* Increment in loop. */) {
3650 // If the item already has been looked up or is a keyword, keep it
3651 if (I->second.isResolved()) {
3652 ++I;
3653 continue;
Douglas Gregore24b5752010-10-14 20:34:08 +00003654 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003655
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003656 // Perform name lookup on this name.
3657 IdentifierInfo *Name = I->second.getCorrectionAsIdentifierInfo();
3658 LookupPotentialTypoResult(*this, TmpRes, Name, S, SS, MemberContext,
3659 EnteringContext, CTC);
3660
3661 switch (TmpRes.getResultKind()) {
3662 case LookupResult::NotFound:
3663 case LookupResult::NotFoundInCurrentInstantiation:
3664 QualifiedResults.insert(Name);
3665 // We didn't find this name in our scope, or didn't like what we found;
3666 // ignore it.
3667 {
3668 TypoCorrectionConsumer::result_iterator Next = I;
3669 ++Next;
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003670 DI->second->erase(I);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003671 I = Next;
3672 }
3673 break;
3674
3675 case LookupResult::Ambiguous:
3676 // We don't deal with ambiguities.
3677 return TypoCorrection();
3678
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003679 case LookupResult::FoundOverloaded: {
3680 // Store all of the Decls for overloaded symbols
3681 for (LookupResult::iterator TRD = TmpRes.begin(),
3682 TRDEnd = TmpRes.end();
3683 TRD != TRDEnd; ++TRD)
3684 I->second.addCorrectionDecl(*TRD);
3685 ++I;
3686 break;
3687 }
3688
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003689 case LookupResult::Found:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003690 case LookupResult::FoundUnresolvedValue:
3691 I->second.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
3692 ++I;
3693 break;
3694 }
Douglas Gregore24b5752010-10-14 20:34:08 +00003695 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003696
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003697 if (DI->second->empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003698 Consumer.erase(DI);
3699 else if (!getLangOptions().CPlusPlus || QualifiedResults.empty() || !ED)
3700 // If there are results in the closest possible bucket, stop
3701 break;
3702
3703 // Only perform the qualified lookups for C++
3704 if (getLangOptions().CPlusPlus) {
3705 TmpRes.suppressDiagnostics();
3706 for (llvm::SmallPtrSet<IdentifierInfo*,
3707 16>::iterator QRI = QualifiedResults.begin(),
3708 QRIEnd = QualifiedResults.end();
3709 QRI != QRIEnd; ++QRI) {
3710 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
3711 NIEnd = Namespaces.end();
3712 NI != NIEnd; ++NI) {
3713 DeclContext *Ctx = NI->DeclCtx;
3714 unsigned QualifiedED = ED + NI->EditDistance;
3715
3716 // Stop searching once the namespaces are too far away to create
3717 // acceptable corrections for this identifier (since the namespaces
3718 // are sorted in ascending order by edit distance)
3719 if (QualifiedED > Consumer.getMaxEditDistance()) break;
3720
3721 TmpRes.clear();
3722 TmpRes.setLookupName(*QRI);
3723 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
3724
3725 switch (TmpRes.getResultKind()) {
3726 case LookupResult::Found:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003727 case LookupResult::FoundUnresolvedValue:
3728 Consumer.addName((*QRI)->getName(), TmpRes.getAsSingle<NamedDecl>(),
3729 QualifiedED, NI->NameSpecifier);
3730 break;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003731 case LookupResult::FoundOverloaded: {
3732 TypoCorrection corr(&Context.Idents.get((*QRI)->getName()), NULL,
3733 NI->NameSpecifier, QualifiedED);
3734 for (LookupResult::iterator TRD = TmpRes.begin(),
3735 TRDEnd = TmpRes.end();
3736 TRD != TRDEnd; ++TRD)
3737 corr.addCorrectionDecl(*TRD);
3738 Consumer.addCorrection(corr);
3739 break;
3740 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003741 case LookupResult::NotFound:
3742 case LookupResult::NotFoundInCurrentInstantiation:
3743 case LookupResult::Ambiguous:
3744 break;
3745 }
3746 }
3747 }
3748 }
3749
3750 QualifiedResults.clear();
3751 }
3752
3753 // No corrections remain...
3754 if (Consumer.empty()) return TypoCorrection();
3755
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003756 TypoResultsMap &BestResults = *Consumer.begin()->second;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003757 ED = Consumer.begin()->first;
3758
3759 if (ED > 0 && Typo->getName().size() / ED < 3) {
3760 // If this was an unqualified lookup, note that no correction was found.
3761 if (IsUnqualifiedLookup)
3762 (void)UnqualifiedTyposCorrected[Typo];
3763
3764 return TypoCorrection();
3765 }
3766
3767 // If we have multiple possible corrections, eliminate the ones where we
3768 // added namespace qualifiers to try to resolve the ambiguity (and to favor
3769 // corrections without additional namespace qualifiers)
3770 if (getLangOptions().CPlusPlus && BestResults.size() > 1) {
3771 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003772 for (TypoCorrectionConsumer::result_iterator I = DI->second->begin(),
3773 IEnd = DI->second->end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003774 I != IEnd; /* Increment in loop. */) {
3775 if (I->second.getCorrectionSpecifier() != NULL) {
3776 TypoCorrectionConsumer::result_iterator Cur = I;
3777 ++I;
Douglas Gregor2ecc28a2011-06-28 16:44:39 +00003778 DI->second->erase(Cur);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003779 } else ++I;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003780 }
Douglas Gregoraaf87162010-04-14 20:04:41 +00003781 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003782
Douglas Gregore24b5752010-10-14 20:34:08 +00003783 // If only a single name remains, return that result.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003784 if (BestResults.size() == 1) {
3785 const llvm::StringMapEntry<TypoCorrection> &Correction = *(BestResults.begin());
3786 const TypoCorrection &Result = Correction.second;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003787
Douglas Gregor53e4b552010-10-26 17:18:00 +00003788 // Don't correct to a keyword that's the same as the typo; the keyword
3789 // wasn't actually in scope.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003790 if (ED == 0 && Result.isKeyword()) return TypoCorrection();
3791
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003792 // Record the correction for unqualified lookup.
3793 if (IsUnqualifiedLookup)
3794 UnqualifiedTyposCorrected[Typo] = Result;
3795
3796 return Result;
3797 }
3798 else if (BestResults.size() > 1 && CTC == CTC_ObjCMessageReceiver
3799 && BestResults["super"].isKeyword()) {
3800 // Prefer 'super' when we're completing in a message-receiver
3801 // context.
3802
3803 // Don't correct to a keyword that's the same as the typo; the keyword
3804 // wasn't actually in scope.
3805 if (ED == 0) return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003806
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003807 // Record the correction for unqualified lookup.
3808 if (IsUnqualifiedLookup)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003809 UnqualifiedTyposCorrected[Typo] = BestResults["super"];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003810
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003811 return BestResults["super"];
Douglas Gregor7b824e82010-10-15 13:35:25 +00003812 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003813
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003814 if (IsUnqualifiedLookup)
3815 (void)UnqualifiedTyposCorrected[Typo];
3816
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003817 return TypoCorrection();
3818}
3819
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003820void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
3821 if (!CDecl) return;
3822
3823 if (isKeyword())
3824 CorrectionDecls.clear();
3825
3826 CorrectionDecls.push_back(CDecl);
3827
3828 if (!CorrectionName)
3829 CorrectionName = CDecl->getDeclName();
3830}
3831
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003832std::string TypoCorrection::getAsString(const LangOptions &LO) const {
3833 if (CorrectionNameSpec) {
3834 std::string tmpBuffer;
3835 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
3836 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
3837 return PrefixOStream.str() + CorrectionName.getAsString();
3838 }
3839
3840 return CorrectionName.getAsString();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003841}