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