blob: 0c1a1fa216dbbfef52550e932e23953cb81de65a [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"
John McCall6e247262009-10-10 05:48:19 +000038#include "llvm/Support/ErrorHandling.h"
Douglas Gregore24b5752010-10-14 20:34:08 +000039#include <limits>
Douglas Gregor546be3c2009-12-30 17:04:44 +000040#include <list>
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +000041#include <set>
Douglas Gregor2a3009a2009-02-03 19:21:40 +000042#include <vector>
43#include <iterator>
44#include <utility>
45#include <algorithm>
Douglas Gregord8bba9c2011-06-28 16:20:02 +000046#include <map>
Douglas Gregoreb11cd02009-01-14 22:20:51 +000047
48using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000049using namespace sema;
Douglas Gregoreb11cd02009-01-14 22:20:51 +000050
John McCalld7be78a2009-11-10 07:01:13 +000051namespace {
52 class UnqualUsingEntry {
53 const DeclContext *Nominated;
54 const DeclContext *CommonAncestor;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000055
John McCalld7be78a2009-11-10 07:01:13 +000056 public:
57 UnqualUsingEntry(const DeclContext *Nominated,
58 const DeclContext *CommonAncestor)
59 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
60 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000061
John McCalld7be78a2009-11-10 07:01:13 +000062 const DeclContext *getCommonAncestor() const {
63 return CommonAncestor;
64 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000065
John McCalld7be78a2009-11-10 07:01:13 +000066 const DeclContext *getNominatedNamespace() const {
67 return Nominated;
68 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000069
John McCalld7be78a2009-11-10 07:01:13 +000070 // Sort by the pointer value of the common ancestor.
71 struct Comparator {
72 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
73 return L.getCommonAncestor() < R.getCommonAncestor();
74 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000075
John McCalld7be78a2009-11-10 07:01:13 +000076 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
77 return E.getCommonAncestor() < DC;
78 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000079
John McCalld7be78a2009-11-10 07:01:13 +000080 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
81 return DC < E.getCommonAncestor();
82 }
83 };
84 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +000085
John McCalld7be78a2009-11-10 07:01:13 +000086 /// A collection of using directives, as used by C++ unqualified
87 /// lookup.
88 class UnqualUsingDirectiveSet {
89 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000090
John McCalld7be78a2009-11-10 07:01:13 +000091 ListTy list;
92 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000093
John McCalld7be78a2009-11-10 07:01:13 +000094 public:
95 UnqualUsingDirectiveSet() {}
Douglas Gregor2a3009a2009-02-03 19:21:40 +000096
John McCalld7be78a2009-11-10 07:01:13 +000097 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000098 // C++ [namespace.udir]p1:
John McCalld7be78a2009-11-10 07:01:13 +000099 // During unqualified name lookup, the names appear as if they
100 // were declared in the nearest enclosing namespace which contains
101 // both the using-directive and the nominated namespace.
102 DeclContext *InnermostFileDC
103 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
104 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000105
John McCalld7be78a2009-11-10 07:01:13 +0000106 for (; S; S = S->getParent()) {
John McCalld7be78a2009-11-10 07:01:13 +0000107 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
108 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
109 visit(Ctx, EffectiveDC);
110 } else {
111 Scope::udir_iterator I = S->using_directives_begin(),
112 End = S->using_directives_end();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000113
John McCalld7be78a2009-11-10 07:01:13 +0000114 for (; I != End; ++I)
John McCalld226f652010-08-21 09:40:31 +0000115 visit(*I, InnermostFileDC);
John McCalld7be78a2009-11-10 07:01:13 +0000116 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000117 }
118 }
John McCalld7be78a2009-11-10 07:01:13 +0000119
120 // Visits a context and collect all of its using directives
121 // recursively. Treats all using directives as if they were
122 // declared in the context.
123 //
124 // A given context is only every visited once, so it is important
125 // that contexts be visited from the inside out in order to get
126 // the effective DCs right.
127 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
128 if (!visited.insert(DC))
129 return;
130
131 addUsingDirectives(DC, EffectiveDC);
132 }
133
134 // Visits a using directive and collects all of its using
135 // directives recursively. Treats all using directives as if they
136 // were declared in the effective DC.
137 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
138 DeclContext *NS = UD->getNominatedNamespace();
139 if (!visited.insert(NS))
140 return;
141
142 addUsingDirective(UD, EffectiveDC);
143 addUsingDirectives(NS, EffectiveDC);
144 }
145
146 // Adds all the using directives in a context (and those nominated
147 // by its using directives, transitively) as if they appeared in
148 // the given effective context.
149 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
150 llvm::SmallVector<DeclContext*,4> queue;
151 while (true) {
152 DeclContext::udir_iterator I, End;
153 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
154 UsingDirectiveDecl *UD = *I;
155 DeclContext *NS = UD->getNominatedNamespace();
156 if (visited.insert(NS)) {
157 addUsingDirective(UD, EffectiveDC);
158 queue.push_back(NS);
159 }
160 }
161
162 if (queue.empty())
163 return;
164
165 DC = queue.back();
166 queue.pop_back();
167 }
168 }
169
170 // Add a using directive as if it had been declared in the given
171 // context. This helps implement C++ [namespace.udir]p3:
172 // The using-directive is transitive: if a scope contains a
173 // using-directive that nominates a second namespace that itself
174 // contains using-directives, the effect is as if the
175 // using-directives from the second namespace also appeared in
176 // the first.
177 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
178 // Find the common ancestor between the effective context and
179 // the nominated namespace.
180 DeclContext *Common = UD->getNominatedNamespace();
181 while (!Common->Encloses(EffectiveDC))
182 Common = Common->getParent();
John McCall12ea5782009-11-10 09:20:04 +0000183 Common = Common->getPrimaryContext();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000184
John McCalld7be78a2009-11-10 07:01:13 +0000185 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
186 }
187
188 void done() {
189 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
190 }
191
John McCalld7be78a2009-11-10 07:01:13 +0000192 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000193
John McCalld7be78a2009-11-10 07:01:13 +0000194 const_iterator begin() const { return list.begin(); }
195 const_iterator end() const { return list.end(); }
196
197 std::pair<const_iterator,const_iterator>
198 getNamespacesFor(DeclContext *DC) const {
John McCall12ea5782009-11-10 09:20:04 +0000199 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCalld7be78a2009-11-10 07:01:13 +0000200 UnqualUsingEntry::Comparator());
201 }
202 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000203}
204
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000205// Retrieve the set of identifier namespaces that correspond to a
206// specific kind of name lookup.
John McCall1d7c5282009-12-18 10:40:03 +0000207static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
208 bool CPlusPlus,
209 bool Redeclaration) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000210 unsigned IDNS = 0;
211 switch (NameKind) {
212 case Sema::LookupOrdinaryName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000213 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000214 IDNS = Decl::IDNS_Ordinary;
John McCall1d7c5282009-12-18 10:40:03 +0000215 if (CPlusPlus) {
John McCall0d6b1642010-04-23 18:46:30 +0000216 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattner337e5502011-02-18 01:27:55 +0000217 if (Redeclaration)
218 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCall1d7c5282009-12-18 10:40:03 +0000219 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000220 break;
221
John McCall76d32642010-04-24 01:30:58 +0000222 case Sema::LookupOperatorName:
223 // Operator lookup is its own crazy thing; it is not the same
224 // as (e.g.) looking up an operator name for redeclaration.
225 assert(!Redeclaration && "cannot do redeclaration operator lookup");
226 IDNS = Decl::IDNS_NonMemberOperator;
227 break;
228
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000229 case Sema::LookupTagName:
John McCall0d6b1642010-04-23 18:46:30 +0000230 if (CPlusPlus) {
231 IDNS = Decl::IDNS_Type;
232
233 // When looking for a redeclaration of a tag name, we add:
234 // 1) TagFriend to find undeclared friend decls
235 // 2) Namespace because they can't "overload" with tag decls.
236 // 3) Tag because it includes class templates, which can't
237 // "overload" with tag decls.
238 if (Redeclaration)
239 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
240 } else {
241 IDNS = Decl::IDNS_Tag;
242 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000243 break;
Chris Lattner337e5502011-02-18 01:27:55 +0000244 case Sema::LookupLabel:
245 IDNS = Decl::IDNS_Label;
246 break;
247
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000248 case Sema::LookupMemberName:
249 IDNS = Decl::IDNS_Member;
250 if (CPlusPlus)
Mike Stump1eb44332009-09-09 15:08:12 +0000251 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000252 break;
253
254 case Sema::LookupNestedNameSpecifierName:
John McCall0d6b1642010-04-23 18:46:30 +0000255 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
256 break;
257
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000258 case Sema::LookupNamespaceName:
John McCall0d6b1642010-04-23 18:46:30 +0000259 IDNS = Decl::IDNS_Namespace;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000260 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000261
John McCall9f54ad42009-12-10 09:41:52 +0000262 case Sema::LookupUsingDeclName:
263 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
264 | Decl::IDNS_Member | Decl::IDNS_Using;
265 break;
266
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000267 case Sema::LookupObjCProtocolName:
268 IDNS = Decl::IDNS_ObjCProtocol;
269 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000270
Douglas Gregor8071e422010-08-15 06:18:01 +0000271 case Sema::LookupAnyName:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000272 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor8071e422010-08-15 06:18:01 +0000273 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
274 | Decl::IDNS_Type;
275 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000276 }
277 return IDNS;
278}
279
John McCall1d7c5282009-12-18 10:40:03 +0000280void LookupResult::configure() {
Chris Lattner337e5502011-02-18 01:27:55 +0000281 IDNS = getIDNS(LookupKind, SemaRef.getLangOptions().CPlusPlus,
John McCall1d7c5282009-12-18 10:40:03 +0000282 isForRedeclaration());
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000283
284 // If we're looking for one of the allocation or deallocation
285 // operators, make sure that the implicitly-declared new and delete
286 // operators can be found.
287 if (!isForRedeclaration()) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000288 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000289 case OO_New:
290 case OO_Delete:
291 case OO_Array_New:
292 case OO_Array_Delete:
293 SemaRef.DeclareGlobalNewDelete();
294 break;
295
296 default:
297 break;
298 }
299 }
John McCall1d7c5282009-12-18 10:40:03 +0000300}
301
John McCall2a7fb272010-08-25 05:32:35 +0000302void LookupResult::sanity() const {
303 assert(ResultKind != NotFound || Decls.size() == 0);
304 assert(ResultKind != Found || Decls.size() == 1);
305 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
306 (Decls.size() == 1 &&
307 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
308 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
309 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorf17b58c2010-10-22 22:08:47 +0000310 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
311 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall2a7fb272010-08-25 05:32:35 +0000312 assert((Paths != NULL) == (ResultKind == Ambiguous &&
313 (Ambiguity == AmbiguousBaseSubobjectTypes ||
314 Ambiguity == AmbiguousBaseSubobjects)));
315}
John McCall2a7fb272010-08-25 05:32:35 +0000316
John McCallf36e02d2009-10-09 21:13:30 +0000317// Necessary because CXXBasePaths is not complete in Sema.h
John McCall7d384dd2009-11-18 07:57:50 +0000318void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCallf36e02d2009-10-09 21:13:30 +0000319 delete Paths;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000320}
321
John McCall7453ed42009-11-22 00:44:51 +0000322/// Resolves the result kind of this lookup.
John McCall7d384dd2009-11-18 07:57:50 +0000323void LookupResult::resolveKind() {
John McCallf36e02d2009-10-09 21:13:30 +0000324 unsigned N = Decls.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000325
John McCallf36e02d2009-10-09 21:13:30 +0000326 // Fast case: no possible ambiguity.
John McCall68263142009-11-18 22:49:29 +0000327 if (N == 0) {
John McCalldc5c7862010-01-15 21:27:01 +0000328 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall68263142009-11-18 22:49:29 +0000329 return;
330 }
331
John McCall7453ed42009-11-22 00:44:51 +0000332 // If there's a single decl, we need to examine it to decide what
333 // kind of lookup this is.
John McCall7ba107a2009-11-18 02:36:19 +0000334 if (N == 1) {
Douglas Gregor2b147f02010-04-25 21:15:30 +0000335 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
336 if (isa<FunctionTemplateDecl>(D))
John McCall7453ed42009-11-22 00:44:51 +0000337 ResultKind = FoundOverloaded;
Douglas Gregor2b147f02010-04-25 21:15:30 +0000338 else if (isa<UnresolvedUsingValueDecl>(D))
John McCall7ba107a2009-11-18 02:36:19 +0000339 ResultKind = FoundUnresolvedValue;
340 return;
341 }
John McCallf36e02d2009-10-09 21:13:30 +0000342
John McCall6e247262009-10-10 05:48:19 +0000343 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000344 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000345
John McCallf36e02d2009-10-09 21:13:30 +0000346 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000347 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000348
John McCallf36e02d2009-10-09 21:13:30 +0000349 bool Ambiguous = false;
350 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000351 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000352
353 unsigned UniqueTagIndex = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000354
John McCallf36e02d2009-10-09 21:13:30 +0000355 unsigned I = 0;
356 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000357 NamedDecl *D = Decls[I]->getUnderlyingDecl();
358 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000359
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000360 // Redeclarations of types via typedef can occur both within a scope
361 // and, through using declarations and directives, across scopes. There is
362 // no ambiguity if they all refer to the same type, so unique based on the
363 // canonical type.
364 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
365 if (!TD->getDeclContext()->isRecord()) {
366 QualType T = SemaRef.Context.getTypeDeclType(TD);
367 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
368 // The type is not unique; pull something off the back and continue
369 // at this index.
370 Decls[I] = Decls[--N];
371 continue;
372 }
373 }
374 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000375
John McCall314be4e2009-11-17 07:50:12 +0000376 if (!Unique.insert(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000377 // If it's not unique, pull something off the back (and
378 // continue at this index).
379 Decls[I] = Decls[--N];
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000380 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000381 }
382
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000383 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000384
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000385 if (isa<UnresolvedUsingValueDecl>(D)) {
386 HasUnresolved = true;
387 } else if (isa<TagDecl>(D)) {
388 if (HasTag)
389 Ambiguous = true;
390 UniqueTagIndex = I;
391 HasTag = true;
392 } else if (isa<FunctionTemplateDecl>(D)) {
393 HasFunction = true;
394 HasFunctionTemplate = true;
395 } else if (isa<FunctionDecl>(D)) {
396 HasFunction = true;
397 } else {
398 if (HasNonFunction)
399 Ambiguous = true;
400 HasNonFunction = true;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000401 }
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000402 I++;
Mike Stump1eb44332009-09-09 15:08:12 +0000403 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000404
John McCallf36e02d2009-10-09 21:13:30 +0000405 // C++ [basic.scope.hiding]p2:
406 // A class name or enumeration name can be hidden by the name of
407 // an object, function, or enumerator declared in the same
408 // scope. If a class or enumeration name and an object, function,
409 // or enumerator are declared in the same scope (in any order)
410 // with the same name, the class or enumeration name is hidden
411 // wherever the object, function, or enumerator name is visible.
412 // But it's still an error if there are distinct tag types found,
413 // even if they're not visible. (ref?)
John McCallfda8e122009-12-03 00:58:24 +0000414 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregor77a1a882010-10-23 16:06:17 +0000415 (HasFunction || HasNonFunction || HasUnresolved)) {
416 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
417 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
418 Decls[UniqueTagIndex] = Decls[--N];
419 else
420 Ambiguous = true;
421 }
Anders Carlsson8b50d012009-06-26 03:37:05 +0000422
John McCallf36e02d2009-10-09 21:13:30 +0000423 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000424
John McCallfda8e122009-12-03 00:58:24 +0000425 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000426 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000427
John McCallf36e02d2009-10-09 21:13:30 +0000428 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000429 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000430 else if (HasUnresolved)
431 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000432 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000433 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000434 else
John McCalla24dc2e2009-11-17 02:14:36 +0000435 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000436}
437
John McCall7d384dd2009-11-18 07:57:50 +0000438void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall6b2accb2010-02-10 09:31:12 +0000439 CXXBasePaths::const_paths_iterator I, E;
John McCallf36e02d2009-10-09 21:13:30 +0000440 DeclContext::lookup_iterator DI, DE;
441 for (I = P.begin(), E = P.end(); I != E; ++I)
442 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
443 addDecl(*DI);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000444}
445
John McCall7d384dd2009-11-18 07:57:50 +0000446void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000447 Paths = new CXXBasePaths;
448 Paths->swap(P);
449 addDeclsFromBasePaths(*Paths);
450 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000451 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000452}
453
John McCall7d384dd2009-11-18 07:57:50 +0000454void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000455 Paths = new CXXBasePaths;
456 Paths->swap(P);
457 addDeclsFromBasePaths(*Paths);
458 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000459 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000460}
461
John McCall7d384dd2009-11-18 07:57:50 +0000462void LookupResult::print(llvm::raw_ostream &Out) {
John McCallf36e02d2009-10-09 21:13:30 +0000463 Out << Decls.size() << " result(s)";
464 if (isAmbiguous()) Out << ", ambiguous";
465 if (Paths) Out << ", base paths present";
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000466
John McCallf36e02d2009-10-09 21:13:30 +0000467 for (iterator I = begin(), E = end(); I != E; ++I) {
468 Out << "\n";
469 (*I)->print(Out, 2);
470 }
471}
472
Douglas Gregor85910982010-02-12 05:48:04 +0000473/// \brief Lookup a builtin function, when name lookup would otherwise
474/// fail.
475static bool LookupBuiltin(Sema &S, LookupResult &R) {
476 Sema::LookupNameKind NameKind = R.getLookupKind();
477
478 // If we didn't find a use of this identifier, and if the identifier
479 // corresponds to a compiler builtin, create the decl object for the builtin
480 // now, injecting it into translation unit scope, and return it.
481 if (NameKind == Sema::LookupOrdinaryName ||
482 NameKind == Sema::LookupRedeclarationWithLinkage) {
483 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
484 if (II) {
485 // If this is a builtin on this (or all) targets, create the decl.
486 if (unsigned BuiltinID = II->getBuiltinID()) {
487 // In C++, we don't have any predefined library functions like
488 // 'malloc'. Instead, we'll just error.
489 if (S.getLangOptions().CPlusPlus &&
490 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
491 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000492
493 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
494 BuiltinID, S.TUScope,
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000495 R.isForRedeclaration(),
496 R.getNameLoc())) {
Douglas Gregor85910982010-02-12 05:48:04 +0000497 R.addDecl(D);
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000498 return true;
499 }
500
501 if (R.isForRedeclaration()) {
502 // If we're redeclaring this function anyway, forget that
503 // this was a builtin at all.
504 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
505 }
506
507 return false;
Douglas Gregor85910982010-02-12 05:48:04 +0000508 }
509 }
510 }
511
512 return false;
513}
514
Douglas Gregor4923aa22010-07-02 20:37:36 +0000515/// \brief Determine whether we can declare a special member function within
516/// the class at this point.
517static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
518 const CXXRecordDecl *Class) {
John McCallb3b50a82010-08-11 23:52:36 +0000519 // Don't do it if the class is invalid.
520 if (Class->isInvalidDecl())
521 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000522
Douglas Gregor4923aa22010-07-02 20:37:36 +0000523 // We need to have a definition for the class.
524 if (!Class->getDefinition() || Class->isDependentContext())
525 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000526
Douglas Gregor4923aa22010-07-02 20:37:36 +0000527 // We can't be in the middle of defining the class.
528 if (const RecordType *RecordTy
529 = Context.getTypeDeclType(Class)->getAs<RecordType>())
530 return !RecordTy->isBeingDefined();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000531
Douglas Gregor4923aa22010-07-02 20:37:36 +0000532 return false;
533}
534
535void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregor22584312010-07-02 23:41:54 +0000536 if (!CanDeclareSpecialMemberFunction(Context, Class))
537 return;
Douglas Gregor18274032010-07-03 00:47:00 +0000538
539 // If the default constructor has not yet been declared, do so now.
Sean Huntcdee3fe2011-05-11 22:34:38 +0000540 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +0000541 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000542
Douglas Gregor22584312010-07-02 23:41:54 +0000543 // If the copy constructor has not yet been declared, do so now.
544 if (!Class->hasDeclaredCopyConstructor())
545 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000546
Douglas Gregora376d102010-07-02 21:50:04 +0000547 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000548 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +0000549 DeclareImplicitCopyAssignment(Class);
550
Douglas Gregor4923aa22010-07-02 20:37:36 +0000551 // If the destructor has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000552 if (!Class->hasDeclaredDestructor())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000553 DeclareImplicitDestructor(Class);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000554}
555
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000556/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregora376d102010-07-02 21:50:04 +0000557/// special member function.
558static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
559 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000560 case DeclarationName::CXXConstructorName:
Douglas Gregora376d102010-07-02 21:50:04 +0000561 case DeclarationName::CXXDestructorName:
562 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000563
Douglas Gregora376d102010-07-02 21:50:04 +0000564 case DeclarationName::CXXOperatorName:
565 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000566
Douglas Gregora376d102010-07-02 21:50:04 +0000567 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000568 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000569 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000570
Douglas Gregora376d102010-07-02 21:50:04 +0000571 return false;
572}
573
574/// \brief If there are any implicit member functions with the given name
575/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000576static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregora376d102010-07-02 21:50:04 +0000577 DeclarationName Name,
578 const DeclContext *DC) {
579 if (!DC)
580 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000581
Douglas Gregora376d102010-07-02 21:50:04 +0000582 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000583 case DeclarationName::CXXConstructorName:
584 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor18274032010-07-03 00:47:00 +0000585 if (Record->getDefinition() &&
586 CanDeclareSpecialMemberFunction(S.Context, Record)) {
Sean Huntcdee3fe2011-05-11 22:34:38 +0000587 if (Record->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +0000588 S.DeclareImplicitDefaultConstructor(
589 const_cast<CXXRecordDecl *>(Record));
590 if (!Record->hasDeclaredCopyConstructor())
591 S.DeclareImplicitCopyConstructor(const_cast<CXXRecordDecl *>(Record));
592 }
Douglas Gregor22584312010-07-02 23:41:54 +0000593 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000594
Douglas Gregora376d102010-07-02 21:50:04 +0000595 case DeclarationName::CXXDestructorName:
596 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
597 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
598 CanDeclareSpecialMemberFunction(S.Context, Record))
599 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregora376d102010-07-02 21:50:04 +0000600 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000601
Douglas Gregora376d102010-07-02 21:50:04 +0000602 case DeclarationName::CXXOperatorName:
603 if (Name.getCXXOverloadedOperator() != OO_Equal)
604 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000605
Douglas Gregora376d102010-07-02 21:50:04 +0000606 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
607 if (Record->getDefinition() && !Record->hasDeclaredCopyAssignment() &&
608 CanDeclareSpecialMemberFunction(S.Context, Record))
609 S.DeclareImplicitCopyAssignment(const_cast<CXXRecordDecl *>(Record));
610 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000611
Douglas Gregora376d102010-07-02 21:50:04 +0000612 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000613 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000614 }
615}
Douglas Gregor4923aa22010-07-02 20:37:36 +0000616
John McCallf36e02d2009-10-09 21:13:30 +0000617// Adds all qualifying matches for a name within a decl context to the
618// given lookup result. Returns true if any matches were found.
Douglas Gregor85910982010-02-12 05:48:04 +0000619static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000620 bool Found = false;
621
Douglas Gregor4923aa22010-07-02 20:37:36 +0000622 // Lazily declare C++ special member functions.
Douglas Gregora376d102010-07-02 21:50:04 +0000623 if (S.getLangOptions().CPlusPlus)
624 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000625
Douglas Gregor4923aa22010-07-02 20:37:36 +0000626 // Perform lookup into this declaration context.
John McCalld7be78a2009-11-10 07:01:13 +0000627 DeclContext::lookup_const_iterator I, E;
Douglas Gregor48026d22010-01-11 18:40:55 +0000628 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall46460a62010-01-20 21:53:11 +0000629 NamedDecl *D = *I;
630 if (R.isAcceptableDecl(D)) {
631 R.addDecl(D);
Douglas Gregor48026d22010-01-11 18:40:55 +0000632 Found = true;
633 }
634 }
John McCallf36e02d2009-10-09 21:13:30 +0000635
Douglas Gregor85910982010-02-12 05:48:04 +0000636 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
637 return true;
638
Douglas Gregor48026d22010-01-11 18:40:55 +0000639 if (R.getLookupName().getNameKind()
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000640 != DeclarationName::CXXConversionFunctionName ||
641 R.getLookupName().getCXXNameType()->isDependentType() ||
642 !isa<CXXRecordDecl>(DC))
643 return Found;
644
645 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000646 // A specialization of a conversion function template is not found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000647 // name lookup. Instead, any conversion function templates visible in the
648 // context of the use are considered. [...]
649 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
650 if (!Record->isDefinition())
651 return Found;
652
653 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000654 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000655 UEnd = Unresolved->end(); U != UEnd; ++U) {
656 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
657 if (!ConvTemplate)
658 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000659
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000660 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000661 // add the conversion function template. When we deduce template
662 // arguments for specializations, we'll end up unifying the return
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000663 // type of the new declaration with the type of the function template.
664 if (R.isForRedeclaration()) {
665 R.addDecl(ConvTemplate);
666 Found = true;
667 continue;
668 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000669
Douglas Gregor48026d22010-01-11 18:40:55 +0000670 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000671 // [...] For each such operator, if argument deduction succeeds
672 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000673 // name lookup.
674 //
675 // When referencing a conversion function for any purpose other than
676 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000677 // result), perform template argument deduction and place the
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000678 // specialization into the result set. We do this to avoid forcing all
679 // callers to perform special deduction for conversion functions.
John McCall2a7fb272010-08-25 05:32:35 +0000680 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000681 FunctionDecl *Specialization = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000682
683 const FunctionProtoType *ConvProto
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000684 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
685 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3f477a12010-01-12 01:17:50 +0000686
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000687 // Compute the type of the function that we would expect the conversion
688 // function to have, if it were to match the name given.
689 // FIXME: Calling convention!
John McCalle23cf432010-12-14 08:05:40 +0000690 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
691 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
Sebastian Redl8b5b4092011-03-06 10:52:04 +0000692 EPI.ExceptionSpecType = EST_None;
John McCalle23cf432010-12-14 08:05:40 +0000693 EPI.NumExceptions = 0;
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000694 QualType ExpectedType
695 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
John McCalle23cf432010-12-14 08:05:40 +0000696 0, 0, EPI);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000697
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000698 // Perform template argument deduction against the type that we would
699 // expect the function to have.
700 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
701 Specialization, Info)
702 == Sema::TDK_Success) {
703 R.addDecl(Specialization);
704 Found = true;
Douglas Gregor48026d22010-01-11 18:40:55 +0000705 }
706 }
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000707
John McCallf36e02d2009-10-09 21:13:30 +0000708 return Found;
709}
710
John McCalld7be78a2009-11-10 07:01:13 +0000711// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000712static bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000713CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregor85910982010-02-12 05:48:04 +0000714 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000715
716 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
717
John McCalld7be78a2009-11-10 07:01:13 +0000718 // Perform direct name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +0000719 bool Found = LookupDirect(S, R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000720
John McCalld7be78a2009-11-10 07:01:13 +0000721 // Perform direct name lookup into the namespaces nominated by the
722 // using directives whose common ancestor is this namespace.
723 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
724 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000725
John McCalld7be78a2009-11-10 07:01:13 +0000726 for (; UI != UEnd; ++UI)
Douglas Gregor85910982010-02-12 05:48:04 +0000727 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000728 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000729
730 R.resolveKind();
731
732 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000733}
734
735static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000736 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000737 return Ctx->isFileContext();
738 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000739}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000740
Douglas Gregor711be1e2010-03-15 14:33:29 +0000741// Find the next outer declaration context from this scope. This
742// routine actually returns the semantic outer context, which may
743// differ from the lexical context (encoded directly in the Scope
744// stack) when we are parsing a member of a class template. In this
745// case, the second element of the pair will be true, to indicate that
746// name lookup should continue searching in this semantic context when
747// it leaves the current template parameter scope.
748static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
749 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
750 DeclContext *Lexical = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000751 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor711be1e2010-03-15 14:33:29 +0000752 OuterS = OuterS->getParent()) {
753 if (OuterS->getEntity()) {
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000754 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor711be1e2010-03-15 14:33:29 +0000755 break;
756 }
757 }
758
759 // C++ [temp.local]p8:
760 // In the definition of a member of a class template that appears
761 // outside of the namespace containing the class template
762 // definition, the name of a template-parameter hides the name of
763 // a member of this namespace.
764 //
765 // Example:
766 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000767 // namespace N {
768 // class C { };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000769 //
770 // template<class T> class B {
771 // void f(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000772 // };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000773 // }
774 //
775 // template<class C> void N::B<C>::f(C) {
776 // C b; // C is the template parameter, not N::C
777 // }
778 //
779 // In this example, the lexical context we return is the
780 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000781 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor711be1e2010-03-15 14:33:29 +0000782 !S->getParent()->isTemplateParamScope())
783 return std::make_pair(Lexical, false);
784
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000785 // Find the outermost template parameter scope.
Douglas Gregor711be1e2010-03-15 14:33:29 +0000786 // For the example, this is the scope for the template parameters of
787 // template<class C>.
788 Scope *OutermostTemplateScope = S->getParent();
789 while (OutermostTemplateScope->getParent() &&
790 OutermostTemplateScope->getParent()->isTemplateParamScope())
791 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000792
Douglas Gregor711be1e2010-03-15 14:33:29 +0000793 // Find the namespace context in which the original scope occurs. In
794 // the example, this is namespace N.
795 DeclContext *Semantic = DC;
796 while (!Semantic->isFileContext())
797 Semantic = Semantic->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000798
Douglas Gregor711be1e2010-03-15 14:33:29 +0000799 // Find the declaration context just outside of the template
800 // parameter scope. This is the context in which the template is
801 // being lexically declaration (a namespace context). In the
802 // example, this is the global scope.
803 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
804 Lexical->Encloses(Semantic))
805 return std::make_pair(Semantic, true);
806
807 return std::make_pair(Lexical, false);
Douglas Gregore942bbe2009-09-10 16:57:35 +0000808}
809
John McCalla24dc2e2009-11-17 02:14:36 +0000810bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCall1d7c5282009-12-18 10:40:03 +0000811 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000812
813 DeclarationName Name = R.getLookupName();
814
Douglas Gregora376d102010-07-02 21:50:04 +0000815 // If this is the name of an implicitly-declared special member function,
816 // go through the scope stack to implicitly declare
817 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
818 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
819 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
820 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
821 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000822
Douglas Gregora376d102010-07-02 21:50:04 +0000823 // Implicitly declare member functions with the name we're looking for, if in
824 // fact we are in a scope where it matters.
825
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000826 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000827 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000828 I = IdResolver.begin(Name),
829 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000830
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000831 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000832 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000833 // ...During unqualified name lookup (3.4.1), the names appear as if
834 // they were declared in the nearest enclosing namespace which contains
835 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000836 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000837 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000838 //
839 // For example:
840 // namespace A { int i; }
841 // void foo() {
842 // int i;
843 // {
844 // using namespace A;
845 // ++i; // finds local 'i', A::i appears at global scope
846 // }
847 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000848 //
Douglas Gregor711be1e2010-03-15 14:33:29 +0000849 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000850 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregord2235f62010-05-20 20:58:56 +0000851 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
852
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000853 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000854 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000855 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000856 if (R.isAcceptableDecl(*I)) {
John McCallf36e02d2009-10-09 21:13:30 +0000857 Found = true;
858 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000859 }
860 }
John McCallf36e02d2009-10-09 21:13:30 +0000861 if (Found) {
862 R.resolveKind();
Douglas Gregord2235f62010-05-20 20:58:56 +0000863 if (S->isClassScope())
864 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
865 R.setNamingClass(Record);
John McCallf36e02d2009-10-09 21:13:30 +0000866 return true;
867 }
868
Douglas Gregor711be1e2010-03-15 14:33:29 +0000869 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
870 S->getParent() && !S->getParent()->isTemplateParamScope()) {
871 // We've just searched the last template parameter scope and
872 // found nothing, so look into the the contexts between the
873 // lexical and semantic declaration contexts returned by
874 // findOuterContext(). This implements the name lookup behavior
875 // of C++ [temp.local]p8.
876 Ctx = OutsideOfTemplateParamDC;
877 OutsideOfTemplateParamDC = 0;
878 }
879
880 if (Ctx) {
881 DeclContext *OuterCtx;
882 bool SearchAfterTemplateScope;
883 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
884 if (SearchAfterTemplateScope)
885 OutsideOfTemplateParamDC = OuterCtx;
886
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000887 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-02-19 16:08:35 +0000888 // We do not directly look into transparent contexts, since
889 // those entities will be found in the nearest enclosing
890 // non-transparent context.
891 if (Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000892 continue;
Douglas Gregor36262b82010-02-19 16:08:35 +0000893
894 // We do not look directly into function or method contexts,
895 // since all of the local variables and parameters of the
896 // function/method are present within the Scope.
897 if (Ctx->isFunctionOrMethod()) {
898 // If we have an Objective-C instance method, look for ivars
899 // in the corresponding interface.
900 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
901 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
902 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
903 ObjCInterfaceDecl *ClassDeclared;
904 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000905 Name.getAsIdentifierInfo(),
Douglas Gregor36262b82010-02-19 16:08:35 +0000906 ClassDeclared)) {
907 if (R.isAcceptableDecl(Ivar)) {
908 R.addDecl(Ivar);
909 R.resolveKind();
910 return true;
911 }
912 }
913 }
914 }
915
916 continue;
917 }
918
Douglas Gregore942bbe2009-09-10 16:57:35 +0000919 // Perform qualified name lookup into this context.
920 // FIXME: In some cases, we know that every name that could be found by
921 // this qualified name lookup will also be on the identifier chain. For
922 // example, inside a class without any base classes, we never need to
923 // perform qualified lookup because all of the members are on top of the
924 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000925 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +0000926 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +0000927 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000928 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000929 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000930
John McCalld7be78a2009-11-10 07:01:13 +0000931 // Stop if we ran out of scopes.
932 // FIXME: This really, really shouldn't be happening.
933 if (!S) return false;
934
Argyrios Kyrtzidis78f59112010-10-29 16:12:50 +0000935 // If we are looking for members, no need to look into global/namespace scope.
936 if (R.getLookupKind() == LookupMemberName)
937 return false;
938
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000939 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000940 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +0000941 //
Mike Stump390b4cc2009-05-16 07:39:55 +0000942 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
943 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000944
John McCalld7be78a2009-11-10 07:01:13 +0000945 UnqualUsingDirectiveSet UDirs;
946 UDirs.visitScopeChain(Initial, S);
947 UDirs.done();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000948
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000949 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000950 // Unqualified name lookup in C++ requires looking into scopes
951 // that aren't strictly lexical, and therefore we walk through the
952 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000953
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000954 for (; S; S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000955 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000956 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000957 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000958 if (R.isAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000959 // We found something. Look for anything else in our scope
960 // with this same name and in an acceptable identifier
961 // namespace, so that we can construct an overload set if we
962 // need to.
John McCallf36e02d2009-10-09 21:13:30 +0000963 Found = true;
964 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000965 }
966 }
967
Douglas Gregor00b4b032010-05-14 04:53:42 +0000968 if (Found && S->isTemplateParamScope()) {
John McCallf36e02d2009-10-09 21:13:30 +0000969 R.resolveKind();
970 return true;
971 }
972
Douglas Gregor00b4b032010-05-14 04:53:42 +0000973 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
974 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
975 S->getParent() && !S->getParent()->isTemplateParamScope()) {
976 // We've just searched the last template parameter scope and
977 // found nothing, so look into the the contexts between the
978 // lexical and semantic declaration contexts returned by
979 // findOuterContext(). This implements the name lookup behavior
980 // of C++ [temp.local]p8.
981 Ctx = OutsideOfTemplateParamDC;
982 OutsideOfTemplateParamDC = 0;
983 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000984
Douglas Gregor00b4b032010-05-14 04:53:42 +0000985 if (Ctx) {
986 DeclContext *OuterCtx;
987 bool SearchAfterTemplateScope;
988 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
989 if (SearchAfterTemplateScope)
990 OutsideOfTemplateParamDC = OuterCtx;
991
992 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
993 // We do not directly look into transparent contexts, since
994 // those entities will be found in the nearest enclosing
995 // non-transparent context.
996 if (Ctx->isTransparentContext())
997 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000998
Douglas Gregor00b4b032010-05-14 04:53:42 +0000999 // If we have a context, and it's not a context stashed in the
1000 // template parameter scope for an out-of-line definition, also
1001 // look into that context.
1002 if (!(Found && S && S->isTemplateParamScope())) {
1003 assert(Ctx->isFileContext() &&
1004 "We should have been looking only at file context here already.");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001005
Douglas Gregor00b4b032010-05-14 04:53:42 +00001006 // Look into context considering using-directives.
1007 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1008 Found = true;
1009 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001010
Douglas Gregor00b4b032010-05-14 04:53:42 +00001011 if (Found) {
1012 R.resolveKind();
1013 return true;
1014 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001015
Douglas Gregor00b4b032010-05-14 04:53:42 +00001016 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1017 return false;
1018 }
1019 }
1020
Douglas Gregor1df0ee92010-02-05 07:07:10 +00001021 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +00001022 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001023 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001024
John McCallf36e02d2009-10-09 21:13:30 +00001025 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001026}
1027
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001028/// @brief Perform unqualified name lookup starting from a given
1029/// scope.
1030///
1031/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1032/// used to find names within the current scope. For example, 'x' in
1033/// @code
1034/// int x;
1035/// int f() {
1036/// return x; // unqualified name look finds 'x' in the global scope
1037/// }
1038/// @endcode
1039///
1040/// Different lookup criteria can find different names. For example, a
1041/// particular scope can have both a struct and a function of the same
1042/// name, and each can be found by certain lookup criteria. For more
1043/// information about lookup criteria, see the documentation for the
1044/// class LookupCriteria.
1045///
1046/// @param S The scope from which unqualified name lookup will
1047/// begin. If the lookup criteria permits, name lookup may also search
1048/// in the parent scopes.
1049///
1050/// @param Name The name of the entity that we are searching for.
1051///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001052/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001053/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001054/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001055///
1056/// @returns The result of name lookup, which includes zero or more
1057/// declarations and possibly additional information used to diagnose
1058/// ambiguities.
John McCalla24dc2e2009-11-17 02:14:36 +00001059bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1060 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +00001061 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001062
John McCalla24dc2e2009-11-17 02:14:36 +00001063 LookupNameKind NameKind = R.getLookupKind();
1064
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001065 if (!getLangOptions().CPlusPlus) {
1066 // Unqualified name lookup in C/Objective-C is purely lexical, so
1067 // search in the declarations attached to the name.
John McCall1d7c5282009-12-18 10:40:03 +00001068 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001069 // Find the nearest non-transparent declaration scope.
1070 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001071 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001072 static_cast<DeclContext *>(S->getEntity())
1073 ->isTransparentContext()))
1074 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001075 }
1076
John McCall1d7c5282009-12-18 10:40:03 +00001077 unsigned IDNS = R.getIdentifierNamespace();
1078
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001079 // Scan up the scope chain looking for a decl that matches this
1080 // identifier that is in the appropriate namespace. This search
1081 // should not take long, as shadowing of names is uncommon, and
1082 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001083 bool LeftStartingScope = false;
1084
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001085 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +00001086 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001087 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001088 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001089 if (NameKind == LookupRedeclarationWithLinkage) {
1090 // Determine whether this (or a previous) declaration is
1091 // out-of-scope.
John McCalld226f652010-08-21 09:40:31 +00001092 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001093 LeftStartingScope = true;
1094
1095 // If we found something outside of our starting scope that
1096 // does not have linkage, skip it.
1097 if (LeftStartingScope && !((*I)->hasLinkage()))
1098 continue;
1099 }
1100
John McCallf36e02d2009-10-09 21:13:30 +00001101 R.addDecl(*I);
1102
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001103 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00001104 // If this declaration has the "overloadable" attribute, we
1105 // might have a set of overloaded functions.
1106
1107 // Figure out what scope the identifier is in.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001108 while (!(S->getFlags() & Scope::DeclScope) ||
John McCalld226f652010-08-21 09:40:31 +00001109 !S->isDeclScope(*I))
Douglas Gregorf9201e02009-02-11 23:02:49 +00001110 S = S->getParent();
1111
1112 // Find the last declaration in this scope (with the same
1113 // name, naturally).
1114 IdentifierResolver::iterator LastI = I;
1115 for (++LastI; LastI != IEnd; ++LastI) {
John McCalld226f652010-08-21 09:40:31 +00001116 if (!S->isDeclScope(*LastI))
Douglas Gregorf9201e02009-02-11 23:02:49 +00001117 break;
John McCallf36e02d2009-10-09 21:13:30 +00001118 R.addDecl(*LastI);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001119 }
Douglas Gregorf9201e02009-02-11 23:02:49 +00001120 }
1121
John McCallf36e02d2009-10-09 21:13:30 +00001122 R.resolveKind();
1123
1124 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +00001125 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001126 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001127 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +00001128 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +00001129 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001130 }
1131
1132 // If we didn't find a use of this identifier, and if the identifier
1133 // corresponds to a compiler builtin, create the decl object for the builtin
1134 // now, injecting it into translation unit scope, and return it.
Axel Naumann42151d52011-04-13 13:19:46 +00001135 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1136 return true;
Douglas Gregor3e41d602009-02-13 23:20:09 +00001137
Axel Naumannf8291a12011-02-24 16:47:47 +00001138 // If we didn't find a use of this identifier, the ExternalSource
1139 // may be able to handle the situation.
1140 // Note: some lookup failures are expected!
1141 // See e.g. R.isForRedeclaration().
1142 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001143}
1144
John McCall6e247262009-10-10 05:48:19 +00001145/// @brief Perform qualified name lookup in the namespaces nominated by
1146/// using directives by the given context.
1147///
1148/// C++98 [namespace.qual]p2:
1149/// Given X::m (where X is a user-declared namespace), or given ::m
1150/// (where X is the global namespace), let S be the set of all
1151/// declarations of m in X and in the transitive closure of all
1152/// namespaces nominated by using-directives in X and its used
1153/// namespaces, except that using-directives are ignored in any
1154/// namespace, including X, directly containing one or more
1155/// declarations of m. No namespace is searched more than once in
1156/// the lookup of a name. If S is the empty set, the program is
1157/// ill-formed. Otherwise, if S has exactly one member, or if the
1158/// context of the reference is a using-declaration
1159/// (namespace.udecl), S is the required set of declarations of
1160/// m. Otherwise if the use of m is not one that allows a unique
1161/// declaration to be chosen from S, the program is ill-formed.
1162/// C++98 [namespace.qual]p5:
1163/// During the lookup of a qualified namespace member name, if the
1164/// lookup finds more than one declaration of the member, and if one
1165/// declaration introduces a class name or enumeration name and the
1166/// other declarations either introduce the same object, the same
1167/// enumerator or a set of functions, the non-type name hides the
1168/// class or enumeration name if and only if the declarations are
1169/// from the same namespace; otherwise (the declarations are from
1170/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +00001171static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +00001172 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +00001173 assert(StartDC->isFileContext() && "start context is not a file context");
1174
1175 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1176 DeclContext::udir_iterator E = StartDC->using_directives_end();
1177
1178 if (I == E) return false;
1179
1180 // We have at least added all these contexts to the queue.
1181 llvm::DenseSet<DeclContext*> Visited;
1182 Visited.insert(StartDC);
1183
1184 // We have not yet looked into these namespaces, much less added
1185 // their "using-children" to the queue.
1186 llvm::SmallVector<NamespaceDecl*, 8> Queue;
1187
1188 // We have already looked into the initial namespace; seed the queue
1189 // with its using-children.
1190 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001191 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6e247262009-10-10 05:48:19 +00001192 if (Visited.insert(ND).second)
1193 Queue.push_back(ND);
1194 }
1195
1196 // The easiest way to implement the restriction in [namespace.qual]p5
1197 // is to check whether any of the individual results found a tag
1198 // and, if so, to declare an ambiguity if the final result is not
1199 // a tag.
1200 bool FoundTag = false;
1201 bool FoundNonTag = false;
1202
John McCall7d384dd2009-11-18 07:57:50 +00001203 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001204
1205 bool Found = false;
1206 while (!Queue.empty()) {
1207 NamespaceDecl *ND = Queue.back();
1208 Queue.pop_back();
1209
1210 // We go through some convolutions here to avoid copying results
1211 // between LookupResults.
1212 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001213 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001214 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001215
1216 if (FoundDirect) {
1217 // First do any local hiding.
1218 DirectR.resolveKind();
1219
1220 // If the local result is a tag, remember that.
1221 if (DirectR.isSingleTagDecl())
1222 FoundTag = true;
1223 else
1224 FoundNonTag = true;
1225
1226 // Append the local results to the total results if necessary.
1227 if (UseLocal) {
1228 R.addAllDecls(LocalR);
1229 LocalR.clear();
1230 }
1231 }
1232
1233 // If we find names in this namespace, ignore its using directives.
1234 if (FoundDirect) {
1235 Found = true;
1236 continue;
1237 }
1238
1239 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1240 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1241 if (Visited.insert(Nom).second)
1242 Queue.push_back(Nom);
1243 }
1244 }
1245
1246 if (Found) {
1247 if (FoundTag && FoundNonTag)
1248 R.setAmbiguousQualifiedTagHiding();
1249 else
1250 R.resolveKind();
1251 }
1252
1253 return Found;
1254}
1255
Douglas Gregor8071e422010-08-15 06:18:01 +00001256/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001257static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor8071e422010-08-15 06:18:01 +00001258 CXXBasePath &Path,
1259 void *Name) {
1260 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001261
Douglas Gregor8071e422010-08-15 06:18:01 +00001262 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1263 Path.Decls = BaseRecord->lookup(N);
1264 return Path.Decls.first != Path.Decls.second;
1265}
1266
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001267/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001268/// static members, nested types, and enumerators.
1269template<typename InputIterator>
1270static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1271 Decl *D = (*First)->getUnderlyingDecl();
1272 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1273 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001274
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001275 if (isa<CXXMethodDecl>(D)) {
1276 // Determine whether all of the methods are static.
1277 bool AllMethodsAreStatic = true;
1278 for(; First != Last; ++First) {
1279 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001280
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001281 if (!isa<CXXMethodDecl>(D)) {
1282 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1283 break;
1284 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001285
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001286 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1287 AllMethodsAreStatic = false;
1288 break;
1289 }
1290 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001291
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001292 if (AllMethodsAreStatic)
1293 return true;
1294 }
1295
1296 return false;
1297}
1298
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001299/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001300///
1301/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1302/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001303/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001304///
1305/// Different lookup criteria can find different names. For example, a
1306/// particular scope can have both a struct and a function of the same
1307/// name, and each can be found by certain lookup criteria. For more
1308/// information about lookup criteria, see the documentation for the
1309/// class LookupCriteria.
1310///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001311/// \param R captures both the lookup criteria and any lookup results found.
1312///
1313/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001314/// search. If the lookup criteria permits, name lookup may also search
1315/// in the parent contexts or (for C++ classes) base classes.
1316///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001317/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001318/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001319///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001320/// \returns true if lookup succeeded, false if it failed.
1321bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1322 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001323 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001324
John McCalla24dc2e2009-11-17 02:14:36 +00001325 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001326 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001327
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001328 // Make sure that the declaration context is complete.
1329 assert((!isa<TagDecl>(LookupCtx) ||
1330 LookupCtx->isDependentContext() ||
1331 cast<TagDecl>(LookupCtx)->isDefinition() ||
1332 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1333 ->isBeingDefined()) &&
1334 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001335
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001336 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001337 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001338 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001339 if (isa<CXXRecordDecl>(LookupCtx))
1340 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001341 return true;
1342 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001343
John McCall6e247262009-10-10 05:48:19 +00001344 // Don't descend into implied contexts for redeclarations.
1345 // C++98 [namespace.qual]p6:
1346 // In a declaration for a namespace member in which the
1347 // declarator-id is a qualified-id, given that the qualified-id
1348 // for the namespace member has the form
1349 // nested-name-specifier unqualified-id
1350 // the unqualified-id shall name a member of the namespace
1351 // designated by the nested-name-specifier.
1352 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001353 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001354 return false;
1355
John McCalla24dc2e2009-11-17 02:14:36 +00001356 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001357 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001358 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001359
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001360 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001361 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001362 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor025291b2010-07-01 00:21:21 +00001363 if (!LookupRec || !LookupRec->getDefinition())
John McCallf36e02d2009-10-09 21:13:30 +00001364 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001365
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001366 // If we're performing qualified name lookup into a dependent class,
1367 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001368 // dependent base classes, then we either have to delay lookup until
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001369 // template instantiation time (at which point all bases will be available)
1370 // or we have to fail.
1371 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1372 LookupRec->hasAnyDependentBases()) {
1373 R.setNotFoundInCurrentInstantiation();
1374 return false;
1375 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001376
Douglas Gregor7176fff2009-01-15 00:26:24 +00001377 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001378 CXXBasePaths Paths;
1379 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001380
1381 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001382 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001383 switch (R.getLookupKind()) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001384 case LookupOrdinaryName:
1385 case LookupMemberName:
1386 case LookupRedeclarationWithLinkage:
1387 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1388 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001389
Douglas Gregora8f32e02009-10-06 17:59:45 +00001390 case LookupTagName:
1391 BaseCallback = &CXXRecordDecl::FindTagMember;
1392 break;
John McCall9f54ad42009-12-10 09:41:52 +00001393
Douglas Gregor8071e422010-08-15 06:18:01 +00001394 case LookupAnyName:
1395 BaseCallback = &LookupAnyMember;
1396 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001397
John McCall9f54ad42009-12-10 09:41:52 +00001398 case LookupUsingDeclName:
1399 // This lookup is for redeclarations only.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001400
Douglas Gregora8f32e02009-10-06 17:59:45 +00001401 case LookupOperatorName:
1402 case LookupNamespaceName:
1403 case LookupObjCProtocolName:
Chris Lattner337e5502011-02-18 01:27:55 +00001404 case LookupLabel:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001405 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001406 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001407
Douglas Gregora8f32e02009-10-06 17:59:45 +00001408 case LookupNestedNameSpecifierName:
1409 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1410 break;
1411 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001412
John McCalla24dc2e2009-11-17 02:14:36 +00001413 if (!LookupRec->lookupInBases(BaseCallback,
1414 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001415 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001416
John McCall92f88312010-01-23 00:46:32 +00001417 R.setNamingClass(LookupRec);
1418
Douglas Gregor7176fff2009-01-15 00:26:24 +00001419 // C++ [class.member.lookup]p2:
1420 // [...] If the resulting set of declarations are not all from
1421 // sub-objects of the same type, or the set has a nonstatic member
1422 // and includes members from distinct sub-objects, there is an
1423 // ambiguity and the program is ill-formed. Otherwise that set is
1424 // the result of the lookup.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001425 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001426 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001427 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001428
Douglas Gregora8f32e02009-10-06 17:59:45 +00001429 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001430 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001431 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001432
John McCall46460a62010-01-20 21:53:11 +00001433 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1434 // across all paths.
1435 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001436
Douglas Gregor7176fff2009-01-15 00:26:24 +00001437 // Determine whether we're looking at a distinct sub-object or not.
1438 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001439 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001440 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1441 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001442 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001443 }
1444
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001445 if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001446 != Context.getCanonicalType(PathElement.Base->getType())) {
1447 // We found members of the given name in two subobjects of
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001448 // different types. If the declaration sets aren't the same, this
1449 // this lookup is ambiguous.
1450 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1451 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1452 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1453 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001454
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001455 while (FirstD != FirstPath->Decls.second &&
1456 CurrentD != Path->Decls.second) {
1457 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1458 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1459 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001460
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001461 ++FirstD;
1462 ++CurrentD;
1463 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001464
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001465 if (FirstD == FirstPath->Decls.second &&
1466 CurrentD == Path->Decls.second)
1467 continue;
1468 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001469
John McCallf36e02d2009-10-09 21:13:30 +00001470 R.setAmbiguousBaseSubobjectTypes(Paths);
1471 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001472 }
1473
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001474 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001475 // We have a different subobject of the same type.
1476
1477 // C++ [class.member.lookup]p5:
1478 // A static member, a nested type or an enumerator defined in
1479 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001480 // has more than one base class subobject of type T.
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001481 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
Douglas Gregor7176fff2009-01-15 00:26:24 +00001482 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001483
Douglas Gregor7176fff2009-01-15 00:26:24 +00001484 // We have found a nonstatic member name in multiple, distinct
1485 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001486 R.setAmbiguousBaseSubobjects(Paths);
1487 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001488 }
1489 }
1490
1491 // Lookup in a base class succeeded; return these results.
1492
John McCallf36e02d2009-10-09 21:13:30 +00001493 DeclContext::lookup_iterator I, E;
John McCall92f88312010-01-23 00:46:32 +00001494 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1495 NamedDecl *D = *I;
1496 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1497 D->getAccess());
1498 R.addDecl(D, AS);
1499 }
John McCallf36e02d2009-10-09 21:13:30 +00001500 R.resolveKind();
1501 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001502}
1503
1504/// @brief Performs name lookup for a name that was parsed in the
1505/// source code, and may contain a C++ scope specifier.
1506///
1507/// This routine is a convenience routine meant to be called from
1508/// contexts that receive a name and an optional C++ scope specifier
1509/// (e.g., "N::M::x"). It will then perform either qualified or
1510/// unqualified name lookup (with LookupQualifiedName or LookupName,
1511/// respectively) on the given name and return those results.
1512///
1513/// @param S The scope from which unqualified name lookup will
1514/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001515///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001516/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001517///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001518/// @param EnteringContext Indicates whether we are going to enter the
1519/// context of the scope-specifier SS (if present).
1520///
John McCallf36e02d2009-10-09 21:13:30 +00001521/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001522bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001523 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001524 if (SS && SS->isInvalid()) {
1525 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001526 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001527 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001528 }
Mike Stump1eb44332009-09-09 15:08:12 +00001529
Douglas Gregor495c35d2009-08-25 22:51:20 +00001530 if (SS && SS->isSet()) {
1531 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001532 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001533 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001534 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001535 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001536
John McCalla24dc2e2009-11-17 02:14:36 +00001537 R.setContextRange(SS->getRange());
1538
1539 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001540 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001541
Douglas Gregor495c35d2009-08-25 22:51:20 +00001542 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001543 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001544 // Name lookup can't find anything in this case.
John McCallf36e02d2009-10-09 21:13:30 +00001545 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001546 }
1547
Mike Stump1eb44332009-09-09 15:08:12 +00001548 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001549 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001550}
1551
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001552
Douglas Gregor7176fff2009-01-15 00:26:24 +00001553/// @brief Produce a diagnostic describing the ambiguity that resulted
1554/// from name lookup.
1555///
1556/// @param Result The ambiguous name lookup result.
Mike Stump1eb44332009-09-09 15:08:12 +00001557///
Douglas Gregor7176fff2009-01-15 00:26:24 +00001558/// @param Name The name of the entity that name lookup was
1559/// searching for.
1560///
1561/// @param NameLoc The location of the name within the source code.
1562///
1563/// @param LookupRange A source range that provides more
1564/// source-location information concerning the lookup itself. For
1565/// example, this range might highlight a nested-name-specifier that
1566/// precedes the name.
1567///
1568/// @returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001569bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001570 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1571
John McCalla24dc2e2009-11-17 02:14:36 +00001572 DeclarationName Name = Result.getLookupName();
1573 SourceLocation NameLoc = Result.getNameLoc();
1574 SourceRange LookupRange = Result.getContextRange();
1575
John McCall6e247262009-10-10 05:48:19 +00001576 switch (Result.getAmbiguityKind()) {
1577 case LookupResult::AmbiguousBaseSubobjects: {
1578 CXXBasePaths *Paths = Result.getBasePaths();
1579 QualType SubobjectType = Paths->front().back().Base->getType();
1580 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1581 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1582 << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001583
John McCall6e247262009-10-10 05:48:19 +00001584 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1585 while (isa<CXXMethodDecl>(*Found) &&
1586 cast<CXXMethodDecl>(*Found)->isStatic())
1587 ++Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001588
John McCall6e247262009-10-10 05:48:19 +00001589 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001590
John McCall6e247262009-10-10 05:48:19 +00001591 return true;
1592 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001593
John McCall6e247262009-10-10 05:48:19 +00001594 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001595 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1596 << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001597
John McCall6e247262009-10-10 05:48:19 +00001598 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001599 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001600 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1601 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001602 Path != PathEnd; ++Path) {
1603 Decl *D = *Path->Decls.first;
1604 if (DeclsPrinted.insert(D).second)
1605 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1606 }
1607
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001608 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001609 }
1610
John McCall6e247262009-10-10 05:48:19 +00001611 case LookupResult::AmbiguousTagHiding: {
1612 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001613
John McCall6e247262009-10-10 05:48:19 +00001614 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1615
1616 LookupResult::iterator DI, DE = Result.end();
1617 for (DI = Result.begin(); DI != DE; ++DI)
1618 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1619 TagDecls.insert(TD);
1620 Diag(TD->getLocation(), diag::note_hidden_tag);
1621 }
1622
1623 for (DI = Result.begin(); DI != DE; ++DI)
1624 if (!isa<TagDecl>(*DI))
1625 Diag((*DI)->getLocation(), diag::note_hiding_object);
1626
1627 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001628 LookupResult::Filter F = Result.makeFilter();
1629 while (F.hasNext()) {
1630 if (TagDecls.count(F.next()))
1631 F.erase();
1632 }
1633 F.done();
John McCall6e247262009-10-10 05:48:19 +00001634
1635 return true;
1636 }
1637
1638 case LookupResult::AmbiguousReference: {
1639 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001640
John McCall6e247262009-10-10 05:48:19 +00001641 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1642 for (; DI != DE; ++DI)
1643 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001644
John McCall6e247262009-10-10 05:48:19 +00001645 return true;
1646 }
1647 }
1648
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001649 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001650 return true;
1651}
Douglas Gregorfa047642009-02-04 00:32:51 +00001652
John McCallc7e04da2010-05-28 18:45:08 +00001653namespace {
1654 struct AssociatedLookup {
1655 AssociatedLookup(Sema &S,
1656 Sema::AssociatedNamespaceSet &Namespaces,
1657 Sema::AssociatedClassSet &Classes)
1658 : S(S), Namespaces(Namespaces), Classes(Classes) {
1659 }
1660
1661 Sema &S;
1662 Sema::AssociatedNamespaceSet &Namespaces;
1663 Sema::AssociatedClassSet &Classes;
1664 };
1665}
1666
Mike Stump1eb44332009-09-09 15:08:12 +00001667static void
John McCallc7e04da2010-05-28 18:45:08 +00001668addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCall6ff07852009-08-07 22:18:02 +00001669
Douglas Gregor54022952010-04-30 07:08:38 +00001670static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1671 DeclContext *Ctx) {
1672 // Add the associated namespace for this class.
1673
1674 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1675 // be a locally scoped record.
1676
Sebastian Redl410c4f22010-08-31 20:53:31 +00001677 // We skip out of inline namespaces. The innermost non-inline namespace
1678 // contains all names of all its nested inline namespaces anyway, so we can
1679 // replace the entire inline namespace tree with its root.
1680 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1681 Ctx->isInlineNamespace())
Douglas Gregor54022952010-04-30 07:08:38 +00001682 Ctx = Ctx->getParent();
1683
John McCall6ff07852009-08-07 22:18:02 +00001684 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001685 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001686}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001687
Mike Stump1eb44332009-09-09 15:08:12 +00001688// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001689// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001690static void
John McCallc7e04da2010-05-28 18:45:08 +00001691addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1692 const TemplateArgument &Arg) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001693 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001694 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001695 switch (Arg.getKind()) {
1696 case TemplateArgument::Null:
1697 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001698
Douglas Gregor69be8d62009-07-08 07:51:57 +00001699 case TemplateArgument::Type:
1700 // [...] the namespaces and classes associated with the types of the
1701 // template arguments provided for template type parameters (excluding
1702 // template template parameters)
John McCallc7e04da2010-05-28 18:45:08 +00001703 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor69be8d62009-07-08 07:51:57 +00001704 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001705
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001706 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001707 case TemplateArgument::TemplateExpansion: {
Mike Stump1eb44332009-09-09 15:08:12 +00001708 // [...] the namespaces in which any template template arguments are
1709 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001710 // template template arguments are defined.
Douglas Gregora7fc9012011-01-05 18:58:31 +00001711 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump1eb44332009-09-09 15:08:12 +00001712 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001713 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001714 DeclContext *Ctx = ClassTemplate->getDeclContext();
1715 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001716 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001717 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001718 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001719 }
1720 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001721 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001722
Douglas Gregor788cd062009-11-11 01:00:40 +00001723 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001724 case TemplateArgument::Integral:
1725 case TemplateArgument::Expression:
Mike Stump1eb44332009-09-09 15:08:12 +00001726 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001727 // associated namespaces. ]
1728 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001729
Douglas Gregor69be8d62009-07-08 07:51:57 +00001730 case TemplateArgument::Pack:
1731 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1732 PEnd = Arg.pack_end();
1733 P != PEnd; ++P)
John McCallc7e04da2010-05-28 18:45:08 +00001734 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001735 break;
1736 }
1737}
1738
Douglas Gregorfa047642009-02-04 00:32:51 +00001739// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001740// argument-dependent lookup with an argument of class type
1741// (C++ [basic.lookup.koenig]p2).
1742static void
John McCallc7e04da2010-05-28 18:45:08 +00001743addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1744 CXXRecordDecl *Class) {
1745
1746 // Just silently ignore anything whose name is __va_list_tag.
1747 if (Class->getDeclName() == Result.S.VAListTagName)
1748 return;
1749
Douglas Gregorfa047642009-02-04 00:32:51 +00001750 // C++ [basic.lookup.koenig]p2:
1751 // [...]
1752 // -- If T is a class type (including unions), its associated
1753 // classes are: the class itself; the class of which it is a
1754 // member, if any; and its direct and indirect base
1755 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001756 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001757
1758 // Add the class of which it is a member, if any.
1759 DeclContext *Ctx = Class->getDeclContext();
1760 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001761 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001762 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001763 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001764
Douglas Gregorfa047642009-02-04 00:32:51 +00001765 // Add the class itself. If we've already seen this class, we don't
1766 // need to visit base classes.
John McCallc7e04da2010-05-28 18:45:08 +00001767 if (!Result.Classes.insert(Class))
Douglas Gregorfa047642009-02-04 00:32:51 +00001768 return;
1769
Mike Stump1eb44332009-09-09 15:08:12 +00001770 // -- If T is a template-id, its associated namespaces and classes are
1771 // the namespace in which the template is defined; for member
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001772 // templates, the member template's class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001773 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001774 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001775 // namespaces in which any template template arguments are defined; and
1776 // the classes in which any member templates used as template template
1777 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001778 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001779 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001780 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1781 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1782 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001783 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001784 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001785 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001786
Douglas Gregor69be8d62009-07-08 07:51:57 +00001787 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1788 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallc7e04da2010-05-28 18:45:08 +00001789 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001790 }
Mike Stump1eb44332009-09-09 15:08:12 +00001791
John McCall86ff3082010-02-04 22:26:26 +00001792 // Only recurse into base classes for complete types.
1793 if (!Class->hasDefinition()) {
1794 // FIXME: we might need to instantiate templates here
1795 return;
1796 }
1797
Douglas Gregorfa047642009-02-04 00:32:51 +00001798 // Add direct and indirect base classes along with their associated
1799 // namespaces.
1800 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1801 Bases.push_back(Class);
1802 while (!Bases.empty()) {
1803 // Pop this class off the stack.
1804 Class = Bases.back();
1805 Bases.pop_back();
1806
1807 // Visit the base classes.
1808 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1809 BaseEnd = Class->bases_end();
1810 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001811 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001812 // In dependent contexts, we do ADL twice, and the first time around,
1813 // the base type might be a dependent TemplateSpecializationType, or a
1814 // TemplateTypeParmType. If that happens, simply ignore it.
1815 // FIXME: If we want to support export, we probably need to add the
1816 // namespace of the template in a TemplateSpecializationType, or even
1817 // the classes and namespaces of known non-dependent arguments.
1818 if (!BaseType)
1819 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001820 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001821 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001822 // Find the associated namespace for this base class.
1823 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallc7e04da2010-05-28 18:45:08 +00001824 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001825
1826 // Make sure we visit the bases of this base class.
1827 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1828 Bases.push_back(BaseDecl);
1829 }
1830 }
1831 }
1832}
1833
1834// \brief Add the associated classes and namespaces for
1835// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001836// (C++ [basic.lookup.koenig]p2).
1837static void
John McCallc7e04da2010-05-28 18:45:08 +00001838addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001839 // C++ [basic.lookup.koenig]p2:
1840 //
1841 // For each argument type T in the function call, there is a set
1842 // of zero or more associated namespaces and a set of zero or more
1843 // associated classes to be considered. The sets of namespaces and
1844 // classes is determined entirely by the types of the function
1845 // arguments (and the namespace of any template template
1846 // argument). Typedef names and using-declarations used to specify
1847 // the types do not contribute to this set. The sets of namespaces
1848 // and classes are determined in the following way:
Douglas Gregorfa047642009-02-04 00:32:51 +00001849
John McCallfa4edcf2010-05-28 06:08:54 +00001850 llvm::SmallVector<const Type *, 16> Queue;
1851 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1852
Douglas Gregorfa047642009-02-04 00:32:51 +00001853 while (true) {
John McCallfa4edcf2010-05-28 06:08:54 +00001854 switch (T->getTypeClass()) {
1855
1856#define TYPE(Class, Base)
1857#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1858#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1859#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1860#define ABSTRACT_TYPE(Class, Base)
1861#include "clang/AST/TypeNodes.def"
1862 // T is canonical. We can also ignore dependent types because
1863 // we don't need to do ADL at the definition point, but if we
1864 // wanted to implement template export (or if we find some other
1865 // use for associated classes and namespaces...) this would be
1866 // wrong.
Douglas Gregorfa047642009-02-04 00:32:51 +00001867 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00001868
John McCallfa4edcf2010-05-28 06:08:54 +00001869 // -- If T is a pointer to U or an array of U, its associated
1870 // namespaces and classes are those associated with U.
1871 case Type::Pointer:
1872 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1873 continue;
1874 case Type::ConstantArray:
1875 case Type::IncompleteArray:
1876 case Type::VariableArray:
1877 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1878 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001879
John McCallfa4edcf2010-05-28 06:08:54 +00001880 // -- If T is a fundamental type, its associated sets of
1881 // namespaces and classes are both empty.
1882 case Type::Builtin:
1883 break;
1884
1885 // -- If T is a class type (including unions), its associated
1886 // classes are: the class itself; the class of which it is a
1887 // member, if any; and its direct and indirect base
1888 // classes. Its associated namespaces are the namespaces in
1889 // which its associated classes are defined.
1890 case Type::Record: {
1891 CXXRecordDecl *Class
1892 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001893 addAssociatedClassesAndNamespaces(Result, Class);
John McCallfa4edcf2010-05-28 06:08:54 +00001894 break;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001895 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00001896
John McCallfa4edcf2010-05-28 06:08:54 +00001897 // -- If T is an enumeration type, its associated namespace is
1898 // the namespace in which it is defined. If it is class
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001899 // member, its associated class is the member's class; else
John McCallfa4edcf2010-05-28 06:08:54 +00001900 // it has no associated class.
1901 case Type::Enum: {
1902 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001903
John McCallfa4edcf2010-05-28 06:08:54 +00001904 DeclContext *Ctx = Enum->getDeclContext();
1905 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001906 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001907
John McCallfa4edcf2010-05-28 06:08:54 +00001908 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001909 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001910
John McCallfa4edcf2010-05-28 06:08:54 +00001911 break;
1912 }
1913
1914 // -- If T is a function type, its associated namespaces and
1915 // classes are those associated with the function parameter
1916 // types and those associated with the return type.
1917 case Type::FunctionProto: {
1918 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1919 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1920 ArgEnd = Proto->arg_type_end();
1921 Arg != ArgEnd; ++Arg)
1922 Queue.push_back(Arg->getTypePtr());
1923 // fallthrough
1924 }
1925 case Type::FunctionNoProto: {
1926 const FunctionType *FnType = cast<FunctionType>(T);
1927 T = FnType->getResultType().getTypePtr();
1928 continue;
1929 }
1930
1931 // -- If T is a pointer to a member function of a class X, its
1932 // associated namespaces and classes are those associated
1933 // with the function parameter types and return type,
1934 // together with those associated with X.
1935 //
1936 // -- If T is a pointer to a data member of class X, its
1937 // associated namespaces and classes are those associated
1938 // with the member type together with those associated with
1939 // X.
1940 case Type::MemberPointer: {
1941 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1942
1943 // Queue up the class type into which this points.
1944 Queue.push_back(MemberPtr->getClass());
1945
1946 // And directly continue with the pointee type.
1947 T = MemberPtr->getPointeeType().getTypePtr();
1948 continue;
1949 }
1950
1951 // As an extension, treat this like a normal pointer.
1952 case Type::BlockPointer:
1953 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1954 continue;
1955
1956 // References aren't covered by the standard, but that's such an
1957 // obvious defect that we cover them anyway.
1958 case Type::LValueReference:
1959 case Type::RValueReference:
1960 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1961 continue;
1962
1963 // These are fundamental types.
1964 case Type::Vector:
1965 case Type::ExtVector:
1966 case Type::Complex:
1967 break;
1968
Douglas Gregorf25760e2011-04-12 01:02:45 +00001969 // If T is an Objective-C object or interface type, or a pointer to an
1970 // object or interface type, the associated namespace is the global
1971 // namespace.
John McCallfa4edcf2010-05-28 06:08:54 +00001972 case Type::ObjCObject:
1973 case Type::ObjCInterface:
1974 case Type::ObjCObjectPointer:
Douglas Gregorf25760e2011-04-12 01:02:45 +00001975 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCallfa4edcf2010-05-28 06:08:54 +00001976 break;
1977 }
1978
1979 if (Queue.empty()) break;
1980 T = Queue.back();
1981 Queue.pop_back();
Douglas Gregorfa047642009-02-04 00:32:51 +00001982 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001983}
1984
1985/// \brief Find the associated classes and namespaces for
1986/// argument-dependent lookup for a call with the given set of
1987/// arguments.
1988///
1989/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00001990/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00001991/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001992void
Douglas Gregorfa047642009-02-04 00:32:51 +00001993Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1994 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001995 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001996 AssociatedNamespaces.clear();
1997 AssociatedClasses.clear();
1998
John McCallc7e04da2010-05-28 18:45:08 +00001999 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
2000
Douglas Gregorfa047642009-02-04 00:32:51 +00002001 // C++ [basic.lookup.koenig]p2:
2002 // For each argument type T in the function call, there is a set
2003 // of zero or more associated namespaces and a set of zero or more
2004 // associated classes to be considered. The sets of namespaces and
2005 // classes is determined entirely by the types of the function
2006 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00002007 // argument).
Douglas Gregorfa047642009-02-04 00:32:51 +00002008 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
2009 Expr *Arg = Args[ArgIdx];
2010
2011 if (Arg->getType() != Context.OverloadTy) {
John McCallc7e04da2010-05-28 18:45:08 +00002012 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002013 continue;
2014 }
2015
2016 // [...] In addition, if the argument is the name or address of a
2017 // set of overloaded functions and/or function templates, its
2018 // associated classes and namespaces are the union of those
2019 // associated with each of the members of the set: the namespace
2020 // in which the function or function template is defined and the
2021 // classes and namespaces associated with its (non-dependent)
2022 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00002023 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00002024 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCall2de56d12010-08-25 11:45:40 +00002025 if (unaryOp->getOpcode() == UO_AddrOf)
John McCallba135432009-11-21 08:51:07 +00002026 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002027
John McCallc7e04da2010-05-28 18:45:08 +00002028 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2029 if (!ULE) continue;
John McCallba135432009-11-21 08:51:07 +00002030
John McCallc7e04da2010-05-28 18:45:08 +00002031 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2032 I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00002033 // Look through any using declarations to find the underlying function.
2034 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002035
Chandler Carruthbd647292009-12-29 06:17:27 +00002036 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2037 if (!FDecl)
2038 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002039
2040 // Add the classes and namespaces associated with the parameter
2041 // types and return type of this function.
John McCallc7e04da2010-05-28 18:45:08 +00002042 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002043 }
2044 }
2045}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002046
2047/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2048/// an acceptable non-member overloaded operator for a call whose
2049/// arguments have types T1 (and, if non-empty, T2). This routine
2050/// implements the check in C++ [over.match.oper]p3b2 concerning
2051/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00002052static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002053IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2054 QualType T1, QualType T2,
2055 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00002056 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2057 return true;
2058
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002059 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2060 return true;
2061
John McCall183700f2009-09-21 23:43:11 +00002062 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002063 if (Proto->getNumArgs() < 1)
2064 return false;
2065
2066 if (T1->isEnumeralType()) {
2067 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002068 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002069 return true;
2070 }
2071
2072 if (Proto->getNumArgs() < 2)
2073 return false;
2074
2075 if (!T2.isNull() && T2->isEnumeralType()) {
2076 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002077 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002078 return true;
2079 }
2080
2081 return false;
2082}
2083
John McCall7d384dd2009-11-18 07:57:50 +00002084NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002085 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00002086 LookupNameKind NameKind,
2087 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002088 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00002089 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00002090 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00002091}
2092
Douglas Gregor6e378de2009-04-23 23:18:26 +00002093/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002094ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002095 SourceLocation IdLoc) {
2096 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2097 LookupObjCProtocolName);
Douglas Gregor6e378de2009-04-23 23:18:26 +00002098 return cast_or_null<ObjCProtocolDecl>(D);
2099}
2100
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002101void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00002102 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00002103 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002104 // C++ [over.match.oper]p3:
2105 // -- The set of non-member candidates is the result of the
2106 // unqualified lookup of operator@ in the context of the
2107 // expression according to the usual rules for name lookup in
2108 // unqualified function calls (3.4.2) except that all member
2109 // functions are ignored. However, if no operand has a class
2110 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00002111 // that have a first parameter of type T1 or "reference to
2112 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002113 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00002114 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002115 // when T2 is an enumeration type, are candidate functions.
2116 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00002117 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2118 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002119
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002120 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2121
John McCallf36e02d2009-10-09 21:13:30 +00002122 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002123 return;
2124
2125 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2126 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002127 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2128 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002129 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002130 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00002131 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002132 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00002133 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00002134 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00002135 // later?
2136 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002137 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00002138 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002139 }
2140}
2141
Sean Huntc39b6bc2011-06-24 02:11:39 +00002142Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Sean Hunt308742c2011-06-04 04:32:43 +00002143 CXXSpecialMember SM,
2144 bool ConstArg,
2145 bool VolatileArg,
2146 bool RValueThis,
2147 bool ConstThis,
2148 bool VolatileThis) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002149 RD = RD->getDefinition();
2150 assert((RD && !RD->isBeingDefined()) &&
Sean Hunt308742c2011-06-04 04:32:43 +00002151 "doing special member lookup into record that isn't fully complete");
2152 if (RValueThis || ConstThis || VolatileThis)
2153 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2154 "constructors and destructors always have unqualified lvalue this");
2155 if (ConstArg || VolatileArg)
2156 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2157 "parameter-less special members can't have qualified arguments");
2158
2159 llvm::FoldingSetNodeID ID;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002160 ID.AddPointer(RD);
Sean Hunt308742c2011-06-04 04:32:43 +00002161 ID.AddInteger(SM);
2162 ID.AddInteger(ConstArg);
2163 ID.AddInteger(VolatileArg);
2164 ID.AddInteger(RValueThis);
2165 ID.AddInteger(ConstThis);
2166 ID.AddInteger(VolatileThis);
2167
2168 void *InsertPoint;
2169 SpecialMemberOverloadResult *Result =
2170 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2171
2172 // This was already cached
2173 if (Result)
2174 return Result;
2175
Sean Hunt30543582011-06-07 00:11:58 +00002176 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2177 Result = new (Result) SpecialMemberOverloadResult(ID);
Sean Hunt308742c2011-06-04 04:32:43 +00002178 SpecialMemberCache.InsertNode(Result, InsertPoint);
2179
2180 if (SM == CXXDestructor) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002181 if (!RD->hasDeclaredDestructor())
2182 DeclareImplicitDestructor(RD);
2183 CXXDestructorDecl *DD = RD->getDestructor();
Sean Hunt308742c2011-06-04 04:32:43 +00002184 assert(DD && "record without a destructor");
2185 Result->setMethod(DD);
2186 Result->setSuccess(DD->isDeleted());
2187 Result->setConstParamMatch(false);
2188 return Result;
2189 }
2190
Sean Huntb320e0c2011-06-10 03:50:41 +00002191 // Prepare for overload resolution. Here we construct a synthetic argument
2192 // if necessary and make sure that implicit functions are declared.
Sean Huntc39b6bc2011-06-24 02:11:39 +00002193 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Sean Huntb320e0c2011-06-10 03:50:41 +00002194 DeclarationName Name;
2195 Expr *Arg = 0;
2196 unsigned NumArgs;
2197
2198 if (SM == CXXDefaultConstructor) {
2199 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2200 NumArgs = 0;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002201 if (RD->needsImplicitDefaultConstructor())
2202 DeclareImplicitDefaultConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002203 } else {
2204 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2205 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002206 if (!RD->hasDeclaredCopyConstructor())
2207 DeclareImplicitCopyConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002208 // TODO: Move constructors
2209 } else {
2210 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002211 if (!RD->hasDeclaredCopyAssignment())
2212 DeclareImplicitCopyAssignment(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002213 // TODO: Move assignment
2214 }
2215
2216 QualType ArgType = CanTy;
2217 if (ConstArg)
2218 ArgType.addConst();
2219 if (VolatileArg)
2220 ArgType.addVolatile();
2221
2222 // This isn't /really/ specified by the standard, but it's implied
2223 // we should be working from an RValue in the case of move to ensure
2224 // that we prefer to bind to rvalue references, and an LValue in the
2225 // case of copy to ensure we don't bind to rvalue references.
2226 // Possibly an XValue is actually correct in the case of move, but
2227 // there is no semantic difference for class types in this restricted
2228 // case.
2229 ExprValueKind VK;
Sean Huntab183df2011-06-22 22:13:13 +00002230 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Sean Huntb320e0c2011-06-10 03:50:41 +00002231 VK = VK_LValue;
2232 else
2233 VK = VK_RValue;
2234
2235 NumArgs = 1;
2236 Arg = new (Context) OpaqueValueExpr(SourceLocation(), ArgType, VK);
2237 }
2238
2239 // Create the object argument
2240 QualType ThisTy = CanTy;
2241 if (ConstThis)
2242 ThisTy.addConst();
2243 if (VolatileThis)
2244 ThisTy.addVolatile();
Sean Hunt4cc12c62011-06-23 00:26:20 +00002245 Expr::Classification Classification =
Sean Huntb320e0c2011-06-10 03:50:41 +00002246 (new (Context) OpaqueValueExpr(SourceLocation(), ThisTy,
2247 RValueThis ? VK_RValue : VK_LValue))->
2248 Classify(Context);
2249
2250 // Now we perform lookup on the name we computed earlier and do overload
2251 // resolution. Lookup is only performed directly into the class since there
2252 // will always be a (possibly implicit) declaration to shadow any others.
2253 OverloadCandidateSet OCS((SourceLocation()));
2254 DeclContext::lookup_iterator I, E;
2255 Result->setConstParamMatch(false);
2256
Sean Huntc39b6bc2011-06-24 02:11:39 +00002257 llvm::tie(I, E) = RD->lookup(Name);
Sean Huntb320e0c2011-06-10 03:50:41 +00002258 assert((I != E) &&
2259 "lookup for a constructor or assignment operator was empty");
2260 for ( ; I != E; ++I) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002261 Decl *Cand = *I;
Sean Hunt4cc12c62011-06-23 00:26:20 +00002262
Sean Huntc39b6bc2011-06-24 02:11:39 +00002263 if (Cand->isInvalidDecl())
Sean Huntb320e0c2011-06-10 03:50:41 +00002264 continue;
2265
Sean Huntc39b6bc2011-06-24 02:11:39 +00002266 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2267 // FIXME: [namespace.udecl]p15 says that we should only consider a
2268 // using declaration here if it does not match a declaration in the
2269 // derived class. We do not implement this correctly in other cases
2270 // either.
2271 Cand = U->getTargetDecl();
2272
2273 if (Cand->isInvalidDecl())
2274 continue;
2275 }
2276
2277 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002278 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Sean Huntc39b6bc2011-06-24 02:11:39 +00002279 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Sean Hunt4cc12c62011-06-23 00:26:20 +00002280 Classification, &Arg, NumArgs, OCS, true);
2281 else
2282 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public), &Arg,
2283 NumArgs, OCS, true);
Sean Huntb320e0c2011-06-10 03:50:41 +00002284
2285 // Here we're looking for a const parameter to speed up creation of
2286 // implicit copy methods.
2287 if ((SM == CXXCopyAssignment && M->isCopyAssignmentOperator()) ||
2288 (SM == CXXCopyConstructor &&
2289 cast<CXXConstructorDecl>(M)->isCopyConstructor())) {
2290 QualType ArgType = M->getType()->getAs<FunctionProtoType>()->getArgType(0);
Sean Hunt661c67a2011-06-21 23:42:56 +00002291 if (!ArgType->isReferenceType() ||
2292 ArgType->getPointeeType().isConstQualified())
Sean Huntb320e0c2011-06-10 03:50:41 +00002293 Result->setConstParamMatch(true);
2294 }
Sean Hunt431a1cb2011-06-22 02:58:46 +00002295 } else if (FunctionTemplateDecl *Tmpl =
Sean Huntc39b6bc2011-06-24 02:11:39 +00002296 dyn_cast<FunctionTemplateDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002297 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2298 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Sean Huntc39b6bc2011-06-24 02:11:39 +00002299 RD, 0, ThisTy, Classification, &Arg, NumArgs,
Sean Hunt4cc12c62011-06-23 00:26:20 +00002300 OCS, true);
2301 else
2302 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
2303 0, &Arg, NumArgs, OCS, true);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002304 } else {
2305 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Sean Huntb320e0c2011-06-10 03:50:41 +00002306 }
2307 }
2308
2309 OverloadCandidateSet::iterator Best;
2310 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2311 case OR_Success:
2312 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2313 Result->setSuccess(true);
2314 break;
2315
2316 case OR_Deleted:
2317 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2318 Result->setSuccess(false);
2319 break;
2320
2321 case OR_Ambiguous:
2322 case OR_No_Viable_Function:
2323 Result->setMethod(0);
2324 Result->setSuccess(false);
2325 break;
2326 }
2327
2328 return Result;
2329}
2330
2331/// \brief Look up the default constructor for the given class.
2332CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Sean Huntc530d172011-06-10 04:44:37 +00002333 SpecialMemberOverloadResult *Result =
Sean Huntb320e0c2011-06-10 03:50:41 +00002334 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2335 false, false);
2336
2337 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Sean Hunt308742c2011-06-04 04:32:43 +00002338}
2339
Sean Hunt661c67a2011-06-21 23:42:56 +00002340/// \brief Look up the copying constructor for the given class.
2341CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
2342 unsigned Quals,
2343 bool *ConstParamMatch) {
Sean Huntc530d172011-06-10 04:44:37 +00002344 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2345 "non-const, non-volatile qualifiers for copy ctor arg");
2346 SpecialMemberOverloadResult *Result =
2347 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2348 Quals & Qualifiers::Volatile, false, false, false);
2349
2350 if (ConstParamMatch)
2351 *ConstParamMatch = Result->hasConstParamMatch();
2352
2353 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2354}
2355
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002356/// \brief Look up the constructors for the given class.
2357DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002358 // If the implicit constructors have not yet been declared, do so now.
Douglas Gregor18274032010-07-03 00:47:00 +00002359 if (CanDeclareSpecialMemberFunction(Context, Class)) {
Sean Huntcdee3fe2011-05-11 22:34:38 +00002360 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002361 DeclareImplicitDefaultConstructor(Class);
2362 if (!Class->hasDeclaredCopyConstructor())
2363 DeclareImplicitCopyConstructor(Class);
2364 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002365
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002366 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2367 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2368 return Class->lookup(Name);
2369}
2370
Sean Hunt661c67a2011-06-21 23:42:56 +00002371/// \brief Look up the copying assignment operator for the given class.
2372CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2373 unsigned Quals, bool RValueThis,
2374 unsigned ThisQuals,
2375 bool *ConstParamMatch) {
2376 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2377 "non-const, non-volatile qualifiers for copy assignment arg");
2378 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2379 "non-const, non-volatile qualifiers for copy assignment this");
2380 SpecialMemberOverloadResult *Result =
2381 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2382 Quals & Qualifiers::Volatile, RValueThis,
2383 ThisQuals & Qualifiers::Const,
2384 ThisQuals & Qualifiers::Volatile);
2385
2386 if (ConstParamMatch)
2387 *ConstParamMatch = Result->hasConstParamMatch();
2388
2389 return Result->getMethod();
2390}
2391
Douglas Gregordb89f282010-07-01 22:47:18 +00002392/// \brief Look for the destructor of the given class.
2393///
Sean Huntc5c9b532011-06-03 21:10:40 +00002394/// During semantic analysis, this routine should be used in lieu of
2395/// CXXRecordDecl::getDestructor().
Douglas Gregordb89f282010-07-01 22:47:18 +00002396///
2397/// \returns The destructor for this class.
2398CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Sean Hunt308742c2011-06-04 04:32:43 +00002399 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2400 false, false, false,
2401 false, false)->getMethod());
Douglas Gregordb89f282010-07-01 22:47:18 +00002402}
2403
John McCall7edb5fd2010-01-26 07:16:45 +00002404void ADLResult::insert(NamedDecl *New) {
2405 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2406
2407 // If we haven't yet seen a decl for this key, or the last decl
2408 // was exactly this one, we're done.
2409 if (Old == 0 || Old == New) {
2410 Old = New;
2411 return;
2412 }
2413
2414 // Otherwise, decide which is a more recent redeclaration.
2415 FunctionDecl *OldFD, *NewFD;
2416 if (isa<FunctionTemplateDecl>(New)) {
2417 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2418 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2419 } else {
2420 OldFD = cast<FunctionDecl>(Old);
2421 NewFD = cast<FunctionDecl>(New);
2422 }
2423
2424 FunctionDecl *Cursor = NewFD;
2425 while (true) {
2426 Cursor = Cursor->getPreviousDeclaration();
2427
2428 // If we got to the end without finding OldFD, OldFD is the newer
2429 // declaration; leave things as they are.
2430 if (!Cursor) return;
2431
2432 // If we do find OldFD, then NewFD is newer.
2433 if (Cursor == OldFD) break;
2434
2435 // Otherwise, keep looking.
2436 }
2437
2438 Old = New;
2439}
2440
Sebastian Redl644be852009-10-23 19:23:15 +00002441void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002442 Expr **Args, unsigned NumArgs,
Richard Smithad762fc2011-04-14 22:09:26 +00002443 ADLResult &Result,
2444 bool StdNamespaceIsAssociated) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002445 // Find all of the associated namespaces and classes based on the
2446 // arguments we have.
2447 AssociatedNamespaceSet AssociatedNamespaces;
2448 AssociatedClassSet AssociatedClasses;
Mike Stump1eb44332009-09-09 15:08:12 +00002449 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCall6ff07852009-08-07 22:18:02 +00002450 AssociatedNamespaces,
2451 AssociatedClasses);
Richard Smithad762fc2011-04-14 22:09:26 +00002452 if (StdNamespaceIsAssociated && StdNamespace)
2453 AssociatedNamespaces.insert(getStdNamespace());
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002454
Sebastian Redl644be852009-10-23 19:23:15 +00002455 QualType T1, T2;
2456 if (Operator) {
2457 T1 = Args[0]->getType();
2458 if (NumArgs >= 2)
2459 T2 = Args[1]->getType();
2460 }
2461
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002462 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002463 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2464 // and let Y be the lookup set produced by argument dependent
2465 // lookup (defined as follows). If X contains [...] then Y is
2466 // empty. Otherwise Y is the set of declarations found in the
2467 // namespaces associated with the argument types as described
2468 // below. The set of declarations found by the lookup of the name
2469 // is the union of X and Y.
2470 //
2471 // Here, we compute Y and add its members to the overloaded
2472 // candidate set.
2473 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002474 NSEnd = AssociatedNamespaces.end();
2475 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002476 // When considering an associated namespace, the lookup is the
2477 // same as the lookup performed when the associated namespace is
2478 // used as a qualifier (3.4.3.2) except that:
2479 //
2480 // -- Any using-directives in the associated namespace are
2481 // ignored.
2482 //
John McCall6ff07852009-08-07 22:18:02 +00002483 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002484 // associated classes are visible within their respective
2485 // namespaces even if they are not visible during an ordinary
2486 // lookup (11.4).
2487 DeclContext::lookup_iterator I, E;
John McCall3f9a8a62009-08-11 06:59:38 +00002488 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall6e266892010-01-26 03:27:55 +00002489 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00002490 // If the only declaration here is an ordinary friend, consider
2491 // it only if it was declared in an associated classes.
2492 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00002493 DeclContext *LexDC = D->getLexicalDeclContext();
2494 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2495 continue;
2496 }
Mike Stump1eb44332009-09-09 15:08:12 +00002497
John McCalla113e722010-01-26 06:04:06 +00002498 if (isa<UsingShadowDecl>(D))
2499 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00002500
John McCalla113e722010-01-26 06:04:06 +00002501 if (isa<FunctionDecl>(D)) {
2502 if (Operator &&
2503 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2504 T1, T2, Context))
2505 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00002506 } else if (!isa<FunctionTemplateDecl>(D))
2507 continue;
2508
2509 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00002510 }
2511 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002512}
Douglas Gregor546be3c2009-12-30 17:04:44 +00002513
2514//----------------------------------------------------------------------------
2515// Search for all visible declarations.
2516//----------------------------------------------------------------------------
2517VisibleDeclConsumer::~VisibleDeclConsumer() { }
2518
2519namespace {
2520
2521class ShadowContextRAII;
2522
2523class VisibleDeclsRecord {
2524public:
2525 /// \brief An entry in the shadow map, which is optimized to store a
2526 /// single declaration (the common case) but can also store a list
2527 /// of declarations.
2528 class ShadowMapEntry {
2529 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002530
Douglas Gregor546be3c2009-12-30 17:04:44 +00002531 /// \brief Contains either the solitary NamedDecl * or a vector
2532 /// of declarations.
2533 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2534
2535 public:
2536 ShadowMapEntry() : DeclOrVector() { }
2537
2538 void Add(NamedDecl *ND);
2539 void Destroy();
2540
2541 // Iteration.
Argyrios Kyrtzidisaef05d72011-02-19 04:02:34 +00002542 typedef NamedDecl * const *iterator;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002543 iterator begin();
2544 iterator end();
2545 };
2546
2547private:
2548 /// \brief A mapping from declaration names to the declarations that have
2549 /// this name within a particular scope.
2550 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2551
2552 /// \brief A list of shadow maps, which is used to model name hiding.
2553 std::list<ShadowMap> ShadowMaps;
2554
2555 /// \brief The declaration contexts we have already visited.
2556 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2557
2558 friend class ShadowContextRAII;
2559
2560public:
2561 /// \brief Determine whether we have already visited this context
2562 /// (and, if not, note that we are going to visit that context now).
2563 bool visitedContext(DeclContext *Ctx) {
2564 return !VisitedContexts.insert(Ctx);
2565 }
2566
Douglas Gregor8071e422010-08-15 06:18:01 +00002567 bool alreadyVisitedContext(DeclContext *Ctx) {
2568 return VisitedContexts.count(Ctx);
2569 }
2570
Douglas Gregor546be3c2009-12-30 17:04:44 +00002571 /// \brief Determine whether the given declaration is hidden in the
2572 /// current scope.
2573 ///
2574 /// \returns the declaration that hides the given declaration, or
2575 /// NULL if no such declaration exists.
2576 NamedDecl *checkHidden(NamedDecl *ND);
2577
2578 /// \brief Add a declaration to the current shadow map.
2579 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2580};
2581
2582/// \brief RAII object that records when we've entered a shadow context.
2583class ShadowContextRAII {
2584 VisibleDeclsRecord &Visible;
2585
2586 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2587
2588public:
2589 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2590 Visible.ShadowMaps.push_back(ShadowMap());
2591 }
2592
2593 ~ShadowContextRAII() {
2594 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2595 EEnd = Visible.ShadowMaps.back().end();
2596 E != EEnd;
2597 ++E)
2598 E->second.Destroy();
2599
2600 Visible.ShadowMaps.pop_back();
2601 }
2602};
2603
2604} // end anonymous namespace
2605
2606void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2607 if (DeclOrVector.isNull()) {
2608 // 0 - > 1 elements: just set the single element information.
2609 DeclOrVector = ND;
2610 return;
2611 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002612
Douglas Gregor546be3c2009-12-30 17:04:44 +00002613 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2614 // 1 -> 2 elements: create the vector of results and push in the
2615 // existing declaration.
2616 DeclVector *Vec = new DeclVector;
2617 Vec->push_back(PrevND);
2618 DeclOrVector = Vec;
2619 }
2620
2621 // Add the new element to the end of the vector.
2622 DeclOrVector.get<DeclVector*>()->push_back(ND);
2623}
2624
2625void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2626 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2627 delete Vec;
2628 DeclOrVector = ((NamedDecl *)0);
2629 }
2630}
2631
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002632VisibleDeclsRecord::ShadowMapEntry::iterator
Douglas Gregor546be3c2009-12-30 17:04:44 +00002633VisibleDeclsRecord::ShadowMapEntry::begin() {
2634 if (DeclOrVector.isNull())
2635 return 0;
2636
Argyrios Kyrtzidisaef05d72011-02-19 04:02:34 +00002637 if (DeclOrVector.is<NamedDecl *>())
2638 return DeclOrVector.getAddrOf<NamedDecl *>();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002639
2640 return DeclOrVector.get<DeclVector *>()->begin();
2641}
2642
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002643VisibleDeclsRecord::ShadowMapEntry::iterator
Douglas Gregor546be3c2009-12-30 17:04:44 +00002644VisibleDeclsRecord::ShadowMapEntry::end() {
2645 if (DeclOrVector.isNull())
2646 return 0;
2647
Chandler Carruth7193b3e2011-05-02 18:54:36 +00002648 if (DeclOrVector.is<NamedDecl *>())
2649 return DeclOrVector.getAddrOf<NamedDecl *>() + 1;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002650
2651 return DeclOrVector.get<DeclVector *>()->end();
2652}
2653
2654NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002655 // Look through using declarations.
2656 ND = ND->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002657
Douglas Gregor546be3c2009-12-30 17:04:44 +00002658 unsigned IDNS = ND->getIdentifierNamespace();
2659 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2660 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2661 SM != SMEnd; ++SM) {
2662 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2663 if (Pos == SM->end())
2664 continue;
2665
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002666 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00002667 IEnd = Pos->second.end();
2668 I != IEnd; ++I) {
2669 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002670 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002671 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor546be3c2009-12-30 17:04:44 +00002672 Decl::IDNS_ObjCProtocol)))
2673 continue;
2674
2675 // Protocols are in distinct namespaces from everything else.
2676 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2677 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2678 (*I)->getIdentifierNamespace() != IDNS)
2679 continue;
2680
Douglas Gregor0cc84042010-01-14 15:47:35 +00002681 // Functions and function templates in the same scope overload
2682 // rather than hide. FIXME: Look for hiding based on function
2683 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002684 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002685 ND->isFunctionOrFunctionTemplate() &&
2686 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002687 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002688
Douglas Gregor546be3c2009-12-30 17:04:44 +00002689 // We've found a declaration that hides this one.
2690 return *I;
2691 }
2692 }
2693
2694 return 0;
2695}
2696
2697static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2698 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002699 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002700 VisibleDeclConsumer &Consumer,
2701 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00002702 if (!Ctx)
2703 return;
2704
Douglas Gregor546be3c2009-12-30 17:04:44 +00002705 // Make sure we don't visit the same context twice.
2706 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2707 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002708
Douglas Gregor4923aa22010-07-02 20:37:36 +00002709 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2710 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2711
Douglas Gregor546be3c2009-12-30 17:04:44 +00002712 // Enumerate all of the results in this context.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002713 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002714 CurCtx = CurCtx->getNextContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002715 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00002716 DEnd = CurCtx->decls_end();
2717 D != DEnd; ++D) {
Douglas Gregor70c23352010-12-09 21:44:02 +00002718 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002719 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002720 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002721 Visited.add(ND);
2722 }
Douglas Gregor70c23352010-12-09 21:44:02 +00002723 } else if (ObjCForwardProtocolDecl *ForwardProto
2724 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
2725 for (ObjCForwardProtocolDecl::protocol_iterator
2726 P = ForwardProto->protocol_begin(),
2727 PEnd = ForwardProto->protocol_end();
2728 P != PEnd;
2729 ++P) {
2730 if (Result.isAcceptableDecl(*P)) {
2731 Consumer.FoundDecl(*P, Visited.checkHidden(*P), InBaseClass);
2732 Visited.add(*P);
2733 }
2734 }
Douglas Gregord98abd82011-02-16 01:39:26 +00002735 } else if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D)) {
2736 for (ObjCClassDecl::iterator I = Class->begin(), IEnd = Class->end();
2737 I != IEnd; ++I) {
2738 ObjCInterfaceDecl *IFace = I->getInterface();
2739 if (Result.isAcceptableDecl(IFace)) {
2740 Consumer.FoundDecl(IFace, Visited.checkHidden(IFace), InBaseClass);
2741 Visited.add(IFace);
2742 }
2743 }
Douglas Gregor70c23352010-12-09 21:44:02 +00002744 }
Douglas Gregord98abd82011-02-16 01:39:26 +00002745
Sebastian Redl410c4f22010-08-31 20:53:31 +00002746 // Visit transparent contexts and inline namespaces inside this context.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002747 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
Sebastian Redl410c4f22010-08-31 20:53:31 +00002748 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Douglas Gregor0cc84042010-01-14 15:47:35 +00002749 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002750 Consumer, Visited);
2751 }
2752 }
2753 }
2754
2755 // Traverse using directives for qualified name lookup.
2756 if (QualifiedNameLookup) {
2757 ShadowContextRAII Shadow(Visited);
2758 DeclContext::udir_iterator I, E;
2759 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002760 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002761 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002762 }
2763 }
2764
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002765 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002766 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00002767 if (!Record->hasDefinition())
2768 return;
2769
Douglas Gregor546be3c2009-12-30 17:04:44 +00002770 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2771 BEnd = Record->bases_end();
2772 B != BEnd; ++B) {
2773 QualType BaseType = B->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002774
Douglas Gregor546be3c2009-12-30 17:04:44 +00002775 // Don't look into dependent bases, because name lookup can't look
2776 // there anyway.
2777 if (BaseType->isDependentType())
2778 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002779
Douglas Gregor546be3c2009-12-30 17:04:44 +00002780 const RecordType *Record = BaseType->getAs<RecordType>();
2781 if (!Record)
2782 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002783
Douglas Gregor546be3c2009-12-30 17:04:44 +00002784 // FIXME: It would be nice to be able to determine whether referencing
2785 // a particular member would be ambiguous. For example, given
2786 //
2787 // struct A { int member; };
2788 // struct B { int member; };
2789 // struct C : A, B { };
2790 //
2791 // void f(C *c) { c->### }
2792 //
2793 // accessing 'member' would result in an ambiguity. However, we
2794 // could be smart enough to qualify the member with the base
2795 // class, e.g.,
2796 //
2797 // c->B::member
2798 //
2799 // or
2800 //
2801 // c->A::member
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002802
Douglas Gregor546be3c2009-12-30 17:04:44 +00002803 // Find results in this base class (and its bases).
2804 ShadowContextRAII Shadow(Visited);
2805 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002806 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002807 }
2808 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002809
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002810 // Traverse the contexts of Objective-C classes.
2811 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2812 // Traverse categories.
2813 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2814 Category; Category = Category->getNextClassCategory()) {
2815 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002816 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002817 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002818 }
2819
2820 // Traverse protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00002821 for (ObjCInterfaceDecl::all_protocol_iterator
2822 I = IFace->all_referenced_protocol_begin(),
2823 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002824 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002825 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002826 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002827 }
2828
2829 // Traverse the superclass.
2830 if (IFace->getSuperClass()) {
2831 ShadowContextRAII Shadow(Visited);
2832 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002833 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002834 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002835
Douglas Gregorc220a182010-04-19 18:02:19 +00002836 // If there is an implementation, traverse it. We do this to find
2837 // synthesized ivars.
2838 if (IFace->getImplementation()) {
2839 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002840 LookupVisibleDecls(IFace->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00002841 QualifiedNameLookup, true, Consumer, Visited);
2842 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002843 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2844 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2845 E = Protocol->protocol_end(); I != E; ++I) {
2846 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002847 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002848 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002849 }
2850 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2851 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2852 E = Category->protocol_end(); I != E; ++I) {
2853 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002854 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002855 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002856 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002857
Douglas Gregorc220a182010-04-19 18:02:19 +00002858 // If there is an implementation, traverse it.
2859 if (Category->getImplementation()) {
2860 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002861 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00002862 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002863 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002864 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002865}
2866
2867static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2868 UnqualUsingDirectiveSet &UDirs,
2869 VisibleDeclConsumer &Consumer,
2870 VisibleDeclsRecord &Visited) {
2871 if (!S)
2872 return;
2873
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002874 if (!S->getEntity() ||
2875 (!S->getParent() &&
Douglas Gregor8071e422010-08-15 06:18:01 +00002876 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor539c5c32010-01-07 00:31:29 +00002877 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2878 // Walk through the declarations in this Scope.
2879 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2880 D != DEnd; ++D) {
John McCalld226f652010-08-21 09:40:31 +00002881 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor539c5c32010-01-07 00:31:29 +00002882 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002883 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002884 Visited.add(ND);
2885 }
2886 }
2887 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002888
Douglas Gregor711be1e2010-03-15 14:33:29 +00002889 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00002890 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00002891 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002892 // Look into this scope's declaration context, along with any of its
2893 // parent lookup contexts (e.g., enclosing classes), up to the point
2894 // where we hit the context stored in the next outer scope.
2895 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00002896 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002897
Douglas Gregordbdf5e72010-03-15 15:26:48 +00002898 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002899 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002900 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2901 if (Method->isInstanceMethod()) {
2902 // For instance methods, look for ivars in the method's interface.
2903 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2904 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregorca45da02010-11-02 20:36:02 +00002905 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002906 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Douglas Gregor62021192010-02-04 23:42:48 +00002907 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002908
Douglas Gregorca45da02010-11-02 20:36:02 +00002909 // Look for properties from which we can synthesize ivars, if
2910 // permitted.
2911 if (Result.getSema().getLangOptions().ObjCNonFragileABI2 &&
2912 IFace->getImplementation() &&
2913 Result.getLookupKind() == Sema::LookupOrdinaryName) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002914 for (ObjCInterfaceDecl::prop_iterator
Douglas Gregorca45da02010-11-02 20:36:02 +00002915 P = IFace->prop_begin(),
2916 PEnd = IFace->prop_end();
2917 P != PEnd; ++P) {
2918 if (Result.getSema().canSynthesizeProvisionalIvar(*P) &&
2919 !IFace->lookupInstanceVariable((*P)->getIdentifier())) {
2920 Consumer.FoundDecl(*P, Visited.checkHidden(*P), false);
2921 Visited.add(*P);
2922 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002923 }
2924 }
Douglas Gregorca45da02010-11-02 20:36:02 +00002925 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002926 }
2927
2928 // We've already performed all of the name lookup that we need
2929 // to for Objective-C methods; the next context will be the
2930 // outer scope.
2931 break;
2932 }
2933
Douglas Gregor546be3c2009-12-30 17:04:44 +00002934 if (Ctx->isFunctionOrMethod())
2935 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002936
2937 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002938 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002939 }
2940 } else if (!S->getParent()) {
2941 // Look into the translation unit scope. We walk through the translation
2942 // unit's declaration context, because the Scope itself won't have all of
2943 // the declarations if we loaded a precompiled header.
2944 // FIXME: We would like the translation unit's Scope object to point to the
2945 // translation unit, so we don't need this special "if" branch. However,
2946 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002947 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002948 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00002949 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002950 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002951 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002952 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002953 }
2954
Douglas Gregor546be3c2009-12-30 17:04:44 +00002955 if (Entity) {
2956 // Lookup visible declarations in any namespaces found by using
2957 // directives.
2958 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2959 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2960 for (; UI != UEnd; ++UI)
2961 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002962 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002963 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002964 }
2965
2966 // Lookup names in the parent scope.
2967 ShadowContextRAII Shadow(Visited);
2968 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2969}
2970
2971void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00002972 VisibleDeclConsumer &Consumer,
2973 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002974 // Determine the set of using directives available during
2975 // unqualified name lookup.
2976 Scope *Initial = S;
2977 UnqualUsingDirectiveSet UDirs;
2978 if (getLangOptions().CPlusPlus) {
2979 // Find the first namespace or translation-unit scope.
2980 while (S && !isNamespaceOrTranslationUnitScope(S))
2981 S = S->getParent();
2982
2983 UDirs.visitScopeChain(Initial, S);
2984 }
2985 UDirs.done();
2986
2987 // Look for visible declarations.
2988 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2989 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00002990 if (!IncludeGlobalScope)
2991 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00002992 ShadowContextRAII Shadow(Visited);
2993 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2994}
2995
2996void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00002997 VisibleDeclConsumer &Consumer,
2998 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002999 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3000 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003001 if (!IncludeGlobalScope)
3002 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003003 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003004 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003005 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003006}
3007
Chris Lattner4ae493c2011-02-18 02:08:43 +00003008/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara67843042011-03-05 18:21:20 +00003009/// If GnuLabelLoc is a valid source location, then this is a definition
3010/// of an __label__ label name, otherwise it is a normal label definition
3011/// or use.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003012LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara67843042011-03-05 18:21:20 +00003013 SourceLocation GnuLabelLoc) {
Chris Lattner337e5502011-02-18 01:27:55 +00003014 // Do a lookup to see if we have a label with this name already.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003015 NamedDecl *Res = 0;
Abramo Bagnara67843042011-03-05 18:21:20 +00003016
3017 if (GnuLabelLoc.isValid()) {
3018 // Local label definitions always shadow existing labels.
3019 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3020 Scope *S = CurScope;
3021 PushOnScopeChains(Res, S, true);
3022 return cast<LabelDecl>(Res);
3023 }
3024
3025 // Not a GNU local label.
3026 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3027 // If we found a label, check to see if it is in the same context as us.
3028 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattner337e5502011-02-18 01:27:55 +00003029 if (Res && Res->getDeclContext() != CurContext)
3030 Res = 0;
Chris Lattner337e5502011-02-18 01:27:55 +00003031 if (Res == 0) {
3032 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara67843042011-03-05 18:21:20 +00003033 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3034 Scope *S = CurScope->getFnParent();
Chris Lattnerfebb5b82011-02-18 21:16:39 +00003035 assert(S && "Not in a function?");
3036 PushOnScopeChains(Res, S, true);
Chris Lattner337e5502011-02-18 01:27:55 +00003037 }
Chris Lattner337e5502011-02-18 01:27:55 +00003038 return cast<LabelDecl>(Res);
3039}
3040
3041//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003042// Typo correction
Chris Lattner337e5502011-02-18 01:27:55 +00003043//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003044
3045namespace {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003046
3047typedef llvm::StringMap<TypoCorrection, llvm::BumpPtrAllocator> TypoResultsMap;
3048typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
3049
3050static const unsigned MaxTypoDistanceResultSets = 5;
3051
Douglas Gregor546be3c2009-12-30 17:04:44 +00003052class TypoCorrectionConsumer : public VisibleDeclConsumer {
3053 /// \brief The name written that is a typo in the source.
3054 llvm::StringRef Typo;
3055
3056 /// \brief The results found that have the smallest edit distance
3057 /// found (so far) with the typo name.
Douglas Gregore24b5752010-10-14 20:34:08 +00003058 ///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003059 /// The pointer value being set to the current DeclContext indicates
3060 /// whether there is a keyword with this name.
3061 TypoEditDistanceMap BestResults;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003062
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003063 /// \brief The worst of the best N edit distances found so far.
3064 unsigned MaxEditDistance;
3065
3066 Sema &SemaRef;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003067
Douglas Gregor546be3c2009-12-30 17:04:44 +00003068public:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003069 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003070 : Typo(Typo->getName()),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003071 MaxEditDistance((std::numeric_limits<unsigned>::max)()),
3072 SemaRef(SemaRef) { }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003073
Douglas Gregor0cc84042010-01-14 15:47:35 +00003074 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregor95f42922010-10-14 22:11:03 +00003075 void FoundName(llvm::StringRef Name);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003076 void addKeywordResult(llvm::StringRef Keyword);
3077 void addName(llvm::StringRef Name, NamedDecl *ND, unsigned Distance,
3078 NestedNameSpecifier *NNS=NULL);
3079 void addCorrection(TypoCorrection Correction);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003080
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003081 typedef TypoResultsMap::iterator result_iterator;
3082 typedef TypoEditDistanceMap::iterator distance_iterator;
3083 distance_iterator begin() { return BestResults.begin(); }
3084 distance_iterator end() { return BestResults.end(); }
3085 void erase(distance_iterator I) { BestResults.erase(I); }
Douglas Gregore24b5752010-10-14 20:34:08 +00003086 unsigned size() const { return BestResults.size(); }
3087 bool empty() const { return BestResults.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003088
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003089 TypoCorrection &operator[](llvm::StringRef Name) {
3090 return BestResults.begin()->second[Name];
Douglas Gregor7b824e82010-10-15 13:35:25 +00003091 }
3092
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003093 unsigned getMaxEditDistance() const {
3094 return MaxEditDistance;
3095 }
3096
3097 unsigned getBestEditDistance() {
3098 return (BestResults.empty()) ? MaxEditDistance : BestResults.begin()->first;
3099 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003100};
3101
3102}
3103
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003104void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003105 bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003106 // Don't consider hidden names for typo correction.
3107 if (Hiding)
3108 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003109
Douglas Gregor546be3c2009-12-30 17:04:44 +00003110 // Only consider entities with identifiers for names, ignoring
3111 // special names (constructors, overloaded operators, selectors,
3112 // etc.).
3113 IdentifierInfo *Name = ND->getIdentifier();
3114 if (!Name)
3115 return;
3116
Douglas Gregor95f42922010-10-14 22:11:03 +00003117 FoundName(Name->getName());
3118}
3119
3120void TypoCorrectionConsumer::FoundName(llvm::StringRef Name) {
Douglas Gregor362a8f22010-10-19 19:39:10 +00003121 // Use a simple length-based heuristic to determine the minimum possible
3122 // edit distance. If the minimum isn't good enough, bail out early.
3123 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003124 if (MinED > MaxEditDistance || (MinED && Typo.size() / MinED < 3))
Douglas Gregor362a8f22010-10-19 19:39:10 +00003125 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003126
Douglas Gregora1194772010-10-19 22:14:33 +00003127 // Compute an upper bound on the allowable edit distance, so that the
3128 // edit-distance algorithm can short-circuit.
Jay Foadf1cc1d02011-04-23 09:06:00 +00003129 unsigned UpperBound =
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003130 std::min(unsigned((Typo.size() + 2) / 3), MaxEditDistance);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003131
Douglas Gregor546be3c2009-12-30 17:04:44 +00003132 // Compute the edit distance between the typo and the name of this
3133 // entity. If this edit distance is not worse than the best edit
3134 // distance we've seen so far, add it to the list of results.
Douglas Gregora1194772010-10-19 22:14:33 +00003135 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003136
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003137 if (ED > MaxEditDistance) {
Douglas Gregore24b5752010-10-14 20:34:08 +00003138 // This result is worse than the best results we've seen so far;
3139 // ignore it.
3140 return;
3141 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003142
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003143 addName(Name, NULL, ED);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003144}
3145
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003146void TypoCorrectionConsumer::addKeywordResult(llvm::StringRef Keyword) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00003147 // Compute the edit distance between the typo and this keyword.
3148 // If this edit distance is not worse than the best edit
3149 // distance we've seen so far, add it to the list of results.
3150 unsigned ED = Typo.edit_distance(Keyword);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003151 if (ED > MaxEditDistance) {
Douglas Gregore24b5752010-10-14 20:34:08 +00003152 // This result is worse than the best results we've seen so far;
3153 // ignore it.
3154 return;
3155 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003156
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003157 addName(Keyword, TypoCorrection::KeywordDecl(), ED);
3158}
3159
3160void TypoCorrectionConsumer::addName(llvm::StringRef Name,
3161 NamedDecl *ND,
3162 unsigned Distance,
3163 NestedNameSpecifier *NNS) {
3164 addCorrection(TypoCorrection(&SemaRef.Context.Idents.get(Name),
3165 ND, NNS, Distance));
3166}
3167
3168void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
3169 llvm::StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
3170 BestResults[Correction.getEditDistance()][Name] = Correction;
3171
3172 while (BestResults.size() > MaxTypoDistanceResultSets) {
3173 BestResults.erase(--BestResults.end());
3174 }
3175}
3176
3177namespace {
3178
3179class SpecifierInfo {
3180 public:
3181 DeclContext* DeclCtx;
3182 NestedNameSpecifier* NameSpecifier;
3183 unsigned EditDistance;
3184
3185 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3186 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3187};
3188
3189typedef llvm::SmallVector<DeclContext*, 4> DeclContextList;
3190typedef llvm::SmallVector<SpecifierInfo, 16> SpecifierInfoList;
3191
3192class NamespaceSpecifierSet {
3193 ASTContext &Context;
3194 DeclContextList CurContextChain;
3195 bool isSorted;
3196
3197 SpecifierInfoList Specifiers;
3198 llvm::SmallSetVector<unsigned, 4> Distances;
3199 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3200
3201 /// \brief Helper for building the list of DeclContexts between the current
3202 /// context and the top of the translation unit
3203 static DeclContextList BuildContextChain(DeclContext *Start);
3204
3205 void SortNamespaces();
3206
3207 public:
3208 explicit NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext)
3209 : Context(Context), CurContextChain(BuildContextChain(CurContext)) {}
3210
3211 /// \brief Add the namespace to the set, computing the corresponding
3212 /// NestedNameSpecifier and its distance in the process.
3213 void AddNamespace(NamespaceDecl *ND);
3214
3215 typedef SpecifierInfoList::iterator iterator;
3216 iterator begin() {
3217 if (!isSorted) SortNamespaces();
3218 return Specifiers.begin();
3219 }
3220 iterator end() { return Specifiers.end(); }
3221};
3222
3223}
3224
3225DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
3226 DeclContextList Chain;
3227 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3228 DC = DC->getLookupParent()) {
3229 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3230 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3231 !(ND && ND->isAnonymousNamespace()))
3232 Chain.push_back(DC->getPrimaryContext());
3233 }
3234 return Chain;
3235}
3236
3237void NamespaceSpecifierSet::SortNamespaces() {
3238 llvm::SmallVector<unsigned, 4> sortedDistances;
3239 sortedDistances.append(Distances.begin(), Distances.end());
3240
3241 if (sortedDistances.size() > 1)
3242 std::sort(sortedDistances.begin(), sortedDistances.end());
3243
3244 Specifiers.clear();
3245 for (llvm::SmallVector<unsigned, 4>::iterator DI = sortedDistances.begin(),
3246 DIEnd = sortedDistances.end();
3247 DI != DIEnd; ++DI) {
3248 SpecifierInfoList &SpecList = DistanceMap[*DI];
3249 Specifiers.append(SpecList.begin(), SpecList.end());
3250 }
3251
3252 isSorted = true;
3253}
3254
3255void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
3256 DeclContext *Ctx = dyn_cast<DeclContext>(ND);
3257 NestedNameSpecifier *NNS = NULL;
3258 unsigned NumSpecifiers = 0;
3259 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
3260
3261 // Eliminate common elements from the two DeclContext chains
3262 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3263 CEnd = CurContextChain.rend();
3264 C != CEnd && NamespaceDeclChain.back() == *C; ++C) {
3265 NamespaceDeclChain.pop_back();
3266 }
3267
3268 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3269 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3270 CEnd = NamespaceDeclChain.rend();
3271 C != CEnd; ++C) {
3272 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3273 if (ND) {
3274 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3275 ++NumSpecifiers;
3276 }
3277 }
3278
3279 isSorted = false;
3280 Distances.insert(NumSpecifiers);
3281 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
Douglas Gregoraaf87162010-04-14 20:04:41 +00003282}
3283
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003284/// \brief Perform name lookup for a possible result for typo correction.
3285static void LookupPotentialTypoResult(Sema &SemaRef,
3286 LookupResult &Res,
3287 IdentifierInfo *Name,
3288 Scope *S, CXXScopeSpec *SS,
3289 DeclContext *MemberContext,
3290 bool EnteringContext,
3291 Sema::CorrectTypoContext CTC) {
3292 Res.suppressDiagnostics();
3293 Res.clear();
3294 Res.setLookupName(Name);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003295 if (MemberContext) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003296 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
3297 if (CTC == Sema::CTC_ObjCIvarLookup) {
3298 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3299 Res.addDecl(Ivar);
3300 Res.resolveKind();
3301 return;
3302 }
3303 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003304
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003305 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3306 Res.addDecl(Prop);
3307 Res.resolveKind();
3308 return;
3309 }
3310 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003311
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003312 SemaRef.LookupQualifiedName(Res, MemberContext);
3313 return;
3314 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003315
3316 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003317 EnteringContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003318
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003319 // Fake ivar lookup; this should really be part of
3320 // LookupParsedName.
3321 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3322 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003323 (Res.empty() ||
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003324 (Res.isSingleResult() &&
3325 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003326 if (ObjCIvarDecl *IV
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003327 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3328 Res.addDecl(IV);
3329 Res.resolveKind();
3330 }
3331 }
3332 }
3333}
3334
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003335/// \brief Add keywords to the consumer as possible typo corrections.
3336static void AddKeywordsToConsumer(Sema &SemaRef,
3337 TypoCorrectionConsumer &Consumer,
3338 Scope *S, Sema::CorrectTypoContext CTC) {
3339 // Add context-dependent keywords.
3340 bool WantTypeSpecifiers = false;
3341 bool WantExpressionKeywords = false;
3342 bool WantCXXNamedCasts = false;
3343 bool WantRemainingKeywords = false;
3344 switch (CTC) {
3345 case Sema::CTC_Unknown:
3346 WantTypeSpecifiers = true;
3347 WantExpressionKeywords = true;
3348 WantCXXNamedCasts = true;
3349 WantRemainingKeywords = true;
3350
3351 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
3352 if (Method->getClassInterface() &&
3353 Method->getClassInterface()->getSuperClass())
3354 Consumer.addKeywordResult("super");
3355
3356 break;
3357
3358 case Sema::CTC_NoKeywords:
3359 break;
3360
3361 case Sema::CTC_Type:
3362 WantTypeSpecifiers = true;
3363 break;
3364
3365 case Sema::CTC_ObjCMessageReceiver:
3366 Consumer.addKeywordResult("super");
3367 // Fall through to handle message receivers like expressions.
3368
3369 case Sema::CTC_Expression:
3370 if (SemaRef.getLangOptions().CPlusPlus)
3371 WantTypeSpecifiers = true;
3372 WantExpressionKeywords = true;
3373 // Fall through to get C++ named casts.
3374
3375 case Sema::CTC_CXXCasts:
3376 WantCXXNamedCasts = true;
3377 break;
3378
3379 case Sema::CTC_ObjCPropertyLookup:
3380 // FIXME: Add "isa"?
3381 break;
3382
3383 case Sema::CTC_MemberLookup:
3384 if (SemaRef.getLangOptions().CPlusPlus)
3385 Consumer.addKeywordResult("template");
3386 break;
3387
3388 case Sema::CTC_ObjCIvarLookup:
3389 break;
3390 }
3391
3392 if (WantTypeSpecifiers) {
3393 // Add type-specifier keywords to the set of results.
3394 const char *CTypeSpecs[] = {
3395 "char", "const", "double", "enum", "float", "int", "long", "short",
3396 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
3397 "_Complex", "_Imaginary",
3398 // storage-specifiers as well
3399 "extern", "inline", "static", "typedef"
3400 };
3401
3402 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3403 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3404 Consumer.addKeywordResult(CTypeSpecs[I]);
3405
3406 if (SemaRef.getLangOptions().C99)
3407 Consumer.addKeywordResult("restrict");
3408 if (SemaRef.getLangOptions().Bool || SemaRef.getLangOptions().CPlusPlus)
3409 Consumer.addKeywordResult("bool");
3410
3411 if (SemaRef.getLangOptions().CPlusPlus) {
3412 Consumer.addKeywordResult("class");
3413 Consumer.addKeywordResult("typename");
3414 Consumer.addKeywordResult("wchar_t");
3415
3416 if (SemaRef.getLangOptions().CPlusPlus0x) {
3417 Consumer.addKeywordResult("char16_t");
3418 Consumer.addKeywordResult("char32_t");
3419 Consumer.addKeywordResult("constexpr");
3420 Consumer.addKeywordResult("decltype");
3421 Consumer.addKeywordResult("thread_local");
3422 }
3423 }
3424
3425 if (SemaRef.getLangOptions().GNUMode)
3426 Consumer.addKeywordResult("typeof");
3427 }
3428
3429 if (WantCXXNamedCasts && SemaRef.getLangOptions().CPlusPlus) {
3430 Consumer.addKeywordResult("const_cast");
3431 Consumer.addKeywordResult("dynamic_cast");
3432 Consumer.addKeywordResult("reinterpret_cast");
3433 Consumer.addKeywordResult("static_cast");
3434 }
3435
3436 if (WantExpressionKeywords) {
3437 Consumer.addKeywordResult("sizeof");
3438 if (SemaRef.getLangOptions().Bool || SemaRef.getLangOptions().CPlusPlus) {
3439 Consumer.addKeywordResult("false");
3440 Consumer.addKeywordResult("true");
3441 }
3442
3443 if (SemaRef.getLangOptions().CPlusPlus) {
3444 const char *CXXExprs[] = {
3445 "delete", "new", "operator", "throw", "typeid"
3446 };
3447 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3448 for (unsigned I = 0; I != NumCXXExprs; ++I)
3449 Consumer.addKeywordResult(CXXExprs[I]);
3450
3451 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3452 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3453 Consumer.addKeywordResult("this");
3454
3455 if (SemaRef.getLangOptions().CPlusPlus0x) {
3456 Consumer.addKeywordResult("alignof");
3457 Consumer.addKeywordResult("nullptr");
3458 }
3459 }
3460 }
3461
3462 if (WantRemainingKeywords) {
3463 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3464 // Statements.
3465 const char *CStmts[] = {
3466 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3467 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3468 for (unsigned I = 0; I != NumCStmts; ++I)
3469 Consumer.addKeywordResult(CStmts[I]);
3470
3471 if (SemaRef.getLangOptions().CPlusPlus) {
3472 Consumer.addKeywordResult("catch");
3473 Consumer.addKeywordResult("try");
3474 }
3475
3476 if (S && S->getBreakParent())
3477 Consumer.addKeywordResult("break");
3478
3479 if (S && S->getContinueParent())
3480 Consumer.addKeywordResult("continue");
3481
3482 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3483 Consumer.addKeywordResult("case");
3484 Consumer.addKeywordResult("default");
3485 }
3486 } else {
3487 if (SemaRef.getLangOptions().CPlusPlus) {
3488 Consumer.addKeywordResult("namespace");
3489 Consumer.addKeywordResult("template");
3490 }
3491
3492 if (S && S->isClassScope()) {
3493 Consumer.addKeywordResult("explicit");
3494 Consumer.addKeywordResult("friend");
3495 Consumer.addKeywordResult("mutable");
3496 Consumer.addKeywordResult("private");
3497 Consumer.addKeywordResult("protected");
3498 Consumer.addKeywordResult("public");
3499 Consumer.addKeywordResult("virtual");
3500 }
3501 }
3502
3503 if (SemaRef.getLangOptions().CPlusPlus) {
3504 Consumer.addKeywordResult("using");
3505
3506 if (SemaRef.getLangOptions().CPlusPlus0x)
3507 Consumer.addKeywordResult("static_assert");
3508 }
3509 }
3510}
3511
Douglas Gregor546be3c2009-12-30 17:04:44 +00003512/// \brief Try to "correct" a typo in the source code by finding
3513/// visible declarations whose names are similar to the name that was
3514/// present in the source code.
3515///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003516/// \param TypoName the \c DeclarationNameInfo structure that contains
3517/// the name that was present in the source code along with its location.
3518///
3519/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003520///
3521/// \param S the scope in which name lookup occurs.
3522///
3523/// \param SS the nested-name-specifier that precedes the name we're
3524/// looking for, if present.
3525///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003526/// \param MemberContext if non-NULL, the context in which to look for
3527/// a member access expression.
3528///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003529/// \param EnteringContext whether we're entering the context described by
Douglas Gregorbb092ba2009-12-31 05:20:13 +00003530/// the nested-name-specifier SS.
3531///
Douglas Gregoraaf87162010-04-14 20:04:41 +00003532/// \param CTC The context in which typo correction occurs, which impacts the
3533/// set of keywords permitted.
3534///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003535/// \param OPT when non-NULL, the search for visible declarations will
3536/// also walk the protocols in the qualified interfaces of \p OPT.
3537///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003538/// \returns a \c TypoCorrection containing the corrected name if the typo
3539/// along with information such as the \c NamedDecl where the corrected name
3540/// was declared, and any additional \c NestedNameSpecifier needed to access
3541/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3542TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3543 Sema::LookupNameKind LookupKind,
3544 Scope *S, CXXScopeSpec *SS,
3545 DeclContext *MemberContext,
3546 bool EnteringContext,
3547 CorrectTypoContext CTC,
3548 const ObjCObjectPointerType *OPT) {
Douglas Gregora0068fc2010-07-09 17:35:33 +00003549 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003550 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003551
Douglas Gregor546be3c2009-12-30 17:04:44 +00003552 // We only attempt to correct typos for identifiers.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003553 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003554 if (!Typo)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003555 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003556
3557 // If the scope specifier itself was invalid, don't try to correct
3558 // typos.
3559 if (SS && SS->isInvalid())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003560 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003561
3562 // Never try to correct typos during template deduction or
3563 // instantiation.
3564 if (!ActiveTemplateInstantiations.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003565 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003566
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003567 NamespaceSpecifierSet Namespaces(Context, CurContext);
3568
3569 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003570
Douglas Gregoraaf87162010-04-14 20:04:41 +00003571 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003572 bool IsUnqualifiedLookup = false;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003573 if (MemberContext) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003574 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003575
3576 // Look in qualified interfaces.
3577 if (OPT) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003578 for (ObjCObjectPointerType::qual_iterator
3579 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003580 I != E; ++I)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003581 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003582 }
3583 } else if (SS && SS->isSet()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003584 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
3585 if (!DC)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003586 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003587
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003588 // Provide a stop gap for files that are just seriously broken. Trying
3589 // to correct all typos can turn into a HUGE performance penalty, causing
3590 // some files to take minutes to get rejected by the parser.
3591 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003592 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003593 ++TyposCorrected;
3594
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003595 LookupVisibleDecls(DC, LookupKind, Consumer);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003596 } else {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003597 IsUnqualifiedLookup = true;
3598 UnqualifiedTyposCorrectedMap::iterator Cached
3599 = UnqualifiedTyposCorrected.find(Typo);
3600 if (Cached == UnqualifiedTyposCorrected.end()) {
3601 // Provide a stop gap for files that are just seriously broken. Trying
3602 // to correct all typos can turn into a HUGE performance penalty, causing
3603 // some files to take minutes to get rejected by the parser.
3604 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003605 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003606
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003607 // For unqualified lookup, look through all of the names that we have
3608 // seen in this translation unit.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003609 for (IdentifierTable::iterator I = Context.Idents.begin(),
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003610 IEnd = Context.Idents.end();
3611 I != IEnd; ++I)
3612 Consumer.FoundName(I->getKey());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003613
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003614 // Walk through identifiers in external identifier sources.
3615 if (IdentifierInfoLookup *External
Douglas Gregor95f42922010-10-14 22:11:03 +00003616 = Context.Idents.getExternalIdentifierLookup()) {
Ted Kremenek7a054b12010-11-07 06:11:33 +00003617 llvm::OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003618 do {
3619 llvm::StringRef Name = Iter->Next();
3620 if (Name.empty())
3621 break;
Douglas Gregor95f42922010-10-14 22:11:03 +00003622
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003623 Consumer.FoundName(Name);
3624 } while (true);
3625 }
3626 } else {
3627 // Use the cached value, unless it's a keyword. In the keyword case, we'll
3628 // end up adding the keyword below.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003629 if (!Cached->second)
3630 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003631
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003632 if (!Cached->second.isKeyword())
3633 Consumer.addCorrection(Cached->second);
Douglas Gregor95f42922010-10-14 22:11:03 +00003634 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003635 }
3636
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003637 AddKeywordsToConsumer(*this, Consumer, S, CTC);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003638
Douglas Gregoraaf87162010-04-14 20:04:41 +00003639 // If we haven't found anything, we're done.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003640 if (Consumer.empty()) {
3641 // If this was an unqualified lookup, note that no correction was found.
3642 if (IsUnqualifiedLookup)
3643 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003644
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003645 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003646 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003647
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003648 // Make sure that the user typed at least 3 characters for each correction
Douglas Gregore24b5752010-10-14 20:34:08 +00003649 // made. Otherwise, we don't even both looking at the results.
3650 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003651 if (ED > 0 && Typo->getName().size() / ED < 3) {
3652 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregor157a3ff2010-10-27 14:20:34 +00003653 if (IsUnqualifiedLookup)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003654 (void)UnqualifiedTyposCorrected[Typo];
3655
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003656 return TypoCorrection();
3657 }
3658
3659 // Build the NestedNameSpecifiers for the KnownNamespaces
3660 if (getLangOptions().CPlusPlus) {
3661 // Load any externally-known namespaces.
3662 if (ExternalSource && !LoadedExternalKnownNamespaces) {
3663 llvm::SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
3664 LoadedExternalKnownNamespaces = true;
3665 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
3666 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
3667 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
3668 }
3669
3670 for (llvm::DenseMap<NamespaceDecl*, bool>::iterator
3671 KNI = KnownNamespaces.begin(),
3672 KNIEnd = KnownNamespaces.end();
3673 KNI != KNIEnd; ++KNI)
3674 Namespaces.AddNamespace(KNI->first);
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003675 }
Douglas Gregore24b5752010-10-14 20:34:08 +00003676
3677 // Weed out any names that could not be found by name lookup.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003678 llvm::SmallPtrSet<IdentifierInfo*, 16> QualifiedResults;
3679 LookupResult TmpRes(*this, TypoName, LookupKind);
3680 TmpRes.suppressDiagnostics();
3681 while (!Consumer.empty()) {
3682 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3683 unsigned ED = DI->first;
3684 for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(),
3685 IEnd = DI->second.end();
3686 I != IEnd; /* Increment in loop. */) {
3687 // If the item already has been looked up or is a keyword, keep it
3688 if (I->second.isResolved()) {
3689 ++I;
3690 continue;
Douglas Gregore24b5752010-10-14 20:34:08 +00003691 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003692
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003693 // Perform name lookup on this name.
3694 IdentifierInfo *Name = I->second.getCorrectionAsIdentifierInfo();
3695 LookupPotentialTypoResult(*this, TmpRes, Name, S, SS, MemberContext,
3696 EnteringContext, CTC);
3697
3698 switch (TmpRes.getResultKind()) {
3699 case LookupResult::NotFound:
3700 case LookupResult::NotFoundInCurrentInstantiation:
3701 QualifiedResults.insert(Name);
3702 // We didn't find this name in our scope, or didn't like what we found;
3703 // ignore it.
3704 {
3705 TypoCorrectionConsumer::result_iterator Next = I;
3706 ++Next;
3707 DI->second.erase(I);
3708 I = Next;
3709 }
3710 break;
3711
3712 case LookupResult::Ambiguous:
3713 // We don't deal with ambiguities.
3714 return TypoCorrection();
3715
3716 case LookupResult::Found:
3717 case LookupResult::FoundOverloaded:
3718 case LookupResult::FoundUnresolvedValue:
3719 I->second.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
3720 ++I;
3721 break;
3722 }
Douglas Gregore24b5752010-10-14 20:34:08 +00003723 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003724
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003725 if (DI->second.empty())
3726 Consumer.erase(DI);
3727 else if (!getLangOptions().CPlusPlus || QualifiedResults.empty() || !ED)
3728 // If there are results in the closest possible bucket, stop
3729 break;
3730
3731 // Only perform the qualified lookups for C++
3732 if (getLangOptions().CPlusPlus) {
3733 TmpRes.suppressDiagnostics();
3734 for (llvm::SmallPtrSet<IdentifierInfo*,
3735 16>::iterator QRI = QualifiedResults.begin(),
3736 QRIEnd = QualifiedResults.end();
3737 QRI != QRIEnd; ++QRI) {
3738 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
3739 NIEnd = Namespaces.end();
3740 NI != NIEnd; ++NI) {
3741 DeclContext *Ctx = NI->DeclCtx;
3742 unsigned QualifiedED = ED + NI->EditDistance;
3743
3744 // Stop searching once the namespaces are too far away to create
3745 // acceptable corrections for this identifier (since the namespaces
3746 // are sorted in ascending order by edit distance)
3747 if (QualifiedED > Consumer.getMaxEditDistance()) break;
3748
3749 TmpRes.clear();
3750 TmpRes.setLookupName(*QRI);
3751 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
3752
3753 switch (TmpRes.getResultKind()) {
3754 case LookupResult::Found:
3755 case LookupResult::FoundOverloaded:
3756 case LookupResult::FoundUnresolvedValue:
3757 Consumer.addName((*QRI)->getName(), TmpRes.getAsSingle<NamedDecl>(),
3758 QualifiedED, NI->NameSpecifier);
3759 break;
3760 case LookupResult::NotFound:
3761 case LookupResult::NotFoundInCurrentInstantiation:
3762 case LookupResult::Ambiguous:
3763 break;
3764 }
3765 }
3766 }
3767 }
3768
3769 QualifiedResults.clear();
3770 }
3771
3772 // No corrections remain...
3773 if (Consumer.empty()) return TypoCorrection();
3774
3775 TypoResultsMap &BestResults = Consumer.begin()->second;
3776 ED = Consumer.begin()->first;
3777
3778 if (ED > 0 && Typo->getName().size() / ED < 3) {
3779 // If this was an unqualified lookup, note that no correction was found.
3780 if (IsUnqualifiedLookup)
3781 (void)UnqualifiedTyposCorrected[Typo];
3782
3783 return TypoCorrection();
3784 }
3785
3786 // If we have multiple possible corrections, eliminate the ones where we
3787 // added namespace qualifiers to try to resolve the ambiguity (and to favor
3788 // corrections without additional namespace qualifiers)
3789 if (getLangOptions().CPlusPlus && BestResults.size() > 1) {
3790 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3791 for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(),
3792 IEnd = DI->second.end();
3793 I != IEnd; /* Increment in loop. */) {
3794 if (I->second.getCorrectionSpecifier() != NULL) {
3795 TypoCorrectionConsumer::result_iterator Cur = I;
3796 ++I;
3797 DI->second.erase(Cur);
3798 } else ++I;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003799 }
Douglas Gregoraaf87162010-04-14 20:04:41 +00003800 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003801
Douglas Gregore24b5752010-10-14 20:34:08 +00003802 // If only a single name remains, return that result.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003803 if (BestResults.size() == 1) {
3804 const llvm::StringMapEntry<TypoCorrection> &Correction = *(BestResults.begin());
3805 const TypoCorrection &Result = Correction.second;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003806
Douglas Gregor53e4b552010-10-26 17:18:00 +00003807 // Don't correct to a keyword that's the same as the typo; the keyword
3808 // wasn't actually in scope.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003809 if (ED == 0 && Result.isKeyword()) return TypoCorrection();
3810
3811 assert(Result.isResolved() && "correction has not been looked up");
3812 // Record the correction for unqualified lookup.
3813 if (IsUnqualifiedLookup)
3814 UnqualifiedTyposCorrected[Typo] = Result;
3815
3816 return Result;
3817 }
3818 else if (BestResults.size() > 1 && CTC == CTC_ObjCMessageReceiver
3819 && BestResults["super"].isKeyword()) {
3820 // Prefer 'super' when we're completing in a message-receiver
3821 // context.
3822
3823 // Don't correct to a keyword that's the same as the typo; the keyword
3824 // wasn't actually in scope.
3825 if (ED == 0) return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003826
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003827 // Record the correction for unqualified lookup.
3828 if (IsUnqualifiedLookup)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003829 UnqualifiedTyposCorrected[Typo] = BestResults["super"];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003830
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003831 return BestResults["super"];
Douglas Gregor7b824e82010-10-15 13:35:25 +00003832 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003833
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003834 if (IsUnqualifiedLookup)
3835 (void)UnqualifiedTyposCorrected[Typo];
3836
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003837 return TypoCorrection();
3838}
3839
3840std::string TypoCorrection::getAsString(const LangOptions &LO) const {
3841 if (CorrectionNameSpec) {
3842 std::string tmpBuffer;
3843 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
3844 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
3845 return PrefixOStream.str() + CorrectionName.getAsString();
3846 }
3847
3848 return CorrectionName.getAsString();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003849}