blob: 0e448e31207dd3f0c52cd206703e1d4331862c72 [file] [log] [blame]
Douglas Gregor34074322009-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 Gregorc3a6ade2010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000016#include "clang/Sema/Lookup.h"
Alexis Hunt4ac55e32011-06-04 04:32:43 +000017#include "clang/Sema/Overload.h"
John McCall8b0666c2010-08-20 18:27:03 +000018#include "clang/Sema/DeclSpec.h"
John McCallcc14d1f2010-08-24 08:50:51 +000019#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000020#include "clang/Sema/ScopeInfo.h"
John McCall19c1bfd2010-08-25 05:32:35 +000021#include "clang/Sema/TemplateDeduction.h"
Axel Naumann016538a2011-02-24 16:47:47 +000022#include "clang/Sema/ExternalSemaSource.h"
Douglas Gregorc2fa1692011-06-28 16:20:02 +000023#include "clang/Sema/TypoCorrection.h"
Douglas Gregor960b5bc2009-01-15 00:26:24 +000024#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000025#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000026#include "clang/AST/Decl.h"
27#include "clang/AST/DeclCXX.h"
28#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000029#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000030#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000031#include "clang/AST/ExprCXX.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000032#include "clang/Basic/Builtins.h"
Douglas Gregor34074322009-01-14 22:20:51 +000033#include "clang/Basic/LangOptions.h"
John McCalla1e130b2010-08-25 07:03:20 +000034#include "llvm/ADT/DenseSet.h"
Douglas Gregor34074322009-01-14 22:20:51 +000035#include "llvm/ADT/STLExtras.h"
Douglas Gregore254f902009-02-04 00:32:51 +000036#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0afa7f62010-10-14 20:34:08 +000037#include "llvm/ADT/StringMap.h"
John McCall6538c932009-10-10 05:48:19 +000038#include "llvm/Support/ErrorHandling.h"
Douglas Gregor0afa7f62010-10-14 20:34:08 +000039#include <limits>
Douglas Gregor2d435302009-12-30 17:04:44 +000040#include <list>
Douglas Gregor1c846b02009-01-16 00:38:09 +000041#include <set>
Douglas Gregor889ceb72009-02-03 19:21:40 +000042#include <vector>
43#include <iterator>
44#include <utility>
45#include <algorithm>
Douglas Gregorc2fa1692011-06-28 16:20:02 +000046#include <map>
Douglas Gregor34074322009-01-14 22:20:51 +000047
48using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000049using namespace sema;
Douglas Gregor34074322009-01-14 22:20:51 +000050
John McCallf6c8a4e2009-11-10 07:01:13 +000051namespace {
52 class UnqualUsingEntry {
53 const DeclContext *Nominated;
54 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000055
John McCallf6c8a4e2009-11-10 07:01:13 +000056 public:
57 UnqualUsingEntry(const DeclContext *Nominated,
58 const DeclContext *CommonAncestor)
59 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
60 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000061
John McCallf6c8a4e2009-11-10 07:01:13 +000062 const DeclContext *getCommonAncestor() const {
63 return CommonAncestor;
64 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000065
John McCallf6c8a4e2009-11-10 07:01:13 +000066 const DeclContext *getNominatedNamespace() const {
67 return Nominated;
68 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000069
John McCallf6c8a4e2009-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 Gregor889ceb72009-02-03 19:21:40 +000075
John McCallf6c8a4e2009-11-10 07:01:13 +000076 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
77 return E.getCommonAncestor() < DC;
78 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000079
John McCallf6c8a4e2009-11-10 07:01:13 +000080 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
81 return DC < E.getCommonAncestor();
82 }
83 };
84 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000085
John McCallf6c8a4e2009-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 Gregor889ceb72009-02-03 19:21:40 +000090
John McCallf6c8a4e2009-11-10 07:01:13 +000091 ListTy list;
92 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000093
John McCallf6c8a4e2009-11-10 07:01:13 +000094 public:
95 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +000096
John McCallf6c8a4e2009-11-10 07:01:13 +000097 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000098 // C++ [namespace.udir]p1:
John McCallf6c8a4e2009-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 Gregor889ceb72009-02-03 19:21:40 +0000105
John McCallf6c8a4e2009-11-10 07:01:13 +0000106 for (; S; S = S->getParent()) {
John McCallf6c8a4e2009-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 Takumif9cbcc42011-01-27 07:10:08 +0000113
John McCallf6c8a4e2009-11-10 07:01:13 +0000114 for (; I != End; ++I)
John McCall48871652010-08-21 09:40:31 +0000115 visit(*I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000116 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000117 }
118 }
John McCallf6c8a4e2009-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 McCall9757d032009-11-10 09:20:04 +0000183 Common = Common->getPrimaryContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000184
John McCallf6c8a4e2009-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 McCallf6c8a4e2009-11-10 07:01:13 +0000192 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000193
John McCallf6c8a4e2009-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 McCall9757d032009-11-10 09:20:04 +0000199 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCallf6c8a4e2009-11-10 07:01:13 +0000200 UnqualUsingEntry::Comparator());
201 }
202 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000203}
204
Douglas Gregor889ceb72009-02-03 19:21:40 +0000205// Retrieve the set of identifier namespaces that correspond to a
206// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000207static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
208 bool CPlusPlus,
209 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000210 unsigned IDNS = 0;
211 switch (NameKind) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +0000212 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000213 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000214 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000215 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000216 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000217 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000218 if (Redeclaration)
219 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCallea305ed2009-12-18 10:40:03 +0000220 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000221 break;
222
John McCallb9467b62010-04-24 01:30:58 +0000223 case Sema::LookupOperatorName:
224 // Operator lookup is its own crazy thing; it is not the same
225 // as (e.g.) looking up an operator name for redeclaration.
226 assert(!Redeclaration && "cannot do redeclaration operator lookup");
227 IDNS = Decl::IDNS_NonMemberOperator;
228 break;
229
Douglas Gregor889ceb72009-02-03 19:21:40 +0000230 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000231 if (CPlusPlus) {
232 IDNS = Decl::IDNS_Type;
233
234 // When looking for a redeclaration of a tag name, we add:
235 // 1) TagFriend to find undeclared friend decls
236 // 2) Namespace because they can't "overload" with tag decls.
237 // 3) Tag because it includes class templates, which can't
238 // "overload" with tag decls.
239 if (Redeclaration)
240 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
241 } else {
242 IDNS = Decl::IDNS_Tag;
243 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000244 break;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000245 case Sema::LookupLabel:
246 IDNS = Decl::IDNS_Label;
247 break;
248
Douglas Gregor889ceb72009-02-03 19:21:40 +0000249 case Sema::LookupMemberName:
250 IDNS = Decl::IDNS_Member;
251 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000252 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000253 break;
254
255 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000256 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
257 break;
258
Douglas Gregor889ceb72009-02-03 19:21:40 +0000259 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000260 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000261 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000262
John McCall84d87672009-12-10 09:41:52 +0000263 case Sema::LookupUsingDeclName:
264 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
265 | Decl::IDNS_Member | Decl::IDNS_Using;
266 break;
267
Douglas Gregor79947a22009-04-24 00:11:27 +0000268 case Sema::LookupObjCProtocolName:
269 IDNS = Decl::IDNS_ObjCProtocol;
270 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000271
Douglas Gregor39982192010-08-15 06:18:01 +0000272 case Sema::LookupAnyName:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000273 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor39982192010-08-15 06:18:01 +0000274 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
275 | Decl::IDNS_Type;
276 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000277 }
278 return IDNS;
279}
280
John McCallea305ed2009-12-18 10:40:03 +0000281void LookupResult::configure() {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000282 IDNS = getIDNS(LookupKind, SemaRef.getLangOptions().CPlusPlus,
John McCallea305ed2009-12-18 10:40:03 +0000283 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000284
285 // If we're looking for one of the allocation or deallocation
286 // operators, make sure that the implicitly-declared new and delete
287 // operators can be found.
288 if (!isForRedeclaration()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000289 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000290 case OO_New:
291 case OO_Delete:
292 case OO_Array_New:
293 case OO_Array_Delete:
294 SemaRef.DeclareGlobalNewDelete();
295 break;
296
297 default:
298 break;
299 }
300 }
John McCallea305ed2009-12-18 10:40:03 +0000301}
302
John McCall19c1bfd2010-08-25 05:32:35 +0000303void LookupResult::sanity() const {
304 assert(ResultKind != NotFound || Decls.size() == 0);
305 assert(ResultKind != Found || Decls.size() == 1);
306 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
307 (Decls.size() == 1 &&
308 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
309 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
310 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000311 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
312 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall19c1bfd2010-08-25 05:32:35 +0000313 assert((Paths != NULL) == (ResultKind == Ambiguous &&
314 (Ambiguity == AmbiguousBaseSubobjectTypes ||
315 Ambiguity == AmbiguousBaseSubobjects)));
316}
John McCall19c1bfd2010-08-25 05:32:35 +0000317
John McCall9f3059a2009-10-09 21:13:30 +0000318// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000319void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000320 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000321}
322
John McCall283b9012009-11-22 00:44:51 +0000323/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000324void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000325 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000326
John McCall9f3059a2009-10-09 21:13:30 +0000327 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000328 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000329 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000330 return;
331 }
332
John McCall283b9012009-11-22 00:44:51 +0000333 // If there's a single decl, we need to examine it to decide what
334 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000335 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000336 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
337 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000338 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000339 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000340 ResultKind = FoundUnresolvedValue;
341 return;
342 }
John McCall9f3059a2009-10-09 21:13:30 +0000343
John McCall6538c932009-10-10 05:48:19 +0000344 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000345 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000346
John McCall9f3059a2009-10-09 21:13:30 +0000347 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor13e65872010-08-11 14:45:53 +0000348 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000349
John McCall9f3059a2009-10-09 21:13:30 +0000350 bool Ambiguous = false;
351 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000352 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000353
354 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000355
John McCall9f3059a2009-10-09 21:13:30 +0000356 unsigned I = 0;
357 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000358 NamedDecl *D = Decls[I]->getUnderlyingDecl();
359 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000360
Douglas Gregor13e65872010-08-11 14:45:53 +0000361 // Redeclarations of types via typedef can occur both within a scope
362 // and, through using declarations and directives, across scopes. There is
363 // no ambiguity if they all refer to the same type, so unique based on the
364 // canonical type.
365 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
366 if (!TD->getDeclContext()->isRecord()) {
367 QualType T = SemaRef.Context.getTypeDeclType(TD);
368 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
369 // The type is not unique; pull something off the back and continue
370 // at this index.
371 Decls[I] = Decls[--N];
372 continue;
373 }
374 }
375 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000376
John McCallf0f1cf02009-11-17 07:50:12 +0000377 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000378 // If it's not unique, pull something off the back (and
379 // continue at this index).
380 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000381 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000382 }
383
Douglas Gregor13e65872010-08-11 14:45:53 +0000384 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000385
Douglas Gregor13e65872010-08-11 14:45:53 +0000386 if (isa<UnresolvedUsingValueDecl>(D)) {
387 HasUnresolved = true;
388 } else if (isa<TagDecl>(D)) {
389 if (HasTag)
390 Ambiguous = true;
391 UniqueTagIndex = I;
392 HasTag = true;
393 } else if (isa<FunctionTemplateDecl>(D)) {
394 HasFunction = true;
395 HasFunctionTemplate = true;
396 } else if (isa<FunctionDecl>(D)) {
397 HasFunction = true;
398 } else {
399 if (HasNonFunction)
400 Ambiguous = true;
401 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000402 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000403 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000404 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000405
John McCall9f3059a2009-10-09 21:13:30 +0000406 // C++ [basic.scope.hiding]p2:
407 // A class name or enumeration name can be hidden by the name of
408 // an object, function, or enumerator declared in the same
409 // scope. If a class or enumeration name and an object, function,
410 // or enumerator are declared in the same scope (in any order)
411 // with the same name, the class or enumeration name is hidden
412 // wherever the object, function, or enumerator name is visible.
413 // But it's still an error if there are distinct tag types found,
414 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000415 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000416 (HasFunction || HasNonFunction || HasUnresolved)) {
417 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
418 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
419 Decls[UniqueTagIndex] = Decls[--N];
420 else
421 Ambiguous = true;
422 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000423
John McCall9f3059a2009-10-09 21:13:30 +0000424 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000425
John McCall80053822009-12-03 00:58:24 +0000426 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000427 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000428
John McCall9f3059a2009-10-09 21:13:30 +0000429 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000430 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000431 else if (HasUnresolved)
432 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000433 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000434 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000435 else
John McCall27b18f82009-11-17 02:14:36 +0000436 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000437}
438
John McCall5cebab12009-11-18 07:57:50 +0000439void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000440 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000441 DeclContext::lookup_iterator DI, DE;
442 for (I = P.begin(), E = P.end(); I != E; ++I)
443 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
444 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000445}
446
John McCall5cebab12009-11-18 07:57:50 +0000447void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000448 Paths = new CXXBasePaths;
449 Paths->swap(P);
450 addDeclsFromBasePaths(*Paths);
451 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000452 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000453}
454
John McCall5cebab12009-11-18 07:57:50 +0000455void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000456 Paths = new CXXBasePaths;
457 Paths->swap(P);
458 addDeclsFromBasePaths(*Paths);
459 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000460 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000461}
462
John McCall5cebab12009-11-18 07:57:50 +0000463void LookupResult::print(llvm::raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000464 Out << Decls.size() << " result(s)";
465 if (isAmbiguous()) Out << ", ambiguous";
466 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000467
John McCall9f3059a2009-10-09 21:13:30 +0000468 for (iterator I = begin(), E = end(); I != E; ++I) {
469 Out << "\n";
470 (*I)->print(Out, 2);
471 }
472}
473
Douglas Gregord3a59182010-02-12 05:48:04 +0000474/// \brief Lookup a builtin function, when name lookup would otherwise
475/// fail.
476static bool LookupBuiltin(Sema &S, LookupResult &R) {
477 Sema::LookupNameKind NameKind = R.getLookupKind();
478
479 // If we didn't find a use of this identifier, and if the identifier
480 // corresponds to a compiler builtin, create the decl object for the builtin
481 // now, injecting it into translation unit scope, and return it.
482 if (NameKind == Sema::LookupOrdinaryName ||
483 NameKind == Sema::LookupRedeclarationWithLinkage) {
484 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
485 if (II) {
486 // If this is a builtin on this (or all) targets, create the decl.
487 if (unsigned BuiltinID = II->getBuiltinID()) {
488 // In C++, we don't have any predefined library functions like
489 // 'malloc'. Instead, we'll just error.
490 if (S.getLangOptions().CPlusPlus &&
491 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
492 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000493
494 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
495 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000496 R.isForRedeclaration(),
497 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000498 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000499 return true;
500 }
501
502 if (R.isForRedeclaration()) {
503 // If we're redeclaring this function anyway, forget that
504 // this was a builtin at all.
505 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
506 }
507
508 return false;
Douglas Gregord3a59182010-02-12 05:48:04 +0000509 }
510 }
511 }
512
513 return false;
514}
515
Douglas Gregor7454c562010-07-02 20:37:36 +0000516/// \brief Determine whether we can declare a special member function within
517/// the class at this point.
518static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
519 const CXXRecordDecl *Class) {
John McCall2ded5d22010-08-11 23:52:36 +0000520 // Don't do it if the class is invalid.
521 if (Class->isInvalidDecl())
522 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000523
Douglas Gregor7454c562010-07-02 20:37:36 +0000524 // We need to have a definition for the class.
525 if (!Class->getDefinition() || Class->isDependentContext())
526 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000527
Douglas Gregor7454c562010-07-02 20:37:36 +0000528 // We can't be in the middle of defining the class.
529 if (const RecordType *RecordTy
530 = Context.getTypeDeclType(Class)->getAs<RecordType>())
531 return !RecordTy->isBeingDefined();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000532
Douglas Gregor7454c562010-07-02 20:37:36 +0000533 return false;
534}
535
536void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000537 if (!CanDeclareSpecialMemberFunction(Context, Class))
538 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000539
540 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000541 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000542 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000543
Douglas Gregora6d69502010-07-02 23:41:54 +0000544 // If the copy constructor has not yet been declared, do so now.
545 if (!Class->hasDeclaredCopyConstructor())
546 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000547
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000548 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000549 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000550 DeclareImplicitCopyAssignment(Class);
551
Douglas Gregor7454c562010-07-02 20:37:36 +0000552 // If the destructor has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000553 if (!Class->hasDeclaredDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000554 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000555}
556
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000557/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000558/// special member function.
559static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
560 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000561 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000562 case DeclarationName::CXXDestructorName:
563 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000564
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000565 case DeclarationName::CXXOperatorName:
566 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000567
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000568 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000569 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000570 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000571
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000572 return false;
573}
574
575/// \brief If there are any implicit member functions with the given name
576/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000577static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000578 DeclarationName Name,
579 const DeclContext *DC) {
580 if (!DC)
581 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000582
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000583 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000584 case DeclarationName::CXXConstructorName:
585 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor9672f922010-07-03 00:47:00 +0000586 if (Record->getDefinition() &&
587 CanDeclareSpecialMemberFunction(S.Context, Record)) {
Alexis Huntea6f0322011-05-11 22:34:38 +0000588 if (Record->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000589 S.DeclareImplicitDefaultConstructor(
590 const_cast<CXXRecordDecl *>(Record));
591 if (!Record->hasDeclaredCopyConstructor())
592 S.DeclareImplicitCopyConstructor(const_cast<CXXRecordDecl *>(Record));
593 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000594 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000595
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000596 case DeclarationName::CXXDestructorName:
597 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
598 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
599 CanDeclareSpecialMemberFunction(S.Context, Record))
600 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000601 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000602
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000603 case DeclarationName::CXXOperatorName:
604 if (Name.getCXXOverloadedOperator() != OO_Equal)
605 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000606
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000607 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
608 if (Record->getDefinition() && !Record->hasDeclaredCopyAssignment() &&
609 CanDeclareSpecialMemberFunction(S.Context, Record))
610 S.DeclareImplicitCopyAssignment(const_cast<CXXRecordDecl *>(Record));
611 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000612
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000613 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000614 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000615 }
616}
Douglas Gregor7454c562010-07-02 20:37:36 +0000617
John McCall9f3059a2009-10-09 21:13:30 +0000618// Adds all qualifying matches for a name within a decl context to the
619// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000620static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000621 bool Found = false;
622
Douglas Gregor7454c562010-07-02 20:37:36 +0000623 // Lazily declare C++ special member functions.
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000624 if (S.getLangOptions().CPlusPlus)
625 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000626
Douglas Gregor7454c562010-07-02 20:37:36 +0000627 // Perform lookup into this declaration context.
John McCallf6c8a4e2009-11-10 07:01:13 +0000628 DeclContext::lookup_const_iterator I, E;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000629 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall401982f2010-01-20 21:53:11 +0000630 NamedDecl *D = *I;
631 if (R.isAcceptableDecl(D)) {
632 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000633 Found = true;
634 }
635 }
John McCall9f3059a2009-10-09 21:13:30 +0000636
Douglas Gregord3a59182010-02-12 05:48:04 +0000637 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
638 return true;
639
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000640 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000641 != DeclarationName::CXXConversionFunctionName ||
642 R.getLookupName().getCXXNameType()->isDependentType() ||
643 !isa<CXXRecordDecl>(DC))
644 return Found;
645
646 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000647 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000648 // name lookup. Instead, any conversion function templates visible in the
649 // context of the use are considered. [...]
650 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
651 if (!Record->isDefinition())
652 return Found;
653
654 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000655 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
Chandler Carruth3a693b72010-01-31 11:44:02 +0000656 UEnd = Unresolved->end(); U != UEnd; ++U) {
657 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
658 if (!ConvTemplate)
659 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000660
Chandler Carruth3a693b72010-01-31 11:44:02 +0000661 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000662 // add the conversion function template. When we deduce template
663 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000664 // type of the new declaration with the type of the function template.
665 if (R.isForRedeclaration()) {
666 R.addDecl(ConvTemplate);
667 Found = true;
668 continue;
669 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000670
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000671 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000672 // [...] For each such operator, if argument deduction succeeds
673 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000674 // name lookup.
675 //
676 // When referencing a conversion function for any purpose other than
677 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000678 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000679 // specialization into the result set. We do this to avoid forcing all
680 // callers to perform special deduction for conversion functions.
John McCall19c1bfd2010-08-25 05:32:35 +0000681 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruth3a693b72010-01-31 11:44:02 +0000682 FunctionDecl *Specialization = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000683
684 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000685 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
686 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000687
Chandler Carruth3a693b72010-01-31 11:44:02 +0000688 // Compute the type of the function that we would expect the conversion
689 // function to have, if it were to match the name given.
690 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000691 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
692 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
Sebastian Redl7c6c9e92011-03-06 10:52:04 +0000693 EPI.ExceptionSpecType = EST_None;
John McCalldb40c7f2010-12-14 08:05:40 +0000694 EPI.NumExceptions = 0;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000695 QualType ExpectedType
696 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
John McCalldb40c7f2010-12-14 08:05:40 +0000697 0, 0, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000698
Chandler Carruth3a693b72010-01-31 11:44:02 +0000699 // Perform template argument deduction against the type that we would
700 // expect the function to have.
701 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
702 Specialization, Info)
703 == Sema::TDK_Success) {
704 R.addDecl(Specialization);
705 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000706 }
707 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000708
John McCall9f3059a2009-10-09 21:13:30 +0000709 return Found;
710}
711
John McCallf6c8a4e2009-11-10 07:01:13 +0000712// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000713static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000714CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000715 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000716
717 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
718
John McCallf6c8a4e2009-11-10 07:01:13 +0000719 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000720 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000721
John McCallf6c8a4e2009-11-10 07:01:13 +0000722 // Perform direct name lookup into the namespaces nominated by the
723 // using directives whose common ancestor is this namespace.
724 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
725 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000726
John McCallf6c8a4e2009-11-10 07:01:13 +0000727 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000728 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000729 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000730
731 R.resolveKind();
732
733 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000734}
735
736static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000737 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000738 return Ctx->isFileContext();
739 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000740}
Douglas Gregored8f2882009-01-30 01:04:22 +0000741
Douglas Gregor66230062010-03-15 14:33:29 +0000742// Find the next outer declaration context from this scope. This
743// routine actually returns the semantic outer context, which may
744// differ from the lexical context (encoded directly in the Scope
745// stack) when we are parsing a member of a class template. In this
746// case, the second element of the pair will be true, to indicate that
747// name lookup should continue searching in this semantic context when
748// it leaves the current template parameter scope.
749static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
750 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
751 DeclContext *Lexical = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000752 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000753 OuterS = OuterS->getParent()) {
754 if (OuterS->getEntity()) {
Douglas Gregorea166062010-03-15 15:26:48 +0000755 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor66230062010-03-15 14:33:29 +0000756 break;
757 }
758 }
759
760 // C++ [temp.local]p8:
761 // In the definition of a member of a class template that appears
762 // outside of the namespace containing the class template
763 // definition, the name of a template-parameter hides the name of
764 // a member of this namespace.
765 //
766 // Example:
767 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000768 // namespace N {
769 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000770 //
771 // template<class T> class B {
772 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000773 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000774 // }
775 //
776 // template<class C> void N::B<C>::f(C) {
777 // C b; // C is the template parameter, not N::C
778 // }
779 //
780 // In this example, the lexical context we return is the
781 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000782 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000783 !S->getParent()->isTemplateParamScope())
784 return std::make_pair(Lexical, false);
785
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000786 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000787 // For the example, this is the scope for the template parameters of
788 // template<class C>.
789 Scope *OutermostTemplateScope = S->getParent();
790 while (OutermostTemplateScope->getParent() &&
791 OutermostTemplateScope->getParent()->isTemplateParamScope())
792 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000793
Douglas Gregor66230062010-03-15 14:33:29 +0000794 // Find the namespace context in which the original scope occurs. In
795 // the example, this is namespace N.
796 DeclContext *Semantic = DC;
797 while (!Semantic->isFileContext())
798 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000799
Douglas Gregor66230062010-03-15 14:33:29 +0000800 // Find the declaration context just outside of the template
801 // parameter scope. This is the context in which the template is
802 // being lexically declaration (a namespace context). In the
803 // example, this is the global scope.
804 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
805 Lexical->Encloses(Semantic))
806 return std::make_pair(Semantic, true);
807
808 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000809}
810
John McCall27b18f82009-11-17 02:14:36 +0000811bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCallea305ed2009-12-18 10:40:03 +0000812 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000813
814 DeclarationName Name = R.getLookupName();
815
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000816 // If this is the name of an implicitly-declared special member function,
817 // go through the scope stack to implicitly declare
818 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
819 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
820 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
821 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
822 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000823
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000824 // Implicitly declare member functions with the name we're looking for, if in
825 // fact we are in a scope where it matters.
826
Douglas Gregor889ceb72009-02-03 19:21:40 +0000827 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000828 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000829 I = IdResolver.begin(Name),
830 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000831
Douglas Gregor889ceb72009-02-03 19:21:40 +0000832 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000833 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000834 // ...During unqualified name lookup (3.4.1), the names appear as if
835 // they were declared in the nearest enclosing namespace which contains
836 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000837 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000838 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000839 //
840 // For example:
841 // namespace A { int i; }
842 // void foo() {
843 // int i;
844 // {
845 // using namespace A;
846 // ++i; // finds local 'i', A::i appears at global scope
847 // }
848 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000849 //
Douglas Gregor66230062010-03-15 14:33:29 +0000850 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor700792c2009-02-05 19:25:20 +0000851 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor3e51e172010-05-20 20:58:56 +0000852 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
853
Douglas Gregor889ceb72009-02-03 19:21:40 +0000854 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000855 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000856 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000857 if (R.isAcceptableDecl(*I)) {
John McCall9f3059a2009-10-09 21:13:30 +0000858 Found = true;
859 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000860 }
861 }
John McCall9f3059a2009-10-09 21:13:30 +0000862 if (Found) {
863 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000864 if (S->isClassScope())
865 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
866 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000867 return true;
868 }
869
Douglas Gregor66230062010-03-15 14:33:29 +0000870 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
871 S->getParent() && !S->getParent()->isTemplateParamScope()) {
872 // We've just searched the last template parameter scope and
873 // found nothing, so look into the the contexts between the
874 // lexical and semantic declaration contexts returned by
875 // findOuterContext(). This implements the name lookup behavior
876 // of C++ [temp.local]p8.
877 Ctx = OutsideOfTemplateParamDC;
878 OutsideOfTemplateParamDC = 0;
879 }
880
881 if (Ctx) {
882 DeclContext *OuterCtx;
883 bool SearchAfterTemplateScope;
884 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
885 if (SearchAfterTemplateScope)
886 OutsideOfTemplateParamDC = OuterCtx;
887
Douglas Gregorea166062010-03-15 15:26:48 +0000888 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000889 // We do not directly look into transparent contexts, since
890 // those entities will be found in the nearest enclosing
891 // non-transparent context.
892 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000893 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000894
895 // We do not look directly into function or method contexts,
896 // since all of the local variables and parameters of the
897 // function/method are present within the Scope.
898 if (Ctx->isFunctionOrMethod()) {
899 // If we have an Objective-C instance method, look for ivars
900 // in the corresponding interface.
901 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
902 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
903 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
904 ObjCInterfaceDecl *ClassDeclared;
905 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000906 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +0000907 ClassDeclared)) {
908 if (R.isAcceptableDecl(Ivar)) {
909 R.addDecl(Ivar);
910 R.resolveKind();
911 return true;
912 }
913 }
914 }
915 }
916
917 continue;
918 }
919
Douglas Gregor7f737c02009-09-10 16:57:35 +0000920 // Perform qualified name lookup into this context.
921 // FIXME: In some cases, we know that every name that could be found by
922 // this qualified name lookup will also be on the identifier chain. For
923 // example, inside a class without any base classes, we never need to
924 // perform qualified lookup because all of the members are on top of the
925 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000926 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +0000927 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000928 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000929 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000930 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000931
John McCallf6c8a4e2009-11-10 07:01:13 +0000932 // Stop if we ran out of scopes.
933 // FIXME: This really, really shouldn't be happening.
934 if (!S) return false;
935
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +0000936 // If we are looking for members, no need to look into global/namespace scope.
937 if (R.getLookupKind() == LookupMemberName)
938 return false;
939
Douglas Gregor700792c2009-02-05 19:25:20 +0000940 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000941 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000942 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000943 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
944 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000945
John McCallf6c8a4e2009-11-10 07:01:13 +0000946 UnqualUsingDirectiveSet UDirs;
947 UDirs.visitScopeChain(Initial, S);
948 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000949
Douglas Gregor700792c2009-02-05 19:25:20 +0000950 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000951 // Unqualified name lookup in C++ requires looking into scopes
952 // that aren't strictly lexical, and therefore we walk through the
953 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000954
Douglas Gregor889ceb72009-02-03 19:21:40 +0000955 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000956 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000957 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000958 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000959 if (R.isAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000960 // We found something. Look for anything else in our scope
961 // with this same name and in an acceptable identifier
962 // namespace, so that we can construct an overload set if we
963 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000964 Found = true;
965 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000966 }
967 }
968
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000969 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +0000970 R.resolveKind();
971 return true;
972 }
973
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000974 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
975 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
976 S->getParent() && !S->getParent()->isTemplateParamScope()) {
977 // We've just searched the last template parameter scope and
978 // found nothing, so look into the the contexts between the
979 // lexical and semantic declaration contexts returned by
980 // findOuterContext(). This implements the name lookup behavior
981 // of C++ [temp.local]p8.
982 Ctx = OutsideOfTemplateParamDC;
983 OutsideOfTemplateParamDC = 0;
984 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000985
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000986 if (Ctx) {
987 DeclContext *OuterCtx;
988 bool SearchAfterTemplateScope;
989 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
990 if (SearchAfterTemplateScope)
991 OutsideOfTemplateParamDC = OuterCtx;
992
993 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
994 // We do not directly look into transparent contexts, since
995 // those entities will be found in the nearest enclosing
996 // non-transparent context.
997 if (Ctx->isTransparentContext())
998 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000999
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001000 // If we have a context, and it's not a context stashed in the
1001 // template parameter scope for an out-of-line definition, also
1002 // look into that context.
1003 if (!(Found && S && S->isTemplateParamScope())) {
1004 assert(Ctx->isFileContext() &&
1005 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001006
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001007 // Look into context considering using-directives.
1008 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1009 Found = true;
1010 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001011
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001012 if (Found) {
1013 R.resolveKind();
1014 return true;
1015 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001016
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001017 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1018 return false;
1019 }
1020 }
1021
Douglas Gregor3ce74932010-02-05 07:07:10 +00001022 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001023 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001024 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001025
John McCall9f3059a2009-10-09 21:13:30 +00001026 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001027}
1028
Douglas Gregor34074322009-01-14 22:20:51 +00001029/// @brief Perform unqualified name lookup starting from a given
1030/// scope.
1031///
1032/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1033/// used to find names within the current scope. For example, 'x' in
1034/// @code
1035/// int x;
1036/// int f() {
1037/// return x; // unqualified name look finds 'x' in the global scope
1038/// }
1039/// @endcode
1040///
1041/// Different lookup criteria can find different names. For example, a
1042/// particular scope can have both a struct and a function of the same
1043/// name, and each can be found by certain lookup criteria. For more
1044/// information about lookup criteria, see the documentation for the
1045/// class LookupCriteria.
1046///
1047/// @param S The scope from which unqualified name lookup will
1048/// begin. If the lookup criteria permits, name lookup may also search
1049/// in the parent scopes.
1050///
1051/// @param Name The name of the entity that we are searching for.
1052///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001053/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001054/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001055/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +00001056///
1057/// @returns The result of name lookup, which includes zero or more
1058/// declarations and possibly additional information used to diagnose
1059/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +00001060bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1061 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001062 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001063
John McCall27b18f82009-11-17 02:14:36 +00001064 LookupNameKind NameKind = R.getLookupKind();
1065
Douglas Gregor34074322009-01-14 22:20:51 +00001066 if (!getLangOptions().CPlusPlus) {
1067 // Unqualified name lookup in C/Objective-C is purely lexical, so
1068 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001069 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001070 // Find the nearest non-transparent declaration scope.
1071 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +00001072 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +00001073 static_cast<DeclContext *>(S->getEntity())
1074 ->isTransparentContext()))
1075 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001076 }
1077
John McCallea305ed2009-12-18 10:40:03 +00001078 unsigned IDNS = R.getIdentifierNamespace();
1079
Douglas Gregor34074322009-01-14 22:20:51 +00001080 // Scan up the scope chain looking for a decl that matches this
1081 // identifier that is in the appropriate namespace. This search
1082 // should not take long, as shadowing of names is uncommon, and
1083 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001084 bool LeftStartingScope = false;
1085
Douglas Gregored8f2882009-01-30 01:04:22 +00001086 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001087 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001088 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001089 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001090 if (NameKind == LookupRedeclarationWithLinkage) {
1091 // Determine whether this (or a previous) declaration is
1092 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001093 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001094 LeftStartingScope = true;
1095
1096 // If we found something outside of our starting scope that
1097 // does not have linkage, skip it.
1098 if (LeftStartingScope && !((*I)->hasLinkage()))
1099 continue;
1100 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001101 else if (NameKind == LookupObjCImplicitSelfParam &&
1102 !isa<ImplicitParamDecl>(*I))
1103 continue;
1104
John McCall9f3059a2009-10-09 21:13:30 +00001105 R.addDecl(*I);
1106
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001107 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001108 // If this declaration has the "overloadable" attribute, we
1109 // might have a set of overloaded functions.
1110
1111 // Figure out what scope the identifier is in.
Chris Lattner83f095c2009-03-28 19:18:32 +00001112 while (!(S->getFlags() & Scope::DeclScope) ||
John McCall48871652010-08-21 09:40:31 +00001113 !S->isDeclScope(*I))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001114 S = S->getParent();
1115
1116 // Find the last declaration in this scope (with the same
1117 // name, naturally).
1118 IdentifierResolver::iterator LastI = I;
1119 for (++LastI; LastI != IEnd; ++LastI) {
John McCall48871652010-08-21 09:40:31 +00001120 if (!S->isDeclScope(*LastI))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001121 break;
John McCall9f3059a2009-10-09 21:13:30 +00001122 R.addDecl(*LastI);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001123 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001124 }
1125
John McCall9f3059a2009-10-09 21:13:30 +00001126 R.resolveKind();
1127
1128 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001129 }
Douglas Gregor34074322009-01-14 22:20:51 +00001130 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001131 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001132 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001133 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001134 }
1135
1136 // If we didn't find a use of this identifier, and if the identifier
1137 // corresponds to a compiler builtin, create the decl object for the builtin
1138 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001139 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1140 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001141
Axel Naumann016538a2011-02-24 16:47:47 +00001142 // If we didn't find a use of this identifier, the ExternalSource
1143 // may be able to handle the situation.
1144 // Note: some lookup failures are expected!
1145 // See e.g. R.isForRedeclaration().
1146 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001147}
1148
John McCall6538c932009-10-10 05:48:19 +00001149/// @brief Perform qualified name lookup in the namespaces nominated by
1150/// using directives by the given context.
1151///
1152/// C++98 [namespace.qual]p2:
1153/// Given X::m (where X is a user-declared namespace), or given ::m
1154/// (where X is the global namespace), let S be the set of all
1155/// declarations of m in X and in the transitive closure of all
1156/// namespaces nominated by using-directives in X and its used
1157/// namespaces, except that using-directives are ignored in any
1158/// namespace, including X, directly containing one or more
1159/// declarations of m. No namespace is searched more than once in
1160/// the lookup of a name. If S is the empty set, the program is
1161/// ill-formed. Otherwise, if S has exactly one member, or if the
1162/// context of the reference is a using-declaration
1163/// (namespace.udecl), S is the required set of declarations of
1164/// m. Otherwise if the use of m is not one that allows a unique
1165/// declaration to be chosen from S, the program is ill-formed.
1166/// C++98 [namespace.qual]p5:
1167/// During the lookup of a qualified namespace member name, if the
1168/// lookup finds more than one declaration of the member, and if one
1169/// declaration introduces a class name or enumeration name and the
1170/// other declarations either introduce the same object, the same
1171/// enumerator or a set of functions, the non-type name hides the
1172/// class or enumeration name if and only if the declarations are
1173/// from the same namespace; otherwise (the declarations are from
1174/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001175static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001176 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001177 assert(StartDC->isFileContext() && "start context is not a file context");
1178
1179 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1180 DeclContext::udir_iterator E = StartDC->using_directives_end();
1181
1182 if (I == E) return false;
1183
1184 // We have at least added all these contexts to the queue.
1185 llvm::DenseSet<DeclContext*> Visited;
1186 Visited.insert(StartDC);
1187
1188 // We have not yet looked into these namespaces, much less added
1189 // their "using-children" to the queue.
1190 llvm::SmallVector<NamespaceDecl*, 8> Queue;
1191
1192 // We have already looked into the initial namespace; seed the queue
1193 // with its using-children.
1194 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +00001195 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6538c932009-10-10 05:48:19 +00001196 if (Visited.insert(ND).second)
1197 Queue.push_back(ND);
1198 }
1199
1200 // The easiest way to implement the restriction in [namespace.qual]p5
1201 // is to check whether any of the individual results found a tag
1202 // and, if so, to declare an ambiguity if the final result is not
1203 // a tag.
1204 bool FoundTag = false;
1205 bool FoundNonTag = false;
1206
John McCall5cebab12009-11-18 07:57:50 +00001207 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001208
1209 bool Found = false;
1210 while (!Queue.empty()) {
1211 NamespaceDecl *ND = Queue.back();
1212 Queue.pop_back();
1213
1214 // We go through some convolutions here to avoid copying results
1215 // between LookupResults.
1216 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001217 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001218 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001219
1220 if (FoundDirect) {
1221 // First do any local hiding.
1222 DirectR.resolveKind();
1223
1224 // If the local result is a tag, remember that.
1225 if (DirectR.isSingleTagDecl())
1226 FoundTag = true;
1227 else
1228 FoundNonTag = true;
1229
1230 // Append the local results to the total results if necessary.
1231 if (UseLocal) {
1232 R.addAllDecls(LocalR);
1233 LocalR.clear();
1234 }
1235 }
1236
1237 // If we find names in this namespace, ignore its using directives.
1238 if (FoundDirect) {
1239 Found = true;
1240 continue;
1241 }
1242
1243 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1244 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1245 if (Visited.insert(Nom).second)
1246 Queue.push_back(Nom);
1247 }
1248 }
1249
1250 if (Found) {
1251 if (FoundTag && FoundNonTag)
1252 R.setAmbiguousQualifiedTagHiding();
1253 else
1254 R.resolveKind();
1255 }
1256
1257 return Found;
1258}
1259
Douglas Gregor39982192010-08-15 06:18:01 +00001260/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001261static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor39982192010-08-15 06:18:01 +00001262 CXXBasePath &Path,
1263 void *Name) {
1264 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001265
Douglas Gregor39982192010-08-15 06:18:01 +00001266 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1267 Path.Decls = BaseRecord->lookup(N);
1268 return Path.Decls.first != Path.Decls.second;
1269}
1270
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001271/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001272/// static members, nested types, and enumerators.
1273template<typename InputIterator>
1274static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1275 Decl *D = (*First)->getUnderlyingDecl();
1276 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1277 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001278
Douglas Gregorc0d24902010-10-22 22:08:47 +00001279 if (isa<CXXMethodDecl>(D)) {
1280 // Determine whether all of the methods are static.
1281 bool AllMethodsAreStatic = true;
1282 for(; First != Last; ++First) {
1283 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001284
Douglas Gregorc0d24902010-10-22 22:08:47 +00001285 if (!isa<CXXMethodDecl>(D)) {
1286 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1287 break;
1288 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001289
Douglas Gregorc0d24902010-10-22 22:08:47 +00001290 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1291 AllMethodsAreStatic = false;
1292 break;
1293 }
1294 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001295
Douglas Gregorc0d24902010-10-22 22:08:47 +00001296 if (AllMethodsAreStatic)
1297 return true;
1298 }
1299
1300 return false;
1301}
1302
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001303/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001304///
1305/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1306/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001307/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001308///
1309/// Different lookup criteria can find different names. For example, a
1310/// particular scope can have both a struct and a function of the same
1311/// name, and each can be found by certain lookup criteria. For more
1312/// information about lookup criteria, see the documentation for the
1313/// class LookupCriteria.
1314///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001315/// \param R captures both the lookup criteria and any lookup results found.
1316///
1317/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001318/// search. If the lookup criteria permits, name lookup may also search
1319/// in the parent contexts or (for C++ classes) base classes.
1320///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001321/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001322/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001323///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001324/// \returns true if lookup succeeded, false if it failed.
1325bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1326 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001327 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001328
John McCall27b18f82009-11-17 02:14:36 +00001329 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001330 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001331
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001332 // Make sure that the declaration context is complete.
1333 assert((!isa<TagDecl>(LookupCtx) ||
1334 LookupCtx->isDependentContext() ||
1335 cast<TagDecl>(LookupCtx)->isDefinition() ||
1336 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1337 ->isBeingDefined()) &&
1338 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001339
Douglas Gregor34074322009-01-14 22:20:51 +00001340 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001341 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001342 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001343 if (isa<CXXRecordDecl>(LookupCtx))
1344 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001345 return true;
1346 }
Douglas Gregor34074322009-01-14 22:20:51 +00001347
John McCall6538c932009-10-10 05:48:19 +00001348 // Don't descend into implied contexts for redeclarations.
1349 // C++98 [namespace.qual]p6:
1350 // In a declaration for a namespace member in which the
1351 // declarator-id is a qualified-id, given that the qualified-id
1352 // for the namespace member has the form
1353 // nested-name-specifier unqualified-id
1354 // the unqualified-id shall name a member of the namespace
1355 // designated by the nested-name-specifier.
1356 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001357 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001358 return false;
1359
John McCall27b18f82009-11-17 02:14:36 +00001360 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001361 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001362 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001363
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001364 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001365 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001366 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001367 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001368 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001369
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001370 // If we're performing qualified name lookup into a dependent class,
1371 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001372 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001373 // template instantiation time (at which point all bases will be available)
1374 // or we have to fail.
1375 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1376 LookupRec->hasAnyDependentBases()) {
1377 R.setNotFoundInCurrentInstantiation();
1378 return false;
1379 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001380
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001381 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001382 CXXBasePaths Paths;
1383 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001384
1385 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001386 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001387 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001388 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001389 case LookupOrdinaryName:
1390 case LookupMemberName:
1391 case LookupRedeclarationWithLinkage:
1392 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1393 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001394
Douglas Gregor36d1b142009-10-06 17:59:45 +00001395 case LookupTagName:
1396 BaseCallback = &CXXRecordDecl::FindTagMember;
1397 break;
John McCall84d87672009-12-10 09:41:52 +00001398
Douglas Gregor39982192010-08-15 06:18:01 +00001399 case LookupAnyName:
1400 BaseCallback = &LookupAnyMember;
1401 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001402
John McCall84d87672009-12-10 09:41:52 +00001403 case LookupUsingDeclName:
1404 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001405
Douglas Gregor36d1b142009-10-06 17:59:45 +00001406 case LookupOperatorName:
1407 case LookupNamespaceName:
1408 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001409 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001410 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001411 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001412
Douglas Gregor36d1b142009-10-06 17:59:45 +00001413 case LookupNestedNameSpecifierName:
1414 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1415 break;
1416 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001417
John McCall27b18f82009-11-17 02:14:36 +00001418 if (!LookupRec->lookupInBases(BaseCallback,
1419 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001420 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001421
John McCall553c0792010-01-23 00:46:32 +00001422 R.setNamingClass(LookupRec);
1423
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001424 // C++ [class.member.lookup]p2:
1425 // [...] If the resulting set of declarations are not all from
1426 // sub-objects of the same type, or the set has a nonstatic member
1427 // and includes members from distinct sub-objects, there is an
1428 // ambiguity and the program is ill-formed. Otherwise that set is
1429 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001430 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001431 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001432 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001433
Douglas Gregor36d1b142009-10-06 17:59:45 +00001434 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001435 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001436 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001437
John McCall401982f2010-01-20 21:53:11 +00001438 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1439 // across all paths.
1440 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001441
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001442 // Determine whether we're looking at a distinct sub-object or not.
1443 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001444 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001445 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1446 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001447 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001448 }
1449
Douglas Gregorc0d24902010-10-22 22:08:47 +00001450 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001451 != Context.getCanonicalType(PathElement.Base->getType())) {
1452 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001453 // different types. If the declaration sets aren't the same, this
1454 // this lookup is ambiguous.
1455 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1456 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1457 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1458 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001459
Douglas Gregorc0d24902010-10-22 22:08:47 +00001460 while (FirstD != FirstPath->Decls.second &&
1461 CurrentD != Path->Decls.second) {
1462 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1463 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1464 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001465
Douglas Gregorc0d24902010-10-22 22:08:47 +00001466 ++FirstD;
1467 ++CurrentD;
1468 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001469
Douglas Gregorc0d24902010-10-22 22:08:47 +00001470 if (FirstD == FirstPath->Decls.second &&
1471 CurrentD == Path->Decls.second)
1472 continue;
1473 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001474
John McCall9f3059a2009-10-09 21:13:30 +00001475 R.setAmbiguousBaseSubobjectTypes(Paths);
1476 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001477 }
1478
Douglas Gregorc0d24902010-10-22 22:08:47 +00001479 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001480 // We have a different subobject of the same type.
1481
1482 // C++ [class.member.lookup]p5:
1483 // A static member, a nested type or an enumerator defined in
1484 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001485 // has more than one base class subobject of type T.
Douglas Gregorc0d24902010-10-22 22:08:47 +00001486 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001487 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001488
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001489 // We have found a nonstatic member name in multiple, distinct
1490 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001491 R.setAmbiguousBaseSubobjects(Paths);
1492 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001493 }
1494 }
1495
1496 // Lookup in a base class succeeded; return these results.
1497
John McCall9f3059a2009-10-09 21:13:30 +00001498 DeclContext::lookup_iterator I, E;
John McCall553c0792010-01-23 00:46:32 +00001499 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1500 NamedDecl *D = *I;
1501 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1502 D->getAccess());
1503 R.addDecl(D, AS);
1504 }
John McCall9f3059a2009-10-09 21:13:30 +00001505 R.resolveKind();
1506 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001507}
1508
1509/// @brief Performs name lookup for a name that was parsed in the
1510/// source code, and may contain a C++ scope specifier.
1511///
1512/// This routine is a convenience routine meant to be called from
1513/// contexts that receive a name and an optional C++ scope specifier
1514/// (e.g., "N::M::x"). It will then perform either qualified or
1515/// unqualified name lookup (with LookupQualifiedName or LookupName,
1516/// respectively) on the given name and return those results.
1517///
1518/// @param S The scope from which unqualified name lookup will
1519/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001520///
Douglas Gregore861bac2009-08-25 22:51:20 +00001521/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001522///
Douglas Gregore861bac2009-08-25 22:51:20 +00001523/// @param EnteringContext Indicates whether we are going to enter the
1524/// context of the scope-specifier SS (if present).
1525///
John McCall9f3059a2009-10-09 21:13:30 +00001526/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001527bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001528 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001529 if (SS && SS->isInvalid()) {
1530 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001531 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001532 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001533 }
Mike Stump11289f42009-09-09 15:08:12 +00001534
Douglas Gregore861bac2009-08-25 22:51:20 +00001535 if (SS && SS->isSet()) {
1536 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001537 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001538 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001539 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001540 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001541
John McCall27b18f82009-11-17 02:14:36 +00001542 R.setContextRange(SS->getRange());
1543
1544 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001545 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001546
Douglas Gregore861bac2009-08-25 22:51:20 +00001547 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001548 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001549 // Name lookup can't find anything in this case.
John McCall9f3059a2009-10-09 21:13:30 +00001550 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001551 }
1552
Mike Stump11289f42009-09-09 15:08:12 +00001553 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001554 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001555}
1556
Douglas Gregor889ceb72009-02-03 19:21:40 +00001557
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001558/// @brief Produce a diagnostic describing the ambiguity that resulted
1559/// from name lookup.
1560///
1561/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001562///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001563/// @param Name The name of the entity that name lookup was
1564/// searching for.
1565///
1566/// @param NameLoc The location of the name within the source code.
1567///
1568/// @param LookupRange A source range that provides more
1569/// source-location information concerning the lookup itself. For
1570/// example, this range might highlight a nested-name-specifier that
1571/// precedes the name.
1572///
1573/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001574bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001575 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1576
John McCall27b18f82009-11-17 02:14:36 +00001577 DeclarationName Name = Result.getLookupName();
1578 SourceLocation NameLoc = Result.getNameLoc();
1579 SourceRange LookupRange = Result.getContextRange();
1580
John McCall6538c932009-10-10 05:48:19 +00001581 switch (Result.getAmbiguityKind()) {
1582 case LookupResult::AmbiguousBaseSubobjects: {
1583 CXXBasePaths *Paths = Result.getBasePaths();
1584 QualType SubobjectType = Paths->front().back().Base->getType();
1585 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1586 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1587 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001588
John McCall6538c932009-10-10 05:48:19 +00001589 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1590 while (isa<CXXMethodDecl>(*Found) &&
1591 cast<CXXMethodDecl>(*Found)->isStatic())
1592 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001593
John McCall6538c932009-10-10 05:48:19 +00001594 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001595
John McCall6538c932009-10-10 05:48:19 +00001596 return true;
1597 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001598
John McCall6538c932009-10-10 05:48:19 +00001599 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001600 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1601 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001602
John McCall6538c932009-10-10 05:48:19 +00001603 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001604 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001605 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1606 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001607 Path != PathEnd; ++Path) {
1608 Decl *D = *Path->Decls.first;
1609 if (DeclsPrinted.insert(D).second)
1610 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1611 }
1612
Douglas Gregor1c846b02009-01-16 00:38:09 +00001613 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001614 }
1615
John McCall6538c932009-10-10 05:48:19 +00001616 case LookupResult::AmbiguousTagHiding: {
1617 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001618
John McCall6538c932009-10-10 05:48:19 +00001619 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1620
1621 LookupResult::iterator DI, DE = Result.end();
1622 for (DI = Result.begin(); DI != DE; ++DI)
1623 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1624 TagDecls.insert(TD);
1625 Diag(TD->getLocation(), diag::note_hidden_tag);
1626 }
1627
1628 for (DI = Result.begin(); DI != DE; ++DI)
1629 if (!isa<TagDecl>(*DI))
1630 Diag((*DI)->getLocation(), diag::note_hiding_object);
1631
1632 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001633 LookupResult::Filter F = Result.makeFilter();
1634 while (F.hasNext()) {
1635 if (TagDecls.count(F.next()))
1636 F.erase();
1637 }
1638 F.done();
John McCall6538c932009-10-10 05:48:19 +00001639
1640 return true;
1641 }
1642
1643 case LookupResult::AmbiguousReference: {
1644 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001645
John McCall6538c932009-10-10 05:48:19 +00001646 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1647 for (; DI != DE; ++DI)
1648 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001649
John McCall6538c932009-10-10 05:48:19 +00001650 return true;
1651 }
1652 }
1653
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001654 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001655 return true;
1656}
Douglas Gregore254f902009-02-04 00:32:51 +00001657
John McCallf24d7bb2010-05-28 18:45:08 +00001658namespace {
1659 struct AssociatedLookup {
1660 AssociatedLookup(Sema &S,
1661 Sema::AssociatedNamespaceSet &Namespaces,
1662 Sema::AssociatedClassSet &Classes)
1663 : S(S), Namespaces(Namespaces), Classes(Classes) {
1664 }
1665
1666 Sema &S;
1667 Sema::AssociatedNamespaceSet &Namespaces;
1668 Sema::AssociatedClassSet &Classes;
1669 };
1670}
1671
Mike Stump11289f42009-09-09 15:08:12 +00001672static void
John McCallf24d7bb2010-05-28 18:45:08 +00001673addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001674
Douglas Gregor8b895222010-04-30 07:08:38 +00001675static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1676 DeclContext *Ctx) {
1677 // Add the associated namespace for this class.
1678
1679 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1680 // be a locally scoped record.
1681
Sebastian Redlbd595762010-08-31 20:53:31 +00001682 // We skip out of inline namespaces. The innermost non-inline namespace
1683 // contains all names of all its nested inline namespaces anyway, so we can
1684 // replace the entire inline namespace tree with its root.
1685 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1686 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00001687 Ctx = Ctx->getParent();
1688
John McCallc7e8e792009-08-07 22:18:02 +00001689 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001690 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001691}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001692
Mike Stump11289f42009-09-09 15:08:12 +00001693// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001694// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001695static void
John McCallf24d7bb2010-05-28 18:45:08 +00001696addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1697 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001698 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001699 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001700 switch (Arg.getKind()) {
1701 case TemplateArgument::Null:
1702 break;
Mike Stump11289f42009-09-09 15:08:12 +00001703
Douglas Gregor197e5f72009-07-08 07:51:57 +00001704 case TemplateArgument::Type:
1705 // [...] the namespaces and classes associated with the types of the
1706 // template arguments provided for template type parameters (excluding
1707 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001708 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001709 break;
Mike Stump11289f42009-09-09 15:08:12 +00001710
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001711 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001712 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00001713 // [...] the namespaces in which any template template arguments are
1714 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001715 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001716 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00001717 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001718 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001719 DeclContext *Ctx = ClassTemplate->getDeclContext();
1720 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001721 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001722 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001723 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001724 }
1725 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001726 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001727
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001728 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001729 case TemplateArgument::Integral:
1730 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001731 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001732 // associated namespaces. ]
1733 break;
Mike Stump11289f42009-09-09 15:08:12 +00001734
Douglas Gregor197e5f72009-07-08 07:51:57 +00001735 case TemplateArgument::Pack:
1736 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1737 PEnd = Arg.pack_end();
1738 P != PEnd; ++P)
John McCallf24d7bb2010-05-28 18:45:08 +00001739 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001740 break;
1741 }
1742}
1743
Douglas Gregore254f902009-02-04 00:32:51 +00001744// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001745// argument-dependent lookup with an argument of class type
1746// (C++ [basic.lookup.koenig]p2).
1747static void
John McCallf24d7bb2010-05-28 18:45:08 +00001748addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1749 CXXRecordDecl *Class) {
1750
1751 // Just silently ignore anything whose name is __va_list_tag.
1752 if (Class->getDeclName() == Result.S.VAListTagName)
1753 return;
1754
Douglas Gregore254f902009-02-04 00:32:51 +00001755 // C++ [basic.lookup.koenig]p2:
1756 // [...]
1757 // -- If T is a class type (including unions), its associated
1758 // classes are: the class itself; the class of which it is a
1759 // member, if any; and its direct and indirect base
1760 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001761 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001762
1763 // Add the class of which it is a member, if any.
1764 DeclContext *Ctx = Class->getDeclContext();
1765 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001766 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001767 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001768 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001769
Douglas Gregore254f902009-02-04 00:32:51 +00001770 // Add the class itself. If we've already seen this class, we don't
1771 // need to visit base classes.
John McCallf24d7bb2010-05-28 18:45:08 +00001772 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00001773 return;
1774
Mike Stump11289f42009-09-09 15:08:12 +00001775 // -- If T is a template-id, its associated namespaces and classes are
1776 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001777 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001778 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001779 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001780 // namespaces in which any template template arguments are defined; and
1781 // the classes in which any member templates used as template template
1782 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001783 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001784 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001785 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1786 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1787 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001788 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001789 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001790 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001791
Douglas Gregor197e5f72009-07-08 07:51:57 +00001792 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1793 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00001794 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001795 }
Mike Stump11289f42009-09-09 15:08:12 +00001796
John McCall67da35c2010-02-04 22:26:26 +00001797 // Only recurse into base classes for complete types.
1798 if (!Class->hasDefinition()) {
1799 // FIXME: we might need to instantiate templates here
1800 return;
1801 }
1802
Douglas Gregore254f902009-02-04 00:32:51 +00001803 // Add direct and indirect base classes along with their associated
1804 // namespaces.
1805 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1806 Bases.push_back(Class);
1807 while (!Bases.empty()) {
1808 // Pop this class off the stack.
1809 Class = Bases.back();
1810 Bases.pop_back();
1811
1812 // Visit the base classes.
1813 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1814 BaseEnd = Class->bases_end();
1815 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001816 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001817 // In dependent contexts, we do ADL twice, and the first time around,
1818 // the base type might be a dependent TemplateSpecializationType, or a
1819 // TemplateTypeParmType. If that happens, simply ignore it.
1820 // FIXME: If we want to support export, we probably need to add the
1821 // namespace of the template in a TemplateSpecializationType, or even
1822 // the classes and namespaces of known non-dependent arguments.
1823 if (!BaseType)
1824 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001825 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001826 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00001827 // Find the associated namespace for this base class.
1828 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00001829 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001830
1831 // Make sure we visit the bases of this base class.
1832 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1833 Bases.push_back(BaseDecl);
1834 }
1835 }
1836 }
1837}
1838
1839// \brief Add the associated classes and namespaces for
1840// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001841// (C++ [basic.lookup.koenig]p2).
1842static void
John McCallf24d7bb2010-05-28 18:45:08 +00001843addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00001844 // C++ [basic.lookup.koenig]p2:
1845 //
1846 // For each argument type T in the function call, there is a set
1847 // of zero or more associated namespaces and a set of zero or more
1848 // associated classes to be considered. The sets of namespaces and
1849 // classes is determined entirely by the types of the function
1850 // arguments (and the namespace of any template template
1851 // argument). Typedef names and using-declarations used to specify
1852 // the types do not contribute to this set. The sets of namespaces
1853 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00001854
John McCall0af3d3b2010-05-28 06:08:54 +00001855 llvm::SmallVector<const Type *, 16> Queue;
1856 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1857
Douglas Gregore254f902009-02-04 00:32:51 +00001858 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00001859 switch (T->getTypeClass()) {
1860
1861#define TYPE(Class, Base)
1862#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1863#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1864#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1865#define ABSTRACT_TYPE(Class, Base)
1866#include "clang/AST/TypeNodes.def"
1867 // T is canonical. We can also ignore dependent types because
1868 // we don't need to do ADL at the definition point, but if we
1869 // wanted to implement template export (or if we find some other
1870 // use for associated classes and namespaces...) this would be
1871 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00001872 break;
Douglas Gregore254f902009-02-04 00:32:51 +00001873
John McCall0af3d3b2010-05-28 06:08:54 +00001874 // -- If T is a pointer to U or an array of U, its associated
1875 // namespaces and classes are those associated with U.
1876 case Type::Pointer:
1877 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1878 continue;
1879 case Type::ConstantArray:
1880 case Type::IncompleteArray:
1881 case Type::VariableArray:
1882 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1883 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001884
John McCall0af3d3b2010-05-28 06:08:54 +00001885 // -- If T is a fundamental type, its associated sets of
1886 // namespaces and classes are both empty.
1887 case Type::Builtin:
1888 break;
1889
1890 // -- If T is a class type (including unions), its associated
1891 // classes are: the class itself; the class of which it is a
1892 // member, if any; and its direct and indirect base
1893 // classes. Its associated namespaces are the namespaces in
1894 // which its associated classes are defined.
1895 case Type::Record: {
1896 CXXRecordDecl *Class
1897 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001898 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00001899 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00001900 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00001901
John McCall0af3d3b2010-05-28 06:08:54 +00001902 // -- If T is an enumeration type, its associated namespace is
1903 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001904 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00001905 // it has no associated class.
1906 case Type::Enum: {
1907 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001908
John McCall0af3d3b2010-05-28 06:08:54 +00001909 DeclContext *Ctx = Enum->getDeclContext();
1910 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001911 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001912
John McCall0af3d3b2010-05-28 06:08:54 +00001913 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001914 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001915
John McCall0af3d3b2010-05-28 06:08:54 +00001916 break;
1917 }
1918
1919 // -- If T is a function type, its associated namespaces and
1920 // classes are those associated with the function parameter
1921 // types and those associated with the return type.
1922 case Type::FunctionProto: {
1923 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1924 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1925 ArgEnd = Proto->arg_type_end();
1926 Arg != ArgEnd; ++Arg)
1927 Queue.push_back(Arg->getTypePtr());
1928 // fallthrough
1929 }
1930 case Type::FunctionNoProto: {
1931 const FunctionType *FnType = cast<FunctionType>(T);
1932 T = FnType->getResultType().getTypePtr();
1933 continue;
1934 }
1935
1936 // -- If T is a pointer to a member function of a class X, its
1937 // associated namespaces and classes are those associated
1938 // with the function parameter types and return type,
1939 // together with those associated with X.
1940 //
1941 // -- If T is a pointer to a data member of class X, its
1942 // associated namespaces and classes are those associated
1943 // with the member type together with those associated with
1944 // X.
1945 case Type::MemberPointer: {
1946 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1947
1948 // Queue up the class type into which this points.
1949 Queue.push_back(MemberPtr->getClass());
1950
1951 // And directly continue with the pointee type.
1952 T = MemberPtr->getPointeeType().getTypePtr();
1953 continue;
1954 }
1955
1956 // As an extension, treat this like a normal pointer.
1957 case Type::BlockPointer:
1958 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1959 continue;
1960
1961 // References aren't covered by the standard, but that's such an
1962 // obvious defect that we cover them anyway.
1963 case Type::LValueReference:
1964 case Type::RValueReference:
1965 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1966 continue;
1967
1968 // These are fundamental types.
1969 case Type::Vector:
1970 case Type::ExtVector:
1971 case Type::Complex:
1972 break;
1973
Douglas Gregor8e936662011-04-12 01:02:45 +00001974 // If T is an Objective-C object or interface type, or a pointer to an
1975 // object or interface type, the associated namespace is the global
1976 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00001977 case Type::ObjCObject:
1978 case Type::ObjCInterface:
1979 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00001980 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00001981 break;
1982 }
1983
1984 if (Queue.empty()) break;
1985 T = Queue.back();
1986 Queue.pop_back();
Douglas Gregore254f902009-02-04 00:32:51 +00001987 }
Douglas Gregore254f902009-02-04 00:32:51 +00001988}
1989
1990/// \brief Find the associated classes and namespaces for
1991/// argument-dependent lookup for a call with the given set of
1992/// arguments.
1993///
1994/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00001995/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00001996/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00001997void
Douglas Gregore254f902009-02-04 00:32:51 +00001998Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1999 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00002000 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002001 AssociatedNamespaces.clear();
2002 AssociatedClasses.clear();
2003
John McCallf24d7bb2010-05-28 18:45:08 +00002004 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
2005
Douglas Gregore254f902009-02-04 00:32:51 +00002006 // C++ [basic.lookup.koenig]p2:
2007 // For each argument type T in the function call, there is a set
2008 // of zero or more associated namespaces and a set of zero or more
2009 // associated classes to be considered. The sets of namespaces and
2010 // classes is determined entirely by the types of the function
2011 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002012 // argument).
Douglas Gregore254f902009-02-04 00:32:51 +00002013 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
2014 Expr *Arg = Args[ArgIdx];
2015
2016 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002017 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002018 continue;
2019 }
2020
2021 // [...] In addition, if the argument is the name or address of a
2022 // set of overloaded functions and/or function templates, its
2023 // associated classes and namespaces are the union of those
2024 // associated with each of the members of the set: the namespace
2025 // in which the function or function template is defined and the
2026 // classes and namespaces associated with its (non-dependent)
2027 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002028 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002029 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002030 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002031 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002032
John McCallf24d7bb2010-05-28 18:45:08 +00002033 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2034 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002035
John McCallf24d7bb2010-05-28 18:45:08 +00002036 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2037 I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002038 // Look through any using declarations to find the underlying function.
2039 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002040
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002041 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2042 if (!FDecl)
2043 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002044
2045 // Add the classes and namespaces associated with the parameter
2046 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002047 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002048 }
2049 }
2050}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002051
2052/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2053/// an acceptable non-member overloaded operator for a call whose
2054/// arguments have types T1 (and, if non-empty, T2). This routine
2055/// implements the check in C++ [over.match.oper]p3b2 concerning
2056/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00002057static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002058IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2059 QualType T1, QualType T2,
2060 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00002061 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2062 return true;
2063
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002064 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2065 return true;
2066
John McCall9dd450b2009-09-21 23:43:11 +00002067 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002068 if (Proto->getNumArgs() < 1)
2069 return false;
2070
2071 if (T1->isEnumeralType()) {
2072 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002073 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002074 return true;
2075 }
2076
2077 if (Proto->getNumArgs() < 2)
2078 return false;
2079
2080 if (!T2.isNull() && T2->isEnumeralType()) {
2081 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002082 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002083 return true;
2084 }
2085
2086 return false;
2087}
2088
John McCall5cebab12009-11-18 07:57:50 +00002089NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002090 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002091 LookupNameKind NameKind,
2092 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002093 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002094 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002095 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002096}
2097
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002098/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002099ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002100 SourceLocation IdLoc) {
2101 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2102 LookupObjCProtocolName);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002103 return cast_or_null<ObjCProtocolDecl>(D);
2104}
2105
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002106void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002107 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002108 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002109 // C++ [over.match.oper]p3:
2110 // -- The set of non-member candidates is the result of the
2111 // unqualified lookup of operator@ in the context of the
2112 // expression according to the usual rules for name lookup in
2113 // unqualified function calls (3.4.2) except that all member
2114 // functions are ignored. However, if no operand has a class
2115 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00002116 // that have a first parameter of type T1 or "reference to
2117 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002118 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00002119 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002120 // when T2 is an enumeration type, are candidate functions.
2121 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002122 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2123 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002124
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002125 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2126
John McCall9f3059a2009-10-09 21:13:30 +00002127 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002128 return;
2129
2130 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2131 Op != OpEnd; ++Op) {
Douglas Gregor645d76f2010-04-25 20:25:43 +00002132 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2133 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002134 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor645d76f2010-04-25 20:25:43 +00002135 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00002136 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor645d76f2010-04-25 20:25:43 +00002137 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor15448f82009-06-27 21:05:07 +00002138 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00002139 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00002140 // later?
2141 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor645d76f2010-04-25 20:25:43 +00002142 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor15448f82009-06-27 21:05:07 +00002143 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002144 }
2145}
2146
Alexis Hunt1da39282011-06-24 02:11:39 +00002147Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002148 CXXSpecialMember SM,
2149 bool ConstArg,
2150 bool VolatileArg,
2151 bool RValueThis,
2152 bool ConstThis,
2153 bool VolatileThis) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002154 RD = RD->getDefinition();
2155 assert((RD && !RD->isBeingDefined()) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002156 "doing special member lookup into record that isn't fully complete");
2157 if (RValueThis || ConstThis || VolatileThis)
2158 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2159 "constructors and destructors always have unqualified lvalue this");
2160 if (ConstArg || VolatileArg)
2161 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2162 "parameter-less special members can't have qualified arguments");
2163
2164 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002165 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002166 ID.AddInteger(SM);
2167 ID.AddInteger(ConstArg);
2168 ID.AddInteger(VolatileArg);
2169 ID.AddInteger(RValueThis);
2170 ID.AddInteger(ConstThis);
2171 ID.AddInteger(VolatileThis);
2172
2173 void *InsertPoint;
2174 SpecialMemberOverloadResult *Result =
2175 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2176
2177 // This was already cached
2178 if (Result)
2179 return Result;
2180
Alexis Huntba8e18d2011-06-07 00:11:58 +00002181 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2182 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002183 SpecialMemberCache.InsertNode(Result, InsertPoint);
2184
2185 if (SM == CXXDestructor) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002186 if (!RD->hasDeclaredDestructor())
2187 DeclareImplicitDestructor(RD);
2188 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002189 assert(DD && "record without a destructor");
2190 Result->setMethod(DD);
2191 Result->setSuccess(DD->isDeleted());
2192 Result->setConstParamMatch(false);
2193 return Result;
2194 }
2195
Alexis Hunteef8ee02011-06-10 03:50:41 +00002196 // Prepare for overload resolution. Here we construct a synthetic argument
2197 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002198 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002199 DeclarationName Name;
2200 Expr *Arg = 0;
2201 unsigned NumArgs;
2202
2203 if (SM == CXXDefaultConstructor) {
2204 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2205 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002206 if (RD->needsImplicitDefaultConstructor())
2207 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002208 } else {
2209 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2210 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Alexis Hunt1da39282011-06-24 02:11:39 +00002211 if (!RD->hasDeclaredCopyConstructor())
2212 DeclareImplicitCopyConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002213 // TODO: Move constructors
2214 } else {
2215 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Alexis Hunt1da39282011-06-24 02:11:39 +00002216 if (!RD->hasDeclaredCopyAssignment())
2217 DeclareImplicitCopyAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002218 // TODO: Move assignment
2219 }
2220
2221 QualType ArgType = CanTy;
2222 if (ConstArg)
2223 ArgType.addConst();
2224 if (VolatileArg)
2225 ArgType.addVolatile();
2226
2227 // This isn't /really/ specified by the standard, but it's implied
2228 // we should be working from an RValue in the case of move to ensure
2229 // that we prefer to bind to rvalue references, and an LValue in the
2230 // case of copy to ensure we don't bind to rvalue references.
2231 // Possibly an XValue is actually correct in the case of move, but
2232 // there is no semantic difference for class types in this restricted
2233 // case.
2234 ExprValueKind VK;
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002235 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002236 VK = VK_LValue;
2237 else
2238 VK = VK_RValue;
2239
2240 NumArgs = 1;
2241 Arg = new (Context) OpaqueValueExpr(SourceLocation(), ArgType, VK);
2242 }
2243
2244 // Create the object argument
2245 QualType ThisTy = CanTy;
2246 if (ConstThis)
2247 ThisTy.addConst();
2248 if (VolatileThis)
2249 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002250 Expr::Classification Classification =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002251 (new (Context) OpaqueValueExpr(SourceLocation(), ThisTy,
2252 RValueThis ? VK_RValue : VK_LValue))->
2253 Classify(Context);
2254
2255 // Now we perform lookup on the name we computed earlier and do overload
2256 // resolution. Lookup is only performed directly into the class since there
2257 // will always be a (possibly implicit) declaration to shadow any others.
2258 OverloadCandidateSet OCS((SourceLocation()));
2259 DeclContext::lookup_iterator I, E;
2260 Result->setConstParamMatch(false);
2261
Alexis Hunt1da39282011-06-24 02:11:39 +00002262 llvm::tie(I, E) = RD->lookup(Name);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002263 assert((I != E) &&
2264 "lookup for a constructor or assignment operator was empty");
2265 for ( ; I != E; ++I) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002266 Decl *Cand = *I;
Alexis Hunt080709f2011-06-23 00:26:20 +00002267
Alexis Hunt1da39282011-06-24 02:11:39 +00002268 if (Cand->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002269 continue;
2270
Alexis Hunt1da39282011-06-24 02:11:39 +00002271 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2272 // FIXME: [namespace.udecl]p15 says that we should only consider a
2273 // using declaration here if it does not match a declaration in the
2274 // derived class. We do not implement this correctly in other cases
2275 // either.
2276 Cand = U->getTargetDecl();
2277
2278 if (Cand->isInvalidDecl())
2279 continue;
2280 }
2281
2282 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002283 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Alexis Hunt1da39282011-06-24 02:11:39 +00002284 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Alexis Hunt080709f2011-06-23 00:26:20 +00002285 Classification, &Arg, NumArgs, OCS, true);
2286 else
2287 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public), &Arg,
2288 NumArgs, OCS, true);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002289
2290 // Here we're looking for a const parameter to speed up creation of
2291 // implicit copy methods.
2292 if ((SM == CXXCopyAssignment && M->isCopyAssignmentOperator()) ||
2293 (SM == CXXCopyConstructor &&
2294 cast<CXXConstructorDecl>(M)->isCopyConstructor())) {
2295 QualType ArgType = M->getType()->getAs<FunctionProtoType>()->getArgType(0);
Alexis Hunt491ec602011-06-21 23:42:56 +00002296 if (!ArgType->isReferenceType() ||
2297 ArgType->getPointeeType().isConstQualified())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002298 Result->setConstParamMatch(true);
2299 }
Alexis Hunt2949f022011-06-22 02:58:46 +00002300 } else if (FunctionTemplateDecl *Tmpl =
Alexis Hunt1da39282011-06-24 02:11:39 +00002301 dyn_cast<FunctionTemplateDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002302 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2303 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Alexis Hunt1da39282011-06-24 02:11:39 +00002304 RD, 0, ThisTy, Classification, &Arg, NumArgs,
Alexis Hunt080709f2011-06-23 00:26:20 +00002305 OCS, true);
2306 else
2307 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
2308 0, &Arg, NumArgs, OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002309 } else {
2310 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002311 }
2312 }
2313
2314 OverloadCandidateSet::iterator Best;
2315 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2316 case OR_Success:
2317 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2318 Result->setSuccess(true);
2319 break;
2320
2321 case OR_Deleted:
2322 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2323 Result->setSuccess(false);
2324 break;
2325
2326 case OR_Ambiguous:
2327 case OR_No_Viable_Function:
2328 Result->setMethod(0);
2329 Result->setSuccess(false);
2330 break;
2331 }
2332
2333 return Result;
2334}
2335
2336/// \brief Look up the default constructor for the given class.
2337CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002338 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002339 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2340 false, false);
2341
2342 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002343}
2344
Alexis Hunt491ec602011-06-21 23:42:56 +00002345/// \brief Look up the copying constructor for the given class.
2346CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
2347 unsigned Quals,
2348 bool *ConstParamMatch) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002349 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2350 "non-const, non-volatile qualifiers for copy ctor arg");
2351 SpecialMemberOverloadResult *Result =
2352 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2353 Quals & Qualifiers::Volatile, false, false, false);
2354
2355 if (ConstParamMatch)
2356 *ConstParamMatch = Result->hasConstParamMatch();
2357
2358 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2359}
2360
Douglas Gregor52b72822010-07-02 23:12:18 +00002361/// \brief Look up the constructors for the given class.
2362DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002363 // If the implicit constructors have not yet been declared, do so now.
Douglas Gregor9672f922010-07-03 00:47:00 +00002364 if (CanDeclareSpecialMemberFunction(Context, Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00002365 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002366 DeclareImplicitDefaultConstructor(Class);
2367 if (!Class->hasDeclaredCopyConstructor())
2368 DeclareImplicitCopyConstructor(Class);
2369 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002370
Douglas Gregor52b72822010-07-02 23:12:18 +00002371 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2372 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2373 return Class->lookup(Name);
2374}
2375
Alexis Hunt491ec602011-06-21 23:42:56 +00002376/// \brief Look up the copying assignment operator for the given class.
2377CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2378 unsigned Quals, bool RValueThis,
2379 unsigned ThisQuals,
2380 bool *ConstParamMatch) {
2381 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2382 "non-const, non-volatile qualifiers for copy assignment arg");
2383 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2384 "non-const, non-volatile qualifiers for copy assignment this");
2385 SpecialMemberOverloadResult *Result =
2386 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2387 Quals & Qualifiers::Volatile, RValueThis,
2388 ThisQuals & Qualifiers::Const,
2389 ThisQuals & Qualifiers::Volatile);
2390
2391 if (ConstParamMatch)
2392 *ConstParamMatch = Result->hasConstParamMatch();
2393
2394 return Result->getMethod();
2395}
2396
Douglas Gregore71edda2010-07-01 22:47:18 +00002397/// \brief Look for the destructor of the given class.
2398///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00002399/// During semantic analysis, this routine should be used in lieu of
2400/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00002401///
2402/// \returns The destructor for this class.
2403CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002404 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2405 false, false, false,
2406 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00002407}
2408
John McCall8fe68082010-01-26 07:16:45 +00002409void ADLResult::insert(NamedDecl *New) {
2410 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2411
2412 // If we haven't yet seen a decl for this key, or the last decl
2413 // was exactly this one, we're done.
2414 if (Old == 0 || Old == New) {
2415 Old = New;
2416 return;
2417 }
2418
2419 // Otherwise, decide which is a more recent redeclaration.
2420 FunctionDecl *OldFD, *NewFD;
2421 if (isa<FunctionTemplateDecl>(New)) {
2422 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2423 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2424 } else {
2425 OldFD = cast<FunctionDecl>(Old);
2426 NewFD = cast<FunctionDecl>(New);
2427 }
2428
2429 FunctionDecl *Cursor = NewFD;
2430 while (true) {
2431 Cursor = Cursor->getPreviousDeclaration();
2432
2433 // If we got to the end without finding OldFD, OldFD is the newer
2434 // declaration; leave things as they are.
2435 if (!Cursor) return;
2436
2437 // If we do find OldFD, then NewFD is newer.
2438 if (Cursor == OldFD) break;
2439
2440 // Otherwise, keep looking.
2441 }
2442
2443 Old = New;
2444}
2445
Sebastian Redlc057f422009-10-23 19:23:15 +00002446void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002447 Expr **Args, unsigned NumArgs,
Richard Smith02e85f32011-04-14 22:09:26 +00002448 ADLResult &Result,
2449 bool StdNamespaceIsAssociated) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002450 // Find all of the associated namespaces and classes based on the
2451 // arguments we have.
2452 AssociatedNamespaceSet AssociatedNamespaces;
2453 AssociatedClassSet AssociatedClasses;
Mike Stump11289f42009-09-09 15:08:12 +00002454 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCallc7e8e792009-08-07 22:18:02 +00002455 AssociatedNamespaces,
2456 AssociatedClasses);
Richard Smith02e85f32011-04-14 22:09:26 +00002457 if (StdNamespaceIsAssociated && StdNamespace)
2458 AssociatedNamespaces.insert(getStdNamespace());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002459
Sebastian Redlc057f422009-10-23 19:23:15 +00002460 QualType T1, T2;
2461 if (Operator) {
2462 T1 = Args[0]->getType();
2463 if (NumArgs >= 2)
2464 T2 = Args[1]->getType();
2465 }
2466
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002467 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002468 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2469 // and let Y be the lookup set produced by argument dependent
2470 // lookup (defined as follows). If X contains [...] then Y is
2471 // empty. Otherwise Y is the set of declarations found in the
2472 // namespaces associated with the argument types as described
2473 // below. The set of declarations found by the lookup of the name
2474 // is the union of X and Y.
2475 //
2476 // Here, we compute Y and add its members to the overloaded
2477 // candidate set.
2478 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00002479 NSEnd = AssociatedNamespaces.end();
2480 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002481 // When considering an associated namespace, the lookup is the
2482 // same as the lookup performed when the associated namespace is
2483 // used as a qualifier (3.4.3.2) except that:
2484 //
2485 // -- Any using-directives in the associated namespace are
2486 // ignored.
2487 //
John McCallc7e8e792009-08-07 22:18:02 +00002488 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002489 // associated classes are visible within their respective
2490 // namespaces even if they are not visible during an ordinary
2491 // lookup (11.4).
2492 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00002493 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00002494 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00002495 // If the only declaration here is an ordinary friend, consider
2496 // it only if it was declared in an associated classes.
2497 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00002498 DeclContext *LexDC = D->getLexicalDeclContext();
2499 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2500 continue;
2501 }
Mike Stump11289f42009-09-09 15:08:12 +00002502
John McCall91f61fc2010-01-26 06:04:06 +00002503 if (isa<UsingShadowDecl>(D))
2504 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002505
John McCall91f61fc2010-01-26 06:04:06 +00002506 if (isa<FunctionDecl>(D)) {
2507 if (Operator &&
2508 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2509 T1, T2, Context))
2510 continue;
John McCall8fe68082010-01-26 07:16:45 +00002511 } else if (!isa<FunctionTemplateDecl>(D))
2512 continue;
2513
2514 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002515 }
2516 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002517}
Douglas Gregor2d435302009-12-30 17:04:44 +00002518
2519//----------------------------------------------------------------------------
2520// Search for all visible declarations.
2521//----------------------------------------------------------------------------
2522VisibleDeclConsumer::~VisibleDeclConsumer() { }
2523
2524namespace {
2525
2526class ShadowContextRAII;
2527
2528class VisibleDeclsRecord {
2529public:
2530 /// \brief An entry in the shadow map, which is optimized to store a
2531 /// single declaration (the common case) but can also store a list
2532 /// of declarations.
2533 class ShadowMapEntry {
2534 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002535
Douglas Gregor2d435302009-12-30 17:04:44 +00002536 /// \brief Contains either the solitary NamedDecl * or a vector
2537 /// of declarations.
2538 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2539
2540 public:
2541 ShadowMapEntry() : DeclOrVector() { }
2542
2543 void Add(NamedDecl *ND);
2544 void Destroy();
2545
2546 // Iteration.
Argyrios Kyrtzidis12f146a2011-02-19 04:02:34 +00002547 typedef NamedDecl * const *iterator;
Douglas Gregor2d435302009-12-30 17:04:44 +00002548 iterator begin();
2549 iterator end();
2550 };
2551
2552private:
2553 /// \brief A mapping from declaration names to the declarations that have
2554 /// this name within a particular scope.
2555 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2556
2557 /// \brief A list of shadow maps, which is used to model name hiding.
2558 std::list<ShadowMap> ShadowMaps;
2559
2560 /// \brief The declaration contexts we have already visited.
2561 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2562
2563 friend class ShadowContextRAII;
2564
2565public:
2566 /// \brief Determine whether we have already visited this context
2567 /// (and, if not, note that we are going to visit that context now).
2568 bool visitedContext(DeclContext *Ctx) {
2569 return !VisitedContexts.insert(Ctx);
2570 }
2571
Douglas Gregor39982192010-08-15 06:18:01 +00002572 bool alreadyVisitedContext(DeclContext *Ctx) {
2573 return VisitedContexts.count(Ctx);
2574 }
2575
Douglas Gregor2d435302009-12-30 17:04:44 +00002576 /// \brief Determine whether the given declaration is hidden in the
2577 /// current scope.
2578 ///
2579 /// \returns the declaration that hides the given declaration, or
2580 /// NULL if no such declaration exists.
2581 NamedDecl *checkHidden(NamedDecl *ND);
2582
2583 /// \brief Add a declaration to the current shadow map.
2584 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2585};
2586
2587/// \brief RAII object that records when we've entered a shadow context.
2588class ShadowContextRAII {
2589 VisibleDeclsRecord &Visible;
2590
2591 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2592
2593public:
2594 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2595 Visible.ShadowMaps.push_back(ShadowMap());
2596 }
2597
2598 ~ShadowContextRAII() {
2599 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2600 EEnd = Visible.ShadowMaps.back().end();
2601 E != EEnd;
2602 ++E)
2603 E->second.Destroy();
2604
2605 Visible.ShadowMaps.pop_back();
2606 }
2607};
2608
2609} // end anonymous namespace
2610
2611void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2612 if (DeclOrVector.isNull()) {
2613 // 0 - > 1 elements: just set the single element information.
2614 DeclOrVector = ND;
2615 return;
2616 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002617
Douglas Gregor2d435302009-12-30 17:04:44 +00002618 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2619 // 1 -> 2 elements: create the vector of results and push in the
2620 // existing declaration.
2621 DeclVector *Vec = new DeclVector;
2622 Vec->push_back(PrevND);
2623 DeclOrVector = Vec;
2624 }
2625
2626 // Add the new element to the end of the vector.
2627 DeclOrVector.get<DeclVector*>()->push_back(ND);
2628}
2629
2630void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2631 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2632 delete Vec;
2633 DeclOrVector = ((NamedDecl *)0);
2634 }
2635}
2636
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002637VisibleDeclsRecord::ShadowMapEntry::iterator
Douglas Gregor2d435302009-12-30 17:04:44 +00002638VisibleDeclsRecord::ShadowMapEntry::begin() {
2639 if (DeclOrVector.isNull())
2640 return 0;
2641
Argyrios Kyrtzidis12f146a2011-02-19 04:02:34 +00002642 if (DeclOrVector.is<NamedDecl *>())
2643 return DeclOrVector.getAddrOf<NamedDecl *>();
Douglas Gregor2d435302009-12-30 17:04:44 +00002644
2645 return DeclOrVector.get<DeclVector *>()->begin();
2646}
2647
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002648VisibleDeclsRecord::ShadowMapEntry::iterator
Douglas Gregor2d435302009-12-30 17:04:44 +00002649VisibleDeclsRecord::ShadowMapEntry::end() {
2650 if (DeclOrVector.isNull())
2651 return 0;
2652
Chandler Carruth38a32822011-05-02 18:54:36 +00002653 if (DeclOrVector.is<NamedDecl *>())
2654 return DeclOrVector.getAddrOf<NamedDecl *>() + 1;
Douglas Gregor2d435302009-12-30 17:04:44 +00002655
2656 return DeclOrVector.get<DeclVector *>()->end();
2657}
2658
2659NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002660 // Look through using declarations.
2661 ND = ND->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002662
Douglas Gregor2d435302009-12-30 17:04:44 +00002663 unsigned IDNS = ND->getIdentifierNamespace();
2664 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2665 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2666 SM != SMEnd; ++SM) {
2667 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2668 if (Pos == SM->end())
2669 continue;
2670
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002671 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor2d435302009-12-30 17:04:44 +00002672 IEnd = Pos->second.end();
2673 I != IEnd; ++I) {
2674 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +00002675 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002676 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00002677 Decl::IDNS_ObjCProtocol)))
2678 continue;
2679
2680 // Protocols are in distinct namespaces from everything else.
2681 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2682 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2683 (*I)->getIdentifierNamespace() != IDNS)
2684 continue;
2685
Douglas Gregor09bbc652010-01-14 15:47:35 +00002686 // Functions and function templates in the same scope overload
2687 // rather than hide. FIXME: Look for hiding based on function
2688 // signatures!
Douglas Gregor200c99d2010-01-14 03:35:48 +00002689 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002690 ND->isFunctionOrFunctionTemplate() &&
2691 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002692 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002693
Douglas Gregor2d435302009-12-30 17:04:44 +00002694 // We've found a declaration that hides this one.
2695 return *I;
2696 }
2697 }
2698
2699 return 0;
2700}
2701
2702static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2703 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002704 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002705 VisibleDeclConsumer &Consumer,
2706 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002707 if (!Ctx)
2708 return;
2709
Douglas Gregor2d435302009-12-30 17:04:44 +00002710 // Make sure we don't visit the same context twice.
2711 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2712 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002713
Douglas Gregor7454c562010-07-02 20:37:36 +00002714 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2715 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2716
Douglas Gregor2d435302009-12-30 17:04:44 +00002717 // Enumerate all of the results in this context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002718 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
Douglas Gregor2d435302009-12-30 17:04:44 +00002719 CurCtx = CurCtx->getNextContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002720 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
Douglas Gregor2d435302009-12-30 17:04:44 +00002721 DEnd = CurCtx->decls_end();
2722 D != DEnd; ++D) {
Douglas Gregora3b23b02010-12-09 21:44:02 +00002723 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002724 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002725 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002726 Visited.add(ND);
2727 }
Douglas Gregora3b23b02010-12-09 21:44:02 +00002728 } else if (ObjCForwardProtocolDecl *ForwardProto
2729 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
2730 for (ObjCForwardProtocolDecl::protocol_iterator
2731 P = ForwardProto->protocol_begin(),
2732 PEnd = ForwardProto->protocol_end();
2733 P != PEnd;
2734 ++P) {
2735 if (Result.isAcceptableDecl(*P)) {
2736 Consumer.FoundDecl(*P, Visited.checkHidden(*P), InBaseClass);
2737 Visited.add(*P);
2738 }
2739 }
Douglas Gregor04246572011-02-16 01:39:26 +00002740 } else if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D)) {
2741 for (ObjCClassDecl::iterator I = Class->begin(), IEnd = Class->end();
2742 I != IEnd; ++I) {
2743 ObjCInterfaceDecl *IFace = I->getInterface();
2744 if (Result.isAcceptableDecl(IFace)) {
2745 Consumer.FoundDecl(IFace, Visited.checkHidden(IFace), InBaseClass);
2746 Visited.add(IFace);
2747 }
2748 }
Douglas Gregora3b23b02010-12-09 21:44:02 +00002749 }
Douglas Gregor04246572011-02-16 01:39:26 +00002750
Sebastian Redlbd595762010-08-31 20:53:31 +00002751 // Visit transparent contexts and inline namespaces inside this context.
Douglas Gregor2d435302009-12-30 17:04:44 +00002752 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
Sebastian Redlbd595762010-08-31 20:53:31 +00002753 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Douglas Gregor09bbc652010-01-14 15:47:35 +00002754 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002755 Consumer, Visited);
2756 }
2757 }
2758 }
2759
2760 // Traverse using directives for qualified name lookup.
2761 if (QualifiedNameLookup) {
2762 ShadowContextRAII Shadow(Visited);
2763 DeclContext::udir_iterator I, E;
2764 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002765 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002766 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002767 }
2768 }
2769
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002770 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00002771 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00002772 if (!Record->hasDefinition())
2773 return;
2774
Douglas Gregor2d435302009-12-30 17:04:44 +00002775 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2776 BEnd = Record->bases_end();
2777 B != BEnd; ++B) {
2778 QualType BaseType = B->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002779
Douglas Gregor2d435302009-12-30 17:04:44 +00002780 // Don't look into dependent bases, because name lookup can't look
2781 // there anyway.
2782 if (BaseType->isDependentType())
2783 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002784
Douglas Gregor2d435302009-12-30 17:04:44 +00002785 const RecordType *Record = BaseType->getAs<RecordType>();
2786 if (!Record)
2787 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002788
Douglas Gregor2d435302009-12-30 17:04:44 +00002789 // FIXME: It would be nice to be able to determine whether referencing
2790 // a particular member would be ambiguous. For example, given
2791 //
2792 // struct A { int member; };
2793 // struct B { int member; };
2794 // struct C : A, B { };
2795 //
2796 // void f(C *c) { c->### }
2797 //
2798 // accessing 'member' would result in an ambiguity. However, we
2799 // could be smart enough to qualify the member with the base
2800 // class, e.g.,
2801 //
2802 // c->B::member
2803 //
2804 // or
2805 //
2806 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002807
Douglas Gregor2d435302009-12-30 17:04:44 +00002808 // Find results in this base class (and its bases).
2809 ShadowContextRAII Shadow(Visited);
2810 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002811 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002812 }
2813 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002814
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002815 // Traverse the contexts of Objective-C classes.
2816 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2817 // Traverse categories.
2818 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2819 Category; Category = Category->getNextClassCategory()) {
2820 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002821 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002822 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002823 }
2824
2825 // Traverse protocols.
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002826 for (ObjCInterfaceDecl::all_protocol_iterator
2827 I = IFace->all_referenced_protocol_begin(),
2828 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002829 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002830 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002831 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002832 }
2833
2834 // Traverse the superclass.
2835 if (IFace->getSuperClass()) {
2836 ShadowContextRAII Shadow(Visited);
2837 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002838 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002839 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002840
Douglas Gregor0b59e802010-04-19 18:02:19 +00002841 // If there is an implementation, traverse it. We do this to find
2842 // synthesized ivars.
2843 if (IFace->getImplementation()) {
2844 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002845 LookupVisibleDecls(IFace->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00002846 QualifiedNameLookup, true, Consumer, Visited);
2847 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002848 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2849 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2850 E = Protocol->protocol_end(); I != E; ++I) {
2851 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002852 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002853 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002854 }
2855 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2856 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2857 E = Category->protocol_end(); I != E; ++I) {
2858 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002859 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002860 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002861 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002862
Douglas Gregor0b59e802010-04-19 18:02:19 +00002863 // If there is an implementation, traverse it.
2864 if (Category->getImplementation()) {
2865 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002866 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00002867 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002868 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002869 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002870}
2871
2872static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2873 UnqualUsingDirectiveSet &UDirs,
2874 VisibleDeclConsumer &Consumer,
2875 VisibleDeclsRecord &Visited) {
2876 if (!S)
2877 return;
2878
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002879 if (!S->getEntity() ||
2880 (!S->getParent() &&
Douglas Gregor39982192010-08-15 06:18:01 +00002881 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002882 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2883 // Walk through the declarations in this Scope.
2884 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2885 D != DEnd; ++D) {
John McCall48871652010-08-21 09:40:31 +00002886 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002887 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002888 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002889 Visited.add(ND);
2890 }
2891 }
2892 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002893
Douglas Gregor66230062010-03-15 14:33:29 +00002894 // FIXME: C++ [temp.local]p8
Douglas Gregor2d435302009-12-30 17:04:44 +00002895 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00002896 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002897 // Look into this scope's declaration context, along with any of its
2898 // parent lookup contexts (e.g., enclosing classes), up to the point
2899 // where we hit the context stored in the next outer scope.
2900 Entity = (DeclContext *)S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00002901 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002902
Douglas Gregorea166062010-03-15 15:26:48 +00002903 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00002904 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002905 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2906 if (Method->isInstanceMethod()) {
2907 // For instance methods, look for ivars in the method's interface.
2908 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2909 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00002910 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002911 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002912 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002913
Douglas Gregor05fcf842010-11-02 20:36:02 +00002914 // Look for properties from which we can synthesize ivars, if
2915 // permitted.
2916 if (Result.getSema().getLangOptions().ObjCNonFragileABI2 &&
2917 IFace->getImplementation() &&
2918 Result.getLookupKind() == Sema::LookupOrdinaryName) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002919 for (ObjCInterfaceDecl::prop_iterator
Douglas Gregor05fcf842010-11-02 20:36:02 +00002920 P = IFace->prop_begin(),
2921 PEnd = IFace->prop_end();
2922 P != PEnd; ++P) {
2923 if (Result.getSema().canSynthesizeProvisionalIvar(*P) &&
2924 !IFace->lookupInstanceVariable((*P)->getIdentifier())) {
2925 Consumer.FoundDecl(*P, Visited.checkHidden(*P), false);
2926 Visited.add(*P);
2927 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002928 }
2929 }
Douglas Gregor05fcf842010-11-02 20:36:02 +00002930 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002931 }
2932
2933 // We've already performed all of the name lookup that we need
2934 // to for Objective-C methods; the next context will be the
2935 // outer scope.
2936 break;
2937 }
2938
Douglas Gregor2d435302009-12-30 17:04:44 +00002939 if (Ctx->isFunctionOrMethod())
2940 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002941
2942 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002943 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002944 }
2945 } else if (!S->getParent()) {
2946 // Look into the translation unit scope. We walk through the translation
2947 // unit's declaration context, because the Scope itself won't have all of
2948 // the declarations if we loaded a precompiled header.
2949 // FIXME: We would like the translation unit's Scope object to point to the
2950 // translation unit, so we don't need this special "if" branch. However,
2951 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002952 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00002953 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002954 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00002955 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002956 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002957 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002958 }
2959
Douglas Gregor2d435302009-12-30 17:04:44 +00002960 if (Entity) {
2961 // Lookup visible declarations in any namespaces found by using
2962 // directives.
2963 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2964 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2965 for (; UI != UEnd; ++UI)
2966 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002967 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002968 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002969 }
2970
2971 // Lookup names in the parent scope.
2972 ShadowContextRAII Shadow(Visited);
2973 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2974}
2975
2976void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00002977 VisibleDeclConsumer &Consumer,
2978 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002979 // Determine the set of using directives available during
2980 // unqualified name lookup.
2981 Scope *Initial = S;
2982 UnqualUsingDirectiveSet UDirs;
2983 if (getLangOptions().CPlusPlus) {
2984 // Find the first namespace or translation-unit scope.
2985 while (S && !isNamespaceOrTranslationUnitScope(S))
2986 S = S->getParent();
2987
2988 UDirs.visitScopeChain(Initial, S);
2989 }
2990 UDirs.done();
2991
2992 // Look for visible declarations.
2993 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2994 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00002995 if (!IncludeGlobalScope)
2996 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00002997 ShadowContextRAII Shadow(Visited);
2998 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2999}
3000
3001void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003002 VisibleDeclConsumer &Consumer,
3003 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003004 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3005 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003006 if (!IncludeGlobalScope)
3007 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003008 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003009 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003010 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003011}
3012
Chris Lattner43e7f312011-02-18 02:08:43 +00003013/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003014/// If GnuLabelLoc is a valid source location, then this is a definition
3015/// of an __label__ label name, otherwise it is a normal label definition
3016/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003017LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003018 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003019 // Do a lookup to see if we have a label with this name already.
Chris Lattner43e7f312011-02-18 02:08:43 +00003020 NamedDecl *Res = 0;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003021
3022 if (GnuLabelLoc.isValid()) {
3023 // Local label definitions always shadow existing labels.
3024 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3025 Scope *S = CurScope;
3026 PushOnScopeChains(Res, S, true);
3027 return cast<LabelDecl>(Res);
3028 }
3029
3030 // Not a GNU local label.
3031 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3032 // If we found a label, check to see if it is in the same context as us.
3033 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003034 if (Res && Res->getDeclContext() != CurContext)
3035 Res = 0;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003036 if (Res == 0) {
3037 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003038 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3039 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003040 assert(S && "Not in a function?");
3041 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003042 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003043 return cast<LabelDecl>(Res);
3044}
3045
3046//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003047// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003048//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003049
3050namespace {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003051
3052typedef llvm::StringMap<TypoCorrection, llvm::BumpPtrAllocator> TypoResultsMap;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003053typedef std::map<unsigned, TypoResultsMap *> TypoEditDistanceMap;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003054
3055static const unsigned MaxTypoDistanceResultSets = 5;
3056
Douglas Gregor2d435302009-12-30 17:04:44 +00003057class TypoCorrectionConsumer : public VisibleDeclConsumer {
3058 /// \brief The name written that is a typo in the source.
3059 llvm::StringRef Typo;
3060
3061 /// \brief The results found that have the smallest edit distance
3062 /// found (so far) with the typo name.
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003063 ///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003064 /// The pointer value being set to the current DeclContext indicates
3065 /// whether there is a keyword with this name.
3066 TypoEditDistanceMap BestResults;
Douglas Gregor2d435302009-12-30 17:04:44 +00003067
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003068 /// \brief The worst of the best N edit distances found so far.
3069 unsigned MaxEditDistance;
3070
3071 Sema &SemaRef;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003072
Douglas Gregor2d435302009-12-30 17:04:44 +00003073public:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003074 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003075 : Typo(Typo->getName()),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003076 MaxEditDistance((std::numeric_limits<unsigned>::max)()),
3077 SemaRef(SemaRef) { }
Douglas Gregor2d435302009-12-30 17:04:44 +00003078
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003079 ~TypoCorrectionConsumer() {
3080 for (TypoEditDistanceMap::iterator I = BestResults.begin(),
3081 IEnd = BestResults.end();
3082 I != IEnd;
3083 ++I)
3084 delete I->second;
3085 }
3086
Douglas Gregor09bbc652010-01-14 15:47:35 +00003087 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregor57756ea2010-10-14 22:11:03 +00003088 void FoundName(llvm::StringRef Name);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003089 void addKeywordResult(llvm::StringRef Keyword);
3090 void addName(llvm::StringRef Name, NamedDecl *ND, unsigned Distance,
3091 NestedNameSpecifier *NNS=NULL);
3092 void addCorrection(TypoCorrection Correction);
Douglas Gregor2d435302009-12-30 17:04:44 +00003093
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003094 typedef TypoResultsMap::iterator result_iterator;
3095 typedef TypoEditDistanceMap::iterator distance_iterator;
3096 distance_iterator begin() { return BestResults.begin(); }
3097 distance_iterator end() { return BestResults.end(); }
3098 void erase(distance_iterator I) { BestResults.erase(I); }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003099 unsigned size() const { return BestResults.size(); }
3100 bool empty() const { return BestResults.empty(); }
Douglas Gregor2d435302009-12-30 17:04:44 +00003101
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003102 TypoCorrection &operator[](llvm::StringRef Name) {
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003103 return (*BestResults.begin()->second)[Name];
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003104 }
3105
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003106 unsigned getMaxEditDistance() const {
3107 return MaxEditDistance;
3108 }
3109
3110 unsigned getBestEditDistance() {
3111 return (BestResults.empty()) ? MaxEditDistance : BestResults.begin()->first;
3112 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003113};
3114
3115}
3116
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003117void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003118 bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003119 // Don't consider hidden names for typo correction.
3120 if (Hiding)
3121 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003122
Douglas Gregor2d435302009-12-30 17:04:44 +00003123 // Only consider entities with identifiers for names, ignoring
3124 // special names (constructors, overloaded operators, selectors,
3125 // etc.).
3126 IdentifierInfo *Name = ND->getIdentifier();
3127 if (!Name)
3128 return;
3129
Douglas Gregor57756ea2010-10-14 22:11:03 +00003130 FoundName(Name->getName());
3131}
3132
3133void TypoCorrectionConsumer::FoundName(llvm::StringRef Name) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003134 // Use a simple length-based heuristic to determine the minimum possible
3135 // edit distance. If the minimum isn't good enough, bail out early.
3136 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003137 if (MinED > MaxEditDistance || (MinED && Typo.size() / MinED < 3))
Douglas Gregor93910a52010-10-19 19:39:10 +00003138 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003139
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003140 // Compute an upper bound on the allowable edit distance, so that the
3141 // edit-distance algorithm can short-circuit.
Jay Foad72e705e2011-04-23 09:06:00 +00003142 unsigned UpperBound =
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003143 std::min(unsigned((Typo.size() + 2) / 3), MaxEditDistance);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003144
Douglas Gregor2d435302009-12-30 17:04:44 +00003145 // Compute the edit distance between the typo and the name of this
3146 // entity. If this edit distance is not worse than the best edit
3147 // distance we've seen so far, add it to the list of results.
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003148 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003149
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003150 if (ED > MaxEditDistance) {
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003151 // This result is worse than the best results we've seen so far;
3152 // ignore it.
3153 return;
3154 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003155
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003156 addName(Name, NULL, ED);
Douglas Gregor2d435302009-12-30 17:04:44 +00003157}
3158
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003159void TypoCorrectionConsumer::addKeywordResult(llvm::StringRef Keyword) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003160 // Compute the edit distance between the typo and this keyword.
3161 // If this edit distance is not worse than the best edit
3162 // distance we've seen so far, add it to the list of results.
3163 unsigned ED = Typo.edit_distance(Keyword);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003164 if (ED > MaxEditDistance) {
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003165 // This result is worse than the best results we've seen so far;
3166 // ignore it.
3167 return;
3168 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003169
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003170 addName(Keyword, TypoCorrection::KeywordDecl(), ED);
3171}
3172
3173void TypoCorrectionConsumer::addName(llvm::StringRef Name,
3174 NamedDecl *ND,
3175 unsigned Distance,
3176 NestedNameSpecifier *NNS) {
3177 addCorrection(TypoCorrection(&SemaRef.Context.Idents.get(Name),
3178 ND, NNS, Distance));
3179}
3180
3181void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
3182 llvm::StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003183 TypoResultsMap *& Map = BestResults[Correction.getEditDistance()];
3184 if (!Map)
3185 Map = new TypoResultsMap;
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003186
3187 TypoCorrection &CurrentCorrection = (*Map)[Name];
3188 if (!CurrentCorrection ||
3189 // FIXME: The following should be rolled up into an operator< on
3190 // TypoCorrection with a more principled definition.
3191 CurrentCorrection.isKeyword() < Correction.isKeyword() ||
3192 Correction.getAsString(SemaRef.getLangOptions()) <
3193 CurrentCorrection.getAsString(SemaRef.getLangOptions()))
3194 CurrentCorrection = Correction;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003195
3196 while (BestResults.size() > MaxTypoDistanceResultSets) {
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003197 TypoEditDistanceMap::iterator Last = BestResults.end();
3198 --Last;
3199 delete Last->second;
3200 BestResults.erase(Last);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003201 }
3202}
3203
3204namespace {
3205
3206class SpecifierInfo {
3207 public:
3208 DeclContext* DeclCtx;
3209 NestedNameSpecifier* NameSpecifier;
3210 unsigned EditDistance;
3211
3212 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3213 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3214};
3215
3216typedef llvm::SmallVector<DeclContext*, 4> DeclContextList;
3217typedef llvm::SmallVector<SpecifierInfo, 16> SpecifierInfoList;
3218
3219class NamespaceSpecifierSet {
3220 ASTContext &Context;
3221 DeclContextList CurContextChain;
3222 bool isSorted;
3223
3224 SpecifierInfoList Specifiers;
3225 llvm::SmallSetVector<unsigned, 4> Distances;
3226 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3227
3228 /// \brief Helper for building the list of DeclContexts between the current
3229 /// context and the top of the translation unit
3230 static DeclContextList BuildContextChain(DeclContext *Start);
3231
3232 void SortNamespaces();
3233
3234 public:
3235 explicit NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext)
Benjamin Kramerde1d6232011-07-05 09:46:31 +00003236 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
3237 isSorted(true) {}
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003238
3239 /// \brief Add the namespace to the set, computing the corresponding
3240 /// NestedNameSpecifier and its distance in the process.
3241 void AddNamespace(NamespaceDecl *ND);
3242
3243 typedef SpecifierInfoList::iterator iterator;
3244 iterator begin() {
3245 if (!isSorted) SortNamespaces();
3246 return Specifiers.begin();
3247 }
3248 iterator end() { return Specifiers.end(); }
3249};
3250
3251}
3252
3253DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003254 assert(Start && "Bulding a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003255 DeclContextList Chain;
3256 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3257 DC = DC->getLookupParent()) {
3258 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3259 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3260 !(ND && ND->isAnonymousNamespace()))
3261 Chain.push_back(DC->getPrimaryContext());
3262 }
3263 return Chain;
3264}
3265
3266void NamespaceSpecifierSet::SortNamespaces() {
3267 llvm::SmallVector<unsigned, 4> sortedDistances;
3268 sortedDistances.append(Distances.begin(), Distances.end());
3269
3270 if (sortedDistances.size() > 1)
3271 std::sort(sortedDistances.begin(), sortedDistances.end());
3272
3273 Specifiers.clear();
3274 for (llvm::SmallVector<unsigned, 4>::iterator DI = sortedDistances.begin(),
3275 DIEnd = sortedDistances.end();
3276 DI != DIEnd; ++DI) {
3277 SpecifierInfoList &SpecList = DistanceMap[*DI];
3278 Specifiers.append(SpecList.begin(), SpecList.end());
3279 }
3280
3281 isSorted = true;
3282}
3283
3284void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003285 DeclContext *Ctx = cast<DeclContext>(ND);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003286 NestedNameSpecifier *NNS = NULL;
3287 unsigned NumSpecifiers = 0;
3288 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
3289
3290 // Eliminate common elements from the two DeclContext chains
3291 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3292 CEnd = CurContextChain.rend();
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003293 C != CEnd && !NamespaceDeclChain.empty() &&
3294 NamespaceDeclChain.back() == *C; ++C) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003295 NamespaceDeclChain.pop_back();
3296 }
3297
3298 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3299 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3300 CEnd = NamespaceDeclChain.rend();
3301 C != CEnd; ++C) {
3302 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3303 if (ND) {
3304 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3305 ++NumSpecifiers;
3306 }
3307 }
3308
3309 isSorted = false;
3310 Distances.insert(NumSpecifiers);
3311 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003312}
3313
Douglas Gregord507d772010-10-20 03:06:34 +00003314/// \brief Perform name lookup for a possible result for typo correction.
3315static void LookupPotentialTypoResult(Sema &SemaRef,
3316 LookupResult &Res,
3317 IdentifierInfo *Name,
3318 Scope *S, CXXScopeSpec *SS,
3319 DeclContext *MemberContext,
3320 bool EnteringContext,
3321 Sema::CorrectTypoContext CTC) {
3322 Res.suppressDiagnostics();
3323 Res.clear();
3324 Res.setLookupName(Name);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003325 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00003326 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
3327 if (CTC == Sema::CTC_ObjCIvarLookup) {
3328 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3329 Res.addDecl(Ivar);
3330 Res.resolveKind();
3331 return;
3332 }
3333 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003334
Douglas Gregord507d772010-10-20 03:06:34 +00003335 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3336 Res.addDecl(Prop);
3337 Res.resolveKind();
3338 return;
3339 }
3340 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003341
Douglas Gregord507d772010-10-20 03:06:34 +00003342 SemaRef.LookupQualifiedName(Res, MemberContext);
3343 return;
3344 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003345
3346 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00003347 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003348
Douglas Gregord507d772010-10-20 03:06:34 +00003349 // Fake ivar lookup; this should really be part of
3350 // LookupParsedName.
3351 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3352 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003353 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00003354 (Res.isSingleResult() &&
3355 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003356 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00003357 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3358 Res.addDecl(IV);
3359 Res.resolveKind();
3360 }
3361 }
3362 }
3363}
3364
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003365/// \brief Add keywords to the consumer as possible typo corrections.
3366static void AddKeywordsToConsumer(Sema &SemaRef,
3367 TypoCorrectionConsumer &Consumer,
3368 Scope *S, Sema::CorrectTypoContext CTC) {
3369 // Add context-dependent keywords.
3370 bool WantTypeSpecifiers = false;
3371 bool WantExpressionKeywords = false;
3372 bool WantCXXNamedCasts = false;
3373 bool WantRemainingKeywords = false;
3374 switch (CTC) {
3375 case Sema::CTC_Unknown:
3376 WantTypeSpecifiers = true;
3377 WantExpressionKeywords = true;
3378 WantCXXNamedCasts = true;
3379 WantRemainingKeywords = true;
3380
3381 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
3382 if (Method->getClassInterface() &&
3383 Method->getClassInterface()->getSuperClass())
3384 Consumer.addKeywordResult("super");
3385
3386 break;
3387
3388 case Sema::CTC_NoKeywords:
3389 break;
3390
3391 case Sema::CTC_Type:
3392 WantTypeSpecifiers = true;
3393 break;
3394
3395 case Sema::CTC_ObjCMessageReceiver:
3396 Consumer.addKeywordResult("super");
3397 // Fall through to handle message receivers like expressions.
3398
3399 case Sema::CTC_Expression:
3400 if (SemaRef.getLangOptions().CPlusPlus)
3401 WantTypeSpecifiers = true;
3402 WantExpressionKeywords = true;
3403 // Fall through to get C++ named casts.
3404
3405 case Sema::CTC_CXXCasts:
3406 WantCXXNamedCasts = true;
3407 break;
3408
3409 case Sema::CTC_ObjCPropertyLookup:
3410 // FIXME: Add "isa"?
3411 break;
3412
3413 case Sema::CTC_MemberLookup:
3414 if (SemaRef.getLangOptions().CPlusPlus)
3415 Consumer.addKeywordResult("template");
3416 break;
3417
3418 case Sema::CTC_ObjCIvarLookup:
3419 break;
3420 }
3421
3422 if (WantTypeSpecifiers) {
3423 // Add type-specifier keywords to the set of results.
3424 const char *CTypeSpecs[] = {
3425 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00003426 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003427 "_Complex", "_Imaginary",
3428 // storage-specifiers as well
3429 "extern", "inline", "static", "typedef"
3430 };
3431
3432 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3433 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3434 Consumer.addKeywordResult(CTypeSpecs[I]);
3435
3436 if (SemaRef.getLangOptions().C99)
3437 Consumer.addKeywordResult("restrict");
3438 if (SemaRef.getLangOptions().Bool || SemaRef.getLangOptions().CPlusPlus)
3439 Consumer.addKeywordResult("bool");
Douglas Gregor3b22a882011-07-01 21:27:45 +00003440 else if (SemaRef.getLangOptions().C99)
3441 Consumer.addKeywordResult("_Bool");
3442
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003443 if (SemaRef.getLangOptions().CPlusPlus) {
3444 Consumer.addKeywordResult("class");
3445 Consumer.addKeywordResult("typename");
3446 Consumer.addKeywordResult("wchar_t");
3447
3448 if (SemaRef.getLangOptions().CPlusPlus0x) {
3449 Consumer.addKeywordResult("char16_t");
3450 Consumer.addKeywordResult("char32_t");
3451 Consumer.addKeywordResult("constexpr");
3452 Consumer.addKeywordResult("decltype");
3453 Consumer.addKeywordResult("thread_local");
3454 }
3455 }
3456
3457 if (SemaRef.getLangOptions().GNUMode)
3458 Consumer.addKeywordResult("typeof");
3459 }
3460
3461 if (WantCXXNamedCasts && SemaRef.getLangOptions().CPlusPlus) {
3462 Consumer.addKeywordResult("const_cast");
3463 Consumer.addKeywordResult("dynamic_cast");
3464 Consumer.addKeywordResult("reinterpret_cast");
3465 Consumer.addKeywordResult("static_cast");
3466 }
3467
3468 if (WantExpressionKeywords) {
3469 Consumer.addKeywordResult("sizeof");
3470 if (SemaRef.getLangOptions().Bool || SemaRef.getLangOptions().CPlusPlus) {
3471 Consumer.addKeywordResult("false");
3472 Consumer.addKeywordResult("true");
3473 }
3474
3475 if (SemaRef.getLangOptions().CPlusPlus) {
3476 const char *CXXExprs[] = {
3477 "delete", "new", "operator", "throw", "typeid"
3478 };
3479 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3480 for (unsigned I = 0; I != NumCXXExprs; ++I)
3481 Consumer.addKeywordResult(CXXExprs[I]);
3482
3483 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3484 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3485 Consumer.addKeywordResult("this");
3486
3487 if (SemaRef.getLangOptions().CPlusPlus0x) {
3488 Consumer.addKeywordResult("alignof");
3489 Consumer.addKeywordResult("nullptr");
3490 }
3491 }
3492 }
3493
3494 if (WantRemainingKeywords) {
3495 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3496 // Statements.
3497 const char *CStmts[] = {
3498 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3499 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3500 for (unsigned I = 0; I != NumCStmts; ++I)
3501 Consumer.addKeywordResult(CStmts[I]);
3502
3503 if (SemaRef.getLangOptions().CPlusPlus) {
3504 Consumer.addKeywordResult("catch");
3505 Consumer.addKeywordResult("try");
3506 }
3507
3508 if (S && S->getBreakParent())
3509 Consumer.addKeywordResult("break");
3510
3511 if (S && S->getContinueParent())
3512 Consumer.addKeywordResult("continue");
3513
3514 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3515 Consumer.addKeywordResult("case");
3516 Consumer.addKeywordResult("default");
3517 }
3518 } else {
3519 if (SemaRef.getLangOptions().CPlusPlus) {
3520 Consumer.addKeywordResult("namespace");
3521 Consumer.addKeywordResult("template");
3522 }
3523
3524 if (S && S->isClassScope()) {
3525 Consumer.addKeywordResult("explicit");
3526 Consumer.addKeywordResult("friend");
3527 Consumer.addKeywordResult("mutable");
3528 Consumer.addKeywordResult("private");
3529 Consumer.addKeywordResult("protected");
3530 Consumer.addKeywordResult("public");
3531 Consumer.addKeywordResult("virtual");
3532 }
3533 }
3534
3535 if (SemaRef.getLangOptions().CPlusPlus) {
3536 Consumer.addKeywordResult("using");
3537
3538 if (SemaRef.getLangOptions().CPlusPlus0x)
3539 Consumer.addKeywordResult("static_assert");
3540 }
3541 }
3542}
3543
Douglas Gregor2d435302009-12-30 17:04:44 +00003544/// \brief Try to "correct" a typo in the source code by finding
3545/// visible declarations whose names are similar to the name that was
3546/// present in the source code.
3547///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003548/// \param TypoName the \c DeclarationNameInfo structure that contains
3549/// the name that was present in the source code along with its location.
3550///
3551/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00003552///
3553/// \param S the scope in which name lookup occurs.
3554///
3555/// \param SS the nested-name-specifier that precedes the name we're
3556/// looking for, if present.
3557///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003558/// \param MemberContext if non-NULL, the context in which to look for
3559/// a member access expression.
3560///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003561/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00003562/// the nested-name-specifier SS.
3563///
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003564/// \param CTC The context in which typo correction occurs, which impacts the
3565/// set of keywords permitted.
3566///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003567/// \param OPT when non-NULL, the search for visible declarations will
3568/// also walk the protocols in the qualified interfaces of \p OPT.
3569///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003570/// \returns a \c TypoCorrection containing the corrected name if the typo
3571/// along with information such as the \c NamedDecl where the corrected name
3572/// was declared, and any additional \c NestedNameSpecifier needed to access
3573/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3574TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3575 Sema::LookupNameKind LookupKind,
3576 Scope *S, CXXScopeSpec *SS,
3577 DeclContext *MemberContext,
3578 bool EnteringContext,
3579 CorrectTypoContext CTC,
3580 const ObjCObjectPointerType *OPT) {
Douglas Gregor8ed0c0b2010-07-09 17:35:33 +00003581 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003582 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003583
Douglas Gregor2d435302009-12-30 17:04:44 +00003584 // We only attempt to correct typos for identifiers.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003585 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor2d435302009-12-30 17:04:44 +00003586 if (!Typo)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003587 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00003588
3589 // If the scope specifier itself was invalid, don't try to correct
3590 // typos.
3591 if (SS && SS->isInvalid())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003592 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00003593
3594 // Never try to correct typos during template deduction or
3595 // instantiation.
3596 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003597 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003598
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003599 NamespaceSpecifierSet Namespaces(Context, CurContext);
3600
3601 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003602
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003603 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor87074f12010-10-20 01:32:02 +00003604 bool IsUnqualifiedLookup = false;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003605 if (MemberContext) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003606 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003607
3608 // Look in qualified interfaces.
3609 if (OPT) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003610 for (ObjCObjectPointerType::qual_iterator
3611 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003612 I != E; ++I)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003613 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003614 }
3615 } else if (SS && SS->isSet()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003616 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
3617 if (!DC)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003618 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003619
Douglas Gregor87074f12010-10-20 01:32:02 +00003620 // Provide a stop gap for files that are just seriously broken. Trying
3621 // to correct all typos can turn into a HUGE performance penalty, causing
3622 // some files to take minutes to get rejected by the parser.
3623 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003624 return TypoCorrection();
Douglas Gregor87074f12010-10-20 01:32:02 +00003625 ++TyposCorrected;
3626
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003627 LookupVisibleDecls(DC, LookupKind, Consumer);
Douglas Gregor2d435302009-12-30 17:04:44 +00003628 } else {
Douglas Gregor87074f12010-10-20 01:32:02 +00003629 IsUnqualifiedLookup = true;
3630 UnqualifiedTyposCorrectedMap::iterator Cached
3631 = UnqualifiedTyposCorrected.find(Typo);
3632 if (Cached == UnqualifiedTyposCorrected.end()) {
3633 // Provide a stop gap for files that are just seriously broken. Trying
3634 // to correct all typos can turn into a HUGE performance penalty, causing
3635 // some files to take minutes to get rejected by the parser.
3636 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003637 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003638
Douglas Gregor87074f12010-10-20 01:32:02 +00003639 // For unqualified lookup, look through all of the names that we have
3640 // seen in this translation unit.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003641 for (IdentifierTable::iterator I = Context.Idents.begin(),
Douglas Gregor87074f12010-10-20 01:32:02 +00003642 IEnd = Context.Idents.end();
3643 I != IEnd; ++I)
3644 Consumer.FoundName(I->getKey());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003645
Douglas Gregor87074f12010-10-20 01:32:02 +00003646 // Walk through identifiers in external identifier sources.
3647 if (IdentifierInfoLookup *External
Douglas Gregor57756ea2010-10-14 22:11:03 +00003648 = Context.Idents.getExternalIdentifierLookup()) {
Ted Kremenekb4ea9a82010-11-07 06:11:33 +00003649 llvm::OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Douglas Gregor87074f12010-10-20 01:32:02 +00003650 do {
3651 llvm::StringRef Name = Iter->Next();
3652 if (Name.empty())
3653 break;
Douglas Gregor57756ea2010-10-14 22:11:03 +00003654
Douglas Gregor87074f12010-10-20 01:32:02 +00003655 Consumer.FoundName(Name);
3656 } while (true);
3657 }
3658 } else {
3659 // Use the cached value, unless it's a keyword. In the keyword case, we'll
3660 // end up adding the keyword below.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003661 if (!Cached->second)
3662 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003663
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003664 if (!Cached->second.isKeyword())
3665 Consumer.addCorrection(Cached->second);
Douglas Gregor57756ea2010-10-14 22:11:03 +00003666 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003667 }
3668
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003669 AddKeywordsToConsumer(*this, Consumer, S, CTC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003670
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003671 // If we haven't found anything, we're done.
Douglas Gregor87074f12010-10-20 01:32:02 +00003672 if (Consumer.empty()) {
3673 // If this was an unqualified lookup, note that no correction was found.
3674 if (IsUnqualifiedLookup)
3675 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003676
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003677 return TypoCorrection();
Douglas Gregor87074f12010-10-20 01:32:02 +00003678 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003679
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003680 // Make sure that the user typed at least 3 characters for each correction
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003681 // made. Otherwise, we don't even both looking at the results.
3682 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregor87074f12010-10-20 01:32:02 +00003683 if (ED > 0 && Typo->getName().size() / ED < 3) {
3684 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregoraf1daa92010-10-27 14:20:34 +00003685 if (IsUnqualifiedLookup)
Douglas Gregor87074f12010-10-20 01:32:02 +00003686 (void)UnqualifiedTyposCorrected[Typo];
3687
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003688 return TypoCorrection();
3689 }
3690
3691 // Build the NestedNameSpecifiers for the KnownNamespaces
3692 if (getLangOptions().CPlusPlus) {
3693 // Load any externally-known namespaces.
3694 if (ExternalSource && !LoadedExternalKnownNamespaces) {
3695 llvm::SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
3696 LoadedExternalKnownNamespaces = true;
3697 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
3698 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
3699 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
3700 }
3701
3702 for (llvm::DenseMap<NamespaceDecl*, bool>::iterator
3703 KNI = KnownNamespaces.begin(),
3704 KNIEnd = KnownNamespaces.end();
3705 KNI != KNIEnd; ++KNI)
3706 Namespaces.AddNamespace(KNI->first);
Douglas Gregor87074f12010-10-20 01:32:02 +00003707 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003708
3709 // Weed out any names that could not be found by name lookup.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003710 llvm::SmallPtrSet<IdentifierInfo*, 16> QualifiedResults;
3711 LookupResult TmpRes(*this, TypoName, LookupKind);
3712 TmpRes.suppressDiagnostics();
3713 while (!Consumer.empty()) {
3714 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3715 unsigned ED = DI->first;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003716 for (TypoCorrectionConsumer::result_iterator I = DI->second->begin(),
3717 IEnd = DI->second->end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003718 I != IEnd; /* Increment in loop. */) {
3719 // If the item already has been looked up or is a keyword, keep it
3720 if (I->second.isResolved()) {
3721 ++I;
3722 continue;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003723 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003724
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003725 // Perform name lookup on this name.
3726 IdentifierInfo *Name = I->second.getCorrectionAsIdentifierInfo();
3727 LookupPotentialTypoResult(*this, TmpRes, Name, S, SS, MemberContext,
3728 EnteringContext, CTC);
3729
3730 switch (TmpRes.getResultKind()) {
3731 case LookupResult::NotFound:
3732 case LookupResult::NotFoundInCurrentInstantiation:
3733 QualifiedResults.insert(Name);
3734 // We didn't find this name in our scope, or didn't like what we found;
3735 // ignore it.
3736 {
3737 TypoCorrectionConsumer::result_iterator Next = I;
3738 ++Next;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003739 DI->second->erase(I);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003740 I = Next;
3741 }
3742 break;
3743
3744 case LookupResult::Ambiguous:
3745 // We don't deal with ambiguities.
3746 return TypoCorrection();
3747
3748 case LookupResult::Found:
3749 case LookupResult::FoundOverloaded:
3750 case LookupResult::FoundUnresolvedValue:
3751 I->second.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
Hans Wennborg38198de2011-07-12 08:45:31 +00003752 // FIXME: This sets the CorrectionDecl to NULL for overloaded functions.
3753 // It would be nice to find the right one with overload resolution.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003754 ++I;
3755 break;
3756 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003757 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003758
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003759 if (DI->second->empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003760 Consumer.erase(DI);
3761 else if (!getLangOptions().CPlusPlus || QualifiedResults.empty() || !ED)
3762 // If there are results in the closest possible bucket, stop
3763 break;
3764
3765 // Only perform the qualified lookups for C++
3766 if (getLangOptions().CPlusPlus) {
3767 TmpRes.suppressDiagnostics();
3768 for (llvm::SmallPtrSet<IdentifierInfo*,
3769 16>::iterator QRI = QualifiedResults.begin(),
3770 QRIEnd = QualifiedResults.end();
3771 QRI != QRIEnd; ++QRI) {
3772 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
3773 NIEnd = Namespaces.end();
3774 NI != NIEnd; ++NI) {
3775 DeclContext *Ctx = NI->DeclCtx;
3776 unsigned QualifiedED = ED + NI->EditDistance;
3777
3778 // Stop searching once the namespaces are too far away to create
3779 // acceptable corrections for this identifier (since the namespaces
3780 // are sorted in ascending order by edit distance)
3781 if (QualifiedED > Consumer.getMaxEditDistance()) break;
3782
3783 TmpRes.clear();
3784 TmpRes.setLookupName(*QRI);
3785 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
3786
3787 switch (TmpRes.getResultKind()) {
3788 case LookupResult::Found:
3789 case LookupResult::FoundOverloaded:
3790 case LookupResult::FoundUnresolvedValue:
3791 Consumer.addName((*QRI)->getName(), TmpRes.getAsSingle<NamedDecl>(),
3792 QualifiedED, NI->NameSpecifier);
3793 break;
3794 case LookupResult::NotFound:
3795 case LookupResult::NotFoundInCurrentInstantiation:
3796 case LookupResult::Ambiguous:
3797 break;
3798 }
3799 }
3800 }
3801 }
3802
3803 QualifiedResults.clear();
3804 }
3805
3806 // No corrections remain...
3807 if (Consumer.empty()) return TypoCorrection();
3808
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003809 TypoResultsMap &BestResults = *Consumer.begin()->second;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003810 ED = Consumer.begin()->first;
3811
3812 if (ED > 0 && Typo->getName().size() / ED < 3) {
3813 // If this was an unqualified lookup, note that no correction was found.
3814 if (IsUnqualifiedLookup)
3815 (void)UnqualifiedTyposCorrected[Typo];
3816
3817 return TypoCorrection();
3818 }
3819
3820 // If we have multiple possible corrections, eliminate the ones where we
3821 // added namespace qualifiers to try to resolve the ambiguity (and to favor
3822 // corrections without additional namespace qualifiers)
3823 if (getLangOptions().CPlusPlus && BestResults.size() > 1) {
3824 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003825 for (TypoCorrectionConsumer::result_iterator I = DI->second->begin(),
3826 IEnd = DI->second->end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003827 I != IEnd; /* Increment in loop. */) {
3828 if (I->second.getCorrectionSpecifier() != NULL) {
3829 TypoCorrectionConsumer::result_iterator Cur = I;
3830 ++I;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003831 DI->second->erase(Cur);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003832 } else ++I;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003833 }
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003834 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003835
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003836 // If only a single name remains, return that result.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003837 if (BestResults.size() == 1) {
3838 const llvm::StringMapEntry<TypoCorrection> &Correction = *(BestResults.begin());
3839 const TypoCorrection &Result = Correction.second;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003840
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00003841 // Don't correct to a keyword that's the same as the typo; the keyword
3842 // wasn't actually in scope.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003843 if (ED == 0 && Result.isKeyword()) return TypoCorrection();
3844
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003845 // Record the correction for unqualified lookup.
3846 if (IsUnqualifiedLookup)
3847 UnqualifiedTyposCorrected[Typo] = Result;
3848
3849 return Result;
3850 }
3851 else if (BestResults.size() > 1 && CTC == CTC_ObjCMessageReceiver
3852 && BestResults["super"].isKeyword()) {
3853 // Prefer 'super' when we're completing in a message-receiver
3854 // context.
3855
3856 // Don't correct to a keyword that's the same as the typo; the keyword
3857 // wasn't actually in scope.
3858 if (ED == 0) return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003859
Douglas Gregor87074f12010-10-20 01:32:02 +00003860 // Record the correction for unqualified lookup.
3861 if (IsUnqualifiedLookup)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003862 UnqualifiedTyposCorrected[Typo] = BestResults["super"];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003863
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003864 return BestResults["super"];
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003865 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003866
Douglas Gregor87074f12010-10-20 01:32:02 +00003867 if (IsUnqualifiedLookup)
3868 (void)UnqualifiedTyposCorrected[Typo];
3869
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003870 return TypoCorrection();
3871}
3872
3873std::string TypoCorrection::getAsString(const LangOptions &LO) const {
3874 if (CorrectionNameSpec) {
3875 std::string tmpBuffer;
3876 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
3877 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
3878 return PrefixOStream.str() + CorrectionName.getAsString();
3879 }
3880
3881 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00003882}