blob: 63d14f46c1ebb8faffeea57e6790626ec537ba35 [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"
Chris Lattner83cfc7c2011-07-18 01:54:02 +000038#include "llvm/ADT/TinyPtrVector.h"
John McCall6538c932009-10-10 05:48:19 +000039#include "llvm/Support/ErrorHandling.h"
Douglas Gregor0afa7f62010-10-14 20:34:08 +000040#include <limits>
Douglas Gregor2d435302009-12-30 17:04:44 +000041#include <list>
Douglas Gregor1c846b02009-01-16 00:38:09 +000042#include <set>
Douglas Gregor889ceb72009-02-03 19:21:40 +000043#include <vector>
44#include <iterator>
45#include <utility>
46#include <algorithm>
Douglas Gregorc2fa1692011-06-28 16:20:02 +000047#include <map>
Douglas Gregor34074322009-01-14 22:20:51 +000048
49using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000050using namespace sema;
Douglas Gregor34074322009-01-14 22:20:51 +000051
John McCallf6c8a4e2009-11-10 07:01:13 +000052namespace {
53 class UnqualUsingEntry {
54 const DeclContext *Nominated;
55 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000056
John McCallf6c8a4e2009-11-10 07:01:13 +000057 public:
58 UnqualUsingEntry(const DeclContext *Nominated,
59 const DeclContext *CommonAncestor)
60 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
61 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000062
John McCallf6c8a4e2009-11-10 07:01:13 +000063 const DeclContext *getCommonAncestor() const {
64 return CommonAncestor;
65 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000066
John McCallf6c8a4e2009-11-10 07:01:13 +000067 const DeclContext *getNominatedNamespace() const {
68 return Nominated;
69 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000070
John McCallf6c8a4e2009-11-10 07:01:13 +000071 // Sort by the pointer value of the common ancestor.
72 struct Comparator {
73 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
74 return L.getCommonAncestor() < R.getCommonAncestor();
75 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000076
John McCallf6c8a4e2009-11-10 07:01:13 +000077 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
78 return E.getCommonAncestor() < DC;
79 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000080
John McCallf6c8a4e2009-11-10 07:01:13 +000081 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
82 return DC < E.getCommonAncestor();
83 }
84 };
85 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000086
John McCallf6c8a4e2009-11-10 07:01:13 +000087 /// A collection of using directives, as used by C++ unqualified
88 /// lookup.
89 class UnqualUsingDirectiveSet {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000090 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000091
John McCallf6c8a4e2009-11-10 07:01:13 +000092 ListTy list;
93 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000094
John McCallf6c8a4e2009-11-10 07:01:13 +000095 public:
96 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +000097
John McCallf6c8a4e2009-11-10 07:01:13 +000098 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000099 // C++ [namespace.udir]p1:
John McCallf6c8a4e2009-11-10 07:01:13 +0000100 // During unqualified name lookup, the names appear as if they
101 // were declared in the nearest enclosing namespace which contains
102 // both the using-directive and the nominated namespace.
103 DeclContext *InnermostFileDC
104 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
105 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +0000106
John McCallf6c8a4e2009-11-10 07:01:13 +0000107 for (; S; S = S->getParent()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000108 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
109 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
110 visit(Ctx, EffectiveDC);
111 } else {
112 Scope::udir_iterator I = S->using_directives_begin(),
113 End = S->using_directives_end();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000114
John McCallf6c8a4e2009-11-10 07:01:13 +0000115 for (; I != End; ++I)
John McCall48871652010-08-21 09:40:31 +0000116 visit(*I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000117 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000118 }
119 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000120
121 // Visits a context and collect all of its using directives
122 // recursively. Treats all using directives as if they were
123 // declared in the context.
124 //
125 // A given context is only every visited once, so it is important
126 // that contexts be visited from the inside out in order to get
127 // the effective DCs right.
128 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
129 if (!visited.insert(DC))
130 return;
131
132 addUsingDirectives(DC, EffectiveDC);
133 }
134
135 // Visits a using directive and collects all of its using
136 // directives recursively. Treats all using directives as if they
137 // were declared in the effective DC.
138 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
139 DeclContext *NS = UD->getNominatedNamespace();
140 if (!visited.insert(NS))
141 return;
142
143 addUsingDirective(UD, EffectiveDC);
144 addUsingDirectives(NS, EffectiveDC);
145 }
146
147 // Adds all the using directives in a context (and those nominated
148 // by its using directives, transitively) as if they appeared in
149 // the given effective context.
150 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000151 SmallVector<DeclContext*,4> queue;
John McCallf6c8a4e2009-11-10 07:01:13 +0000152 while (true) {
153 DeclContext::udir_iterator I, End;
154 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
155 UsingDirectiveDecl *UD = *I;
156 DeclContext *NS = UD->getNominatedNamespace();
157 if (visited.insert(NS)) {
158 addUsingDirective(UD, EffectiveDC);
159 queue.push_back(NS);
160 }
161 }
162
163 if (queue.empty())
164 return;
165
166 DC = queue.back();
167 queue.pop_back();
168 }
169 }
170
171 // Add a using directive as if it had been declared in the given
172 // context. This helps implement C++ [namespace.udir]p3:
173 // The using-directive is transitive: if a scope contains a
174 // using-directive that nominates a second namespace that itself
175 // contains using-directives, the effect is as if the
176 // using-directives from the second namespace also appeared in
177 // the first.
178 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
179 // Find the common ancestor between the effective context and
180 // the nominated namespace.
181 DeclContext *Common = UD->getNominatedNamespace();
182 while (!Common->Encloses(EffectiveDC))
183 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000184 Common = Common->getPrimaryContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000185
John McCallf6c8a4e2009-11-10 07:01:13 +0000186 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
187 }
188
189 void done() {
190 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
191 }
192
John McCallf6c8a4e2009-11-10 07:01:13 +0000193 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000194
John McCallf6c8a4e2009-11-10 07:01:13 +0000195 const_iterator begin() const { return list.begin(); }
196 const_iterator end() const { return list.end(); }
197
198 std::pair<const_iterator,const_iterator>
199 getNamespacesFor(DeclContext *DC) const {
John McCall9757d032009-11-10 09:20:04 +0000200 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCallf6c8a4e2009-11-10 07:01:13 +0000201 UnqualUsingEntry::Comparator());
202 }
203 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000204}
205
Douglas Gregor889ceb72009-02-03 19:21:40 +0000206// Retrieve the set of identifier namespaces that correspond to a
207// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000208static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
209 bool CPlusPlus,
210 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000211 unsigned IDNS = 0;
212 switch (NameKind) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +0000213 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000214 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000215 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000216 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000217 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000218 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000219 if (Redeclaration)
220 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCallea305ed2009-12-18 10:40:03 +0000221 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000222 break;
223
John McCallb9467b62010-04-24 01:30:58 +0000224 case Sema::LookupOperatorName:
225 // Operator lookup is its own crazy thing; it is not the same
226 // as (e.g.) looking up an operator name for redeclaration.
227 assert(!Redeclaration && "cannot do redeclaration operator lookup");
228 IDNS = Decl::IDNS_NonMemberOperator;
229 break;
230
Douglas Gregor889ceb72009-02-03 19:21:40 +0000231 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000232 if (CPlusPlus) {
233 IDNS = Decl::IDNS_Type;
234
235 // When looking for a redeclaration of a tag name, we add:
236 // 1) TagFriend to find undeclared friend decls
237 // 2) Namespace because they can't "overload" with tag decls.
238 // 3) Tag because it includes class templates, which can't
239 // "overload" with tag decls.
240 if (Redeclaration)
241 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
242 } else {
243 IDNS = Decl::IDNS_Tag;
244 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000245 break;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000246 case Sema::LookupLabel:
247 IDNS = Decl::IDNS_Label;
248 break;
249
Douglas Gregor889ceb72009-02-03 19:21:40 +0000250 case Sema::LookupMemberName:
251 IDNS = Decl::IDNS_Member;
252 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000253 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000254 break;
255
256 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000257 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
258 break;
259
Douglas Gregor889ceb72009-02-03 19:21:40 +0000260 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000261 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000262 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000263
John McCall84d87672009-12-10 09:41:52 +0000264 case Sema::LookupUsingDeclName:
265 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
266 | Decl::IDNS_Member | Decl::IDNS_Using;
267 break;
268
Douglas Gregor79947a22009-04-24 00:11:27 +0000269 case Sema::LookupObjCProtocolName:
270 IDNS = Decl::IDNS_ObjCProtocol;
271 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000272
Douglas Gregor39982192010-08-15 06:18:01 +0000273 case Sema::LookupAnyName:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000274 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor39982192010-08-15 06:18:01 +0000275 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
276 | Decl::IDNS_Type;
277 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000278 }
279 return IDNS;
280}
281
John McCallea305ed2009-12-18 10:40:03 +0000282void LookupResult::configure() {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000283 IDNS = getIDNS(LookupKind, SemaRef.getLangOptions().CPlusPlus,
John McCallea305ed2009-12-18 10:40:03 +0000284 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000285
286 // If we're looking for one of the allocation or deallocation
287 // operators, make sure that the implicitly-declared new and delete
288 // operators can be found.
289 if (!isForRedeclaration()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000290 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000291 case OO_New:
292 case OO_Delete:
293 case OO_Array_New:
294 case OO_Array_Delete:
295 SemaRef.DeclareGlobalNewDelete();
296 break;
297
298 default:
299 break;
300 }
301 }
John McCallea305ed2009-12-18 10:40:03 +0000302}
303
John McCall19c1bfd2010-08-25 05:32:35 +0000304void LookupResult::sanity() const {
305 assert(ResultKind != NotFound || Decls.size() == 0);
306 assert(ResultKind != Found || Decls.size() == 1);
307 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
308 (Decls.size() == 1 &&
309 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
310 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
311 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000312 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
313 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall19c1bfd2010-08-25 05:32:35 +0000314 assert((Paths != NULL) == (ResultKind == Ambiguous &&
315 (Ambiguity == AmbiguousBaseSubobjectTypes ||
316 Ambiguity == AmbiguousBaseSubobjects)));
317}
John McCall19c1bfd2010-08-25 05:32:35 +0000318
John McCall9f3059a2009-10-09 21:13:30 +0000319// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000320void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000321 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000322}
323
Douglas Gregor4a814562011-12-14 16:03:29 +0000324static NamedDecl *getVisibleDecl(NamedDecl *D);
325
326NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
327 return getVisibleDecl(D);
328}
329
John McCall283b9012009-11-22 00:44:51 +0000330/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000331void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000332 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000333
John McCall9f3059a2009-10-09 21:13:30 +0000334 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000335 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000336 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000337 return;
338 }
339
John McCall283b9012009-11-22 00:44:51 +0000340 // If there's a single decl, we need to examine it to decide what
341 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000342 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000343 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
344 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000345 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000346 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000347 ResultKind = FoundUnresolvedValue;
348 return;
349 }
John McCall9f3059a2009-10-09 21:13:30 +0000350
John McCall6538c932009-10-10 05:48:19 +0000351 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000352 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000353
John McCall9f3059a2009-10-09 21:13:30 +0000354 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor13e65872010-08-11 14:45:53 +0000355 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000356
John McCall9f3059a2009-10-09 21:13:30 +0000357 bool Ambiguous = false;
358 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000359 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000360
361 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000362
John McCall9f3059a2009-10-09 21:13:30 +0000363 unsigned I = 0;
364 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000365 NamedDecl *D = Decls[I]->getUnderlyingDecl();
366 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000367
Douglas Gregor13e65872010-08-11 14:45:53 +0000368 // Redeclarations of types via typedef can occur both within a scope
369 // and, through using declarations and directives, across scopes. There is
370 // no ambiguity if they all refer to the same type, so unique based on the
371 // canonical type.
372 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
373 if (!TD->getDeclContext()->isRecord()) {
374 QualType T = SemaRef.Context.getTypeDeclType(TD);
375 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
376 // The type is not unique; pull something off the back and continue
377 // at this index.
378 Decls[I] = Decls[--N];
379 continue;
380 }
381 }
382 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000383
John McCallf0f1cf02009-11-17 07:50:12 +0000384 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000385 // If it's not unique, pull something off the back (and
386 // continue at this index).
387 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000388 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000389 }
390
Douglas Gregor13e65872010-08-11 14:45:53 +0000391 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000392
Douglas Gregor13e65872010-08-11 14:45:53 +0000393 if (isa<UnresolvedUsingValueDecl>(D)) {
394 HasUnresolved = true;
395 } else if (isa<TagDecl>(D)) {
396 if (HasTag)
397 Ambiguous = true;
398 UniqueTagIndex = I;
399 HasTag = true;
400 } else if (isa<FunctionTemplateDecl>(D)) {
401 HasFunction = true;
402 HasFunctionTemplate = true;
403 } else if (isa<FunctionDecl>(D)) {
404 HasFunction = true;
405 } else {
406 if (HasNonFunction)
407 Ambiguous = true;
408 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000409 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000410 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000411 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000412
John McCall9f3059a2009-10-09 21:13:30 +0000413 // C++ [basic.scope.hiding]p2:
414 // A class name or enumeration name can be hidden by the name of
415 // an object, function, or enumerator declared in the same
416 // scope. If a class or enumeration name and an object, function,
417 // or enumerator are declared in the same scope (in any order)
418 // with the same name, the class or enumeration name is hidden
419 // wherever the object, function, or enumerator name is visible.
420 // But it's still an error if there are distinct tag types found,
421 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000422 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000423 (HasFunction || HasNonFunction || HasUnresolved)) {
424 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
425 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
426 Decls[UniqueTagIndex] = Decls[--N];
427 else
428 Ambiguous = true;
429 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000430
John McCall9f3059a2009-10-09 21:13:30 +0000431 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000432
John McCall80053822009-12-03 00:58:24 +0000433 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000434 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000435
John McCall9f3059a2009-10-09 21:13:30 +0000436 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000437 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000438 else if (HasUnresolved)
439 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000440 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000441 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000442 else
John McCall27b18f82009-11-17 02:14:36 +0000443 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000444}
445
John McCall5cebab12009-11-18 07:57:50 +0000446void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000447 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000448 DeclContext::lookup_iterator DI, DE;
449 for (I = P.begin(), E = P.end(); I != E; ++I)
450 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
451 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000452}
453
John McCall5cebab12009-11-18 07:57:50 +0000454void LookupResult::setAmbiguousBaseSubobjects(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(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000460}
461
John McCall5cebab12009-11-18 07:57:50 +0000462void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000463 Paths = new CXXBasePaths;
464 Paths->swap(P);
465 addDeclsFromBasePaths(*Paths);
466 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000467 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000468}
469
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000470void LookupResult::print(raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000471 Out << Decls.size() << " result(s)";
472 if (isAmbiguous()) Out << ", ambiguous";
473 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000474
John McCall9f3059a2009-10-09 21:13:30 +0000475 for (iterator I = begin(), E = end(); I != E; ++I) {
476 Out << "\n";
477 (*I)->print(Out, 2);
478 }
479}
480
Douglas Gregord3a59182010-02-12 05:48:04 +0000481/// \brief Lookup a builtin function, when name lookup would otherwise
482/// fail.
483static bool LookupBuiltin(Sema &S, LookupResult &R) {
484 Sema::LookupNameKind NameKind = R.getLookupKind();
485
486 // If we didn't find a use of this identifier, and if the identifier
487 // corresponds to a compiler builtin, create the decl object for the builtin
488 // now, injecting it into translation unit scope, and return it.
489 if (NameKind == Sema::LookupOrdinaryName ||
490 NameKind == Sema::LookupRedeclarationWithLinkage) {
491 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
492 if (II) {
493 // If this is a builtin on this (or all) targets, create the decl.
494 if (unsigned BuiltinID = II->getBuiltinID()) {
495 // In C++, we don't have any predefined library functions like
496 // 'malloc'. Instead, we'll just error.
497 if (S.getLangOptions().CPlusPlus &&
498 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
499 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000500
501 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
502 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000503 R.isForRedeclaration(),
504 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000505 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000506 return true;
507 }
508
509 if (R.isForRedeclaration()) {
510 // If we're redeclaring this function anyway, forget that
511 // this was a builtin at all.
512 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
513 }
514
515 return false;
Douglas Gregord3a59182010-02-12 05:48:04 +0000516 }
517 }
518 }
519
520 return false;
521}
522
Douglas Gregor7454c562010-07-02 20:37:36 +0000523/// \brief Determine whether we can declare a special member function within
524/// the class at this point.
525static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
526 const CXXRecordDecl *Class) {
John McCall2ded5d22010-08-11 23:52:36 +0000527 // Don't do it if the class is invalid.
528 if (Class->isInvalidDecl())
529 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000530
Douglas Gregor7454c562010-07-02 20:37:36 +0000531 // We need to have a definition for the class.
532 if (!Class->getDefinition() || Class->isDependentContext())
533 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000534
Douglas Gregor7454c562010-07-02 20:37:36 +0000535 // We can't be in the middle of defining the class.
536 if (const RecordType *RecordTy
537 = Context.getTypeDeclType(Class)->getAs<RecordType>())
538 return !RecordTy->isBeingDefined();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000539
Douglas Gregor7454c562010-07-02 20:37:36 +0000540 return false;
541}
542
543void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000544 if (!CanDeclareSpecialMemberFunction(Context, Class))
545 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000546
547 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000548 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000549 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000550
Douglas Gregora6d69502010-07-02 23:41:54 +0000551 // If the copy constructor has not yet been declared, do so now.
552 if (!Class->hasDeclaredCopyConstructor())
553 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000554
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000555 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000556 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000557 DeclareImplicitCopyAssignment(Class);
558
Sebastian Redl22653ba2011-08-30 19:58:05 +0000559 if (getLangOptions().CPlusPlus0x) {
560 // If the move constructor has not yet been declared, do so now.
561 if (Class->needsImplicitMoveConstructor())
562 DeclareImplicitMoveConstructor(Class); // might not actually do it
563
564 // If the move assignment operator has not yet been declared, do so now.
565 if (Class->needsImplicitMoveAssignment())
566 DeclareImplicitMoveAssignment(Class); // might not actually do it
567 }
568
Douglas Gregor7454c562010-07-02 20:37:36 +0000569 // If the destructor has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000570 if (!Class->hasDeclaredDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000571 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000572}
573
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000574/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000575/// special member function.
576static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
577 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000578 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000579 case DeclarationName::CXXDestructorName:
580 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000581
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000582 case DeclarationName::CXXOperatorName:
583 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000584
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000585 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000586 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000587 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000588
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000589 return false;
590}
591
592/// \brief If there are any implicit member functions with the given name
593/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000594static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000595 DeclarationName Name,
596 const DeclContext *DC) {
597 if (!DC)
598 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000599
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000600 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000601 case DeclarationName::CXXConstructorName:
602 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor9672f922010-07-03 00:47:00 +0000603 if (Record->getDefinition() &&
604 CanDeclareSpecialMemberFunction(S.Context, Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000605 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000606 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000607 S.DeclareImplicitDefaultConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000608 if (!Record->hasDeclaredCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000609 S.DeclareImplicitCopyConstructor(Class);
610 if (S.getLangOptions().CPlusPlus0x &&
611 Record->needsImplicitMoveConstructor())
612 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000613 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000614 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000615
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000616 case DeclarationName::CXXDestructorName:
617 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
618 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
619 CanDeclareSpecialMemberFunction(S.Context, Record))
620 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000621 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000622
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000623 case DeclarationName::CXXOperatorName:
624 if (Name.getCXXOverloadedOperator() != OO_Equal)
625 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000626
Sebastian Redl22653ba2011-08-30 19:58:05 +0000627 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
628 if (Record->getDefinition() &&
629 CanDeclareSpecialMemberFunction(S.Context, Record)) {
630 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
631 if (!Record->hasDeclaredCopyAssignment())
632 S.DeclareImplicitCopyAssignment(Class);
633 if (S.getLangOptions().CPlusPlus0x &&
634 Record->needsImplicitMoveAssignment())
635 S.DeclareImplicitMoveAssignment(Class);
636 }
637 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000638 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000639
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000640 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000641 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000642 }
643}
Douglas Gregor7454c562010-07-02 20:37:36 +0000644
John McCall9f3059a2009-10-09 21:13:30 +0000645// Adds all qualifying matches for a name within a decl context to the
646// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000647static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000648 bool Found = false;
649
Douglas Gregor7454c562010-07-02 20:37:36 +0000650 // Lazily declare C++ special member functions.
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000651 if (S.getLangOptions().CPlusPlus)
652 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000653
Douglas Gregor7454c562010-07-02 20:37:36 +0000654 // Perform lookup into this declaration context.
John McCallf6c8a4e2009-11-10 07:01:13 +0000655 DeclContext::lookup_const_iterator I, E;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000656 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall401982f2010-01-20 21:53:11 +0000657 NamedDecl *D = *I;
Douglas Gregor4a814562011-12-14 16:03:29 +0000658 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000659 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000660 Found = true;
661 }
662 }
John McCall9f3059a2009-10-09 21:13:30 +0000663
Douglas Gregord3a59182010-02-12 05:48:04 +0000664 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
665 return true;
666
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000667 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000668 != DeclarationName::CXXConversionFunctionName ||
669 R.getLookupName().getCXXNameType()->isDependentType() ||
670 !isa<CXXRecordDecl>(DC))
671 return Found;
672
673 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000674 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000675 // name lookup. Instead, any conversion function templates visible in the
676 // context of the use are considered. [...]
677 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000678 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000679 return Found;
680
681 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000682 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
Chandler Carruth3a693b72010-01-31 11:44:02 +0000683 UEnd = Unresolved->end(); U != UEnd; ++U) {
684 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
685 if (!ConvTemplate)
686 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000687
Chandler Carruth3a693b72010-01-31 11:44:02 +0000688 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000689 // add the conversion function template. When we deduce template
690 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000691 // type of the new declaration with the type of the function template.
692 if (R.isForRedeclaration()) {
693 R.addDecl(ConvTemplate);
694 Found = true;
695 continue;
696 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000697
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000698 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000699 // [...] For each such operator, if argument deduction succeeds
700 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000701 // name lookup.
702 //
703 // When referencing a conversion function for any purpose other than
704 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000705 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000706 // specialization into the result set. We do this to avoid forcing all
707 // callers to perform special deduction for conversion functions.
John McCall19c1bfd2010-08-25 05:32:35 +0000708 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruth3a693b72010-01-31 11:44:02 +0000709 FunctionDecl *Specialization = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000710
711 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000712 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
713 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000714
Chandler Carruth3a693b72010-01-31 11:44:02 +0000715 // Compute the type of the function that we would expect the conversion
716 // function to have, if it were to match the name given.
717 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000718 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
719 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
Sebastian Redl7c6c9e92011-03-06 10:52:04 +0000720 EPI.ExceptionSpecType = EST_None;
John McCalldb40c7f2010-12-14 08:05:40 +0000721 EPI.NumExceptions = 0;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000722 QualType ExpectedType
723 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
John McCalldb40c7f2010-12-14 08:05:40 +0000724 0, 0, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000725
Chandler Carruth3a693b72010-01-31 11:44:02 +0000726 // Perform template argument deduction against the type that we would
727 // expect the function to have.
728 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
729 Specialization, Info)
730 == Sema::TDK_Success) {
731 R.addDecl(Specialization);
732 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000733 }
734 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000735
John McCall9f3059a2009-10-09 21:13:30 +0000736 return Found;
737}
738
John McCallf6c8a4e2009-11-10 07:01:13 +0000739// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000740static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000741CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000742 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000743
744 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
745
John McCallf6c8a4e2009-11-10 07:01:13 +0000746 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000747 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000748
John McCallf6c8a4e2009-11-10 07:01:13 +0000749 // Perform direct name lookup into the namespaces nominated by the
750 // using directives whose common ancestor is this namespace.
751 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
752 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000753
John McCallf6c8a4e2009-11-10 07:01:13 +0000754 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000755 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000756 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000757
758 R.resolveKind();
759
760 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000761}
762
763static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000764 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000765 return Ctx->isFileContext();
766 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000767}
Douglas Gregored8f2882009-01-30 01:04:22 +0000768
Douglas Gregor66230062010-03-15 14:33:29 +0000769// Find the next outer declaration context from this scope. This
770// routine actually returns the semantic outer context, which may
771// differ from the lexical context (encoded directly in the Scope
772// stack) when we are parsing a member of a class template. In this
773// case, the second element of the pair will be true, to indicate that
774// name lookup should continue searching in this semantic context when
775// it leaves the current template parameter scope.
776static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
777 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
778 DeclContext *Lexical = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000779 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000780 OuterS = OuterS->getParent()) {
781 if (OuterS->getEntity()) {
Douglas Gregorea166062010-03-15 15:26:48 +0000782 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor66230062010-03-15 14:33:29 +0000783 break;
784 }
785 }
786
787 // C++ [temp.local]p8:
788 // In the definition of a member of a class template that appears
789 // outside of the namespace containing the class template
790 // definition, the name of a template-parameter hides the name of
791 // a member of this namespace.
792 //
793 // Example:
794 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000795 // namespace N {
796 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000797 //
798 // template<class T> class B {
799 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000800 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000801 // }
802 //
803 // template<class C> void N::B<C>::f(C) {
804 // C b; // C is the template parameter, not N::C
805 // }
806 //
807 // In this example, the lexical context we return is the
808 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000809 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000810 !S->getParent()->isTemplateParamScope())
811 return std::make_pair(Lexical, false);
812
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000813 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000814 // For the example, this is the scope for the template parameters of
815 // template<class C>.
816 Scope *OutermostTemplateScope = S->getParent();
817 while (OutermostTemplateScope->getParent() &&
818 OutermostTemplateScope->getParent()->isTemplateParamScope())
819 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000820
Douglas Gregor66230062010-03-15 14:33:29 +0000821 // Find the namespace context in which the original scope occurs. In
822 // the example, this is namespace N.
823 DeclContext *Semantic = DC;
824 while (!Semantic->isFileContext())
825 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000826
Douglas Gregor66230062010-03-15 14:33:29 +0000827 // Find the declaration context just outside of the template
828 // parameter scope. This is the context in which the template is
829 // being lexically declaration (a namespace context). In the
830 // example, this is the global scope.
831 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
832 Lexical->Encloses(Semantic))
833 return std::make_pair(Semantic, true);
834
835 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000836}
837
John McCall27b18f82009-11-17 02:14:36 +0000838bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCallea305ed2009-12-18 10:40:03 +0000839 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000840
841 DeclarationName Name = R.getLookupName();
842
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000843 // If this is the name of an implicitly-declared special member function,
844 // go through the scope stack to implicitly declare
845 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
846 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
847 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
848 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
849 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000850
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000851 // Implicitly declare member functions with the name we're looking for, if in
852 // fact we are in a scope where it matters.
853
Douglas Gregor889ceb72009-02-03 19:21:40 +0000854 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000855 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000856 I = IdResolver.begin(Name),
857 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000858
Douglas Gregor889ceb72009-02-03 19:21:40 +0000859 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000860 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000861 // ...During unqualified name lookup (3.4.1), the names appear as if
862 // they were declared in the nearest enclosing namespace which contains
863 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000864 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000865 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000866 //
867 // For example:
868 // namespace A { int i; }
869 // void foo() {
870 // int i;
871 // {
872 // using namespace A;
873 // ++i; // finds local 'i', A::i appears at global scope
874 // }
875 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000876 //
Douglas Gregor66230062010-03-15 14:33:29 +0000877 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor700792c2009-02-05 19:25:20 +0000878 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor3e51e172010-05-20 20:58:56 +0000879 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
880
Douglas Gregor889ceb72009-02-03 19:21:40 +0000881 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000882 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000883 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000884 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
John McCall9f3059a2009-10-09 21:13:30 +0000885 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +0000886 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000887 }
888 }
John McCall9f3059a2009-10-09 21:13:30 +0000889 if (Found) {
890 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000891 if (S->isClassScope())
892 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
893 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000894 return true;
895 }
896
Douglas Gregor66230062010-03-15 14:33:29 +0000897 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
898 S->getParent() && !S->getParent()->isTemplateParamScope()) {
899 // We've just searched the last template parameter scope and
900 // found nothing, so look into the the contexts between the
901 // lexical and semantic declaration contexts returned by
902 // findOuterContext(). This implements the name lookup behavior
903 // of C++ [temp.local]p8.
904 Ctx = OutsideOfTemplateParamDC;
905 OutsideOfTemplateParamDC = 0;
906 }
907
908 if (Ctx) {
909 DeclContext *OuterCtx;
910 bool SearchAfterTemplateScope;
911 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
912 if (SearchAfterTemplateScope)
913 OutsideOfTemplateParamDC = OuterCtx;
914
Douglas Gregorea166062010-03-15 15:26:48 +0000915 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000916 // We do not directly look into transparent contexts, since
917 // those entities will be found in the nearest enclosing
918 // non-transparent context.
919 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000920 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000921
922 // We do not look directly into function or method contexts,
923 // since all of the local variables and parameters of the
924 // function/method are present within the Scope.
925 if (Ctx->isFunctionOrMethod()) {
926 // If we have an Objective-C instance method, look for ivars
927 // in the corresponding interface.
928 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
929 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
930 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
931 ObjCInterfaceDecl *ClassDeclared;
932 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000933 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +0000934 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000935 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
936 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +0000937 R.resolveKind();
938 return true;
939 }
940 }
941 }
942 }
943
944 continue;
945 }
946
Douglas Gregor7f737c02009-09-10 16:57:35 +0000947 // Perform qualified name lookup into this context.
948 // FIXME: In some cases, we know that every name that could be found by
949 // this qualified name lookup will also be on the identifier chain. For
950 // example, inside a class without any base classes, we never need to
951 // perform qualified lookup because all of the members are on top of the
952 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000953 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +0000954 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000955 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000956 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000957 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000958
John McCallf6c8a4e2009-11-10 07:01:13 +0000959 // Stop if we ran out of scopes.
960 // FIXME: This really, really shouldn't be happening.
961 if (!S) return false;
962
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +0000963 // If we are looking for members, no need to look into global/namespace scope.
964 if (R.getLookupKind() == LookupMemberName)
965 return false;
966
Douglas Gregor700792c2009-02-05 19:25:20 +0000967 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000968 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000969 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000970 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
971 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000972
John McCallf6c8a4e2009-11-10 07:01:13 +0000973 UnqualUsingDirectiveSet UDirs;
974 UDirs.visitScopeChain(Initial, S);
975 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000976
Douglas Gregor700792c2009-02-05 19:25:20 +0000977 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000978 // Unqualified name lookup in C++ requires looking into scopes
979 // that aren't strictly lexical, and therefore we walk through the
980 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000981
Douglas Gregor889ceb72009-02-03 19:21:40 +0000982 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000983 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000984 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000985 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000986 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000987 // We found something. Look for anything else in our scope
988 // with this same name and in an acceptable identifier
989 // namespace, so that we can construct an overload set if we
990 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000991 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +0000992 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000993 }
994 }
995
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000996 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +0000997 R.resolveKind();
998 return true;
999 }
1000
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001001 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1002 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1003 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1004 // We've just searched the last template parameter scope and
1005 // found nothing, so look into the the contexts between the
1006 // lexical and semantic declaration contexts returned by
1007 // findOuterContext(). This implements the name lookup behavior
1008 // of C++ [temp.local]p8.
1009 Ctx = OutsideOfTemplateParamDC;
1010 OutsideOfTemplateParamDC = 0;
1011 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001012
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001013 if (Ctx) {
1014 DeclContext *OuterCtx;
1015 bool SearchAfterTemplateScope;
1016 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1017 if (SearchAfterTemplateScope)
1018 OutsideOfTemplateParamDC = OuterCtx;
1019
1020 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1021 // We do not directly look into transparent contexts, since
1022 // those entities will be found in the nearest enclosing
1023 // non-transparent context.
1024 if (Ctx->isTransparentContext())
1025 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001026
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001027 // If we have a context, and it's not a context stashed in the
1028 // template parameter scope for an out-of-line definition, also
1029 // look into that context.
1030 if (!(Found && S && S->isTemplateParamScope())) {
1031 assert(Ctx->isFileContext() &&
1032 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001033
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001034 // Look into context considering using-directives.
1035 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1036 Found = true;
1037 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001038
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001039 if (Found) {
1040 R.resolveKind();
1041 return true;
1042 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001043
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001044 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1045 return false;
1046 }
1047 }
1048
Douglas Gregor3ce74932010-02-05 07:07:10 +00001049 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001050 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001051 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001052
John McCall9f3059a2009-10-09 21:13:30 +00001053 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001054}
1055
Douglas Gregor4a814562011-12-14 16:03:29 +00001056/// \brief Retrieve the previous declaration of D.
1057static NamedDecl *getPreviousDeclaration(NamedDecl *D) {
1058 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1059 return TD->getPreviousDeclaration();
1060 if (VarDecl *VD = dyn_cast<VarDecl>(D))
1061 return VD->getPreviousDeclaration();
1062 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1063 return FD->getPreviousDeclaration();
1064 if (RedeclarableTemplateDecl *RTD = dyn_cast<RedeclarableTemplateDecl>(D))
1065 return RTD->getPreviousDeclaration();
Douglas Gregor05f10352011-12-17 23:38:30 +00001066 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
1067 return TD->getPreviousDeclaration();
Douglas Gregor95ab1862011-12-15 20:36:27 +00001068 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
1069 return ID->getPreviousDeclaration();
Douglas Gregora715bff2012-01-01 19:51:50 +00001070 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
1071 return PD->getPreviousDeclaration();
Douglas Gregor4a814562011-12-14 16:03:29 +00001072
1073 return 0;
1074}
1075
1076/// \brief Retrieve the visible declaration corresponding to D, if any.
1077///
1078/// This routine determines whether the declaration D is visible in the current
1079/// module, with the current imports. If not, it checks whether any
1080/// redeclaration of D is visible, and if so, returns that declaration.
1081///
1082/// \returns D, or a visible previous declaration of D, whichever is more recent
1083/// and visible. If no declaration of D is visible, returns null.
1084static NamedDecl *getVisibleDecl(NamedDecl *D) {
1085 if (LookupResult::isVisible(D))
1086 return D;
1087
1088 while ((D = getPreviousDeclaration(D))) {
1089 if (LookupResult::isVisible(D))
1090 return D;
1091 }
1092
1093 return 0;
1094}
1095
Douglas Gregor34074322009-01-14 22:20:51 +00001096/// @brief Perform unqualified name lookup starting from a given
1097/// scope.
1098///
1099/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1100/// used to find names within the current scope. For example, 'x' in
1101/// @code
1102/// int x;
1103/// int f() {
1104/// return x; // unqualified name look finds 'x' in the global scope
1105/// }
1106/// @endcode
1107///
1108/// Different lookup criteria can find different names. For example, a
1109/// particular scope can have both a struct and a function of the same
1110/// name, and each can be found by certain lookup criteria. For more
1111/// information about lookup criteria, see the documentation for the
1112/// class LookupCriteria.
1113///
1114/// @param S The scope from which unqualified name lookup will
1115/// begin. If the lookup criteria permits, name lookup may also search
1116/// in the parent scopes.
1117///
1118/// @param Name The name of the entity that we are searching for.
1119///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001120/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001121/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001122/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +00001123///
1124/// @returns The result of name lookup, which includes zero or more
1125/// declarations and possibly additional information used to diagnose
1126/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +00001127bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1128 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001129 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001130
John McCall27b18f82009-11-17 02:14:36 +00001131 LookupNameKind NameKind = R.getLookupKind();
1132
Douglas Gregor34074322009-01-14 22:20:51 +00001133 if (!getLangOptions().CPlusPlus) {
1134 // Unqualified name lookup in C/Objective-C is purely lexical, so
1135 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001136 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001137 // Find the nearest non-transparent declaration scope.
1138 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +00001139 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +00001140 static_cast<DeclContext *>(S->getEntity())
1141 ->isTransparentContext()))
1142 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001143 }
1144
John McCallea305ed2009-12-18 10:40:03 +00001145 unsigned IDNS = R.getIdentifierNamespace();
1146
Douglas Gregor34074322009-01-14 22:20:51 +00001147 // Scan up the scope chain looking for a decl that matches this
1148 // identifier that is in the appropriate namespace. This search
1149 // should not take long, as shadowing of names is uncommon, and
1150 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001151 bool LeftStartingScope = false;
1152
Douglas Gregored8f2882009-01-30 01:04:22 +00001153 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001154 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001155 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001156 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001157 if (NameKind == LookupRedeclarationWithLinkage) {
1158 // Determine whether this (or a previous) declaration is
1159 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001160 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001161 LeftStartingScope = true;
1162
1163 // If we found something outside of our starting scope that
1164 // does not have linkage, skip it.
1165 if (LeftStartingScope && !((*I)->hasLinkage()))
1166 continue;
1167 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001168 else if (NameKind == LookupObjCImplicitSelfParam &&
1169 !isa<ImplicitParamDecl>(*I))
1170 continue;
1171
Douglas Gregor2a5d1482011-12-02 20:08:44 +00001172 // If this declaration is module-private and it came from an AST
1173 // file, we can't see it.
Douglas Gregor21823bf2011-12-20 18:11:52 +00001174 NamedDecl *D = R.isForRedeclaration()? *I : getVisibleDecl(*I);
Douglas Gregor4a814562011-12-14 16:03:29 +00001175 if (!D)
Douglas Gregor2a5d1482011-12-02 20:08:44 +00001176 continue;
Douglas Gregor4a814562011-12-14 16:03:29 +00001177
1178 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001179
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001180 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001181 // If this declaration has the "overloadable" attribute, we
1182 // might have a set of overloaded functions.
1183
1184 // Figure out what scope the identifier is in.
Chris Lattner83f095c2009-03-28 19:18:32 +00001185 while (!(S->getFlags() & Scope::DeclScope) ||
John McCall48871652010-08-21 09:40:31 +00001186 !S->isDeclScope(*I))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001187 S = S->getParent();
1188
1189 // Find the last declaration in this scope (with the same
1190 // name, naturally).
1191 IdentifierResolver::iterator LastI = I;
1192 for (++LastI; LastI != IEnd; ++LastI) {
John McCall48871652010-08-21 09:40:31 +00001193 if (!S->isDeclScope(*LastI))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001194 break;
Douglas Gregor4a814562011-12-14 16:03:29 +00001195
1196 D = getVisibleDecl(*LastI);
1197 if (D)
1198 R.addDecl(D);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001199 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001200 }
1201
John McCall9f3059a2009-10-09 21:13:30 +00001202 R.resolveKind();
1203
1204 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001205 }
Douglas Gregor34074322009-01-14 22:20:51 +00001206 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001207 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001208 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001209 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001210 }
1211
1212 // If we didn't find a use of this identifier, and if the identifier
1213 // corresponds to a compiler builtin, create the decl object for the builtin
1214 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001215 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1216 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001217
Axel Naumann016538a2011-02-24 16:47:47 +00001218 // If we didn't find a use of this identifier, the ExternalSource
1219 // may be able to handle the situation.
1220 // Note: some lookup failures are expected!
1221 // See e.g. R.isForRedeclaration().
1222 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001223}
1224
John McCall6538c932009-10-10 05:48:19 +00001225/// @brief Perform qualified name lookup in the namespaces nominated by
1226/// using directives by the given context.
1227///
1228/// C++98 [namespace.qual]p2:
1229/// Given X::m (where X is a user-declared namespace), or given ::m
1230/// (where X is the global namespace), let S be the set of all
1231/// declarations of m in X and in the transitive closure of all
1232/// namespaces nominated by using-directives in X and its used
1233/// namespaces, except that using-directives are ignored in any
1234/// namespace, including X, directly containing one or more
1235/// declarations of m. No namespace is searched more than once in
1236/// the lookup of a name. If S is the empty set, the program is
1237/// ill-formed. Otherwise, if S has exactly one member, or if the
1238/// context of the reference is a using-declaration
1239/// (namespace.udecl), S is the required set of declarations of
1240/// m. Otherwise if the use of m is not one that allows a unique
1241/// declaration to be chosen from S, the program is ill-formed.
1242/// C++98 [namespace.qual]p5:
1243/// During the lookup of a qualified namespace member name, if the
1244/// lookup finds more than one declaration of the member, and if one
1245/// declaration introduces a class name or enumeration name and the
1246/// other declarations either introduce the same object, the same
1247/// enumerator or a set of functions, the non-type name hides the
1248/// class or enumeration name if and only if the declarations are
1249/// from the same namespace; otherwise (the declarations are from
1250/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001251static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001252 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001253 assert(StartDC->isFileContext() && "start context is not a file context");
1254
1255 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1256 DeclContext::udir_iterator E = StartDC->using_directives_end();
1257
1258 if (I == E) return false;
1259
1260 // We have at least added all these contexts to the queue.
1261 llvm::DenseSet<DeclContext*> Visited;
1262 Visited.insert(StartDC);
1263
1264 // We have not yet looked into these namespaces, much less added
1265 // their "using-children" to the queue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001266 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001267
1268 // We have already looked into the initial namespace; seed the queue
1269 // with its using-children.
1270 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +00001271 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6538c932009-10-10 05:48:19 +00001272 if (Visited.insert(ND).second)
1273 Queue.push_back(ND);
1274 }
1275
1276 // The easiest way to implement the restriction in [namespace.qual]p5
1277 // is to check whether any of the individual results found a tag
1278 // and, if so, to declare an ambiguity if the final result is not
1279 // a tag.
1280 bool FoundTag = false;
1281 bool FoundNonTag = false;
1282
John McCall5cebab12009-11-18 07:57:50 +00001283 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001284
1285 bool Found = false;
1286 while (!Queue.empty()) {
1287 NamespaceDecl *ND = Queue.back();
1288 Queue.pop_back();
1289
1290 // We go through some convolutions here to avoid copying results
1291 // between LookupResults.
1292 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001293 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001294 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001295
1296 if (FoundDirect) {
1297 // First do any local hiding.
1298 DirectR.resolveKind();
1299
1300 // If the local result is a tag, remember that.
1301 if (DirectR.isSingleTagDecl())
1302 FoundTag = true;
1303 else
1304 FoundNonTag = true;
1305
1306 // Append the local results to the total results if necessary.
1307 if (UseLocal) {
1308 R.addAllDecls(LocalR);
1309 LocalR.clear();
1310 }
1311 }
1312
1313 // If we find names in this namespace, ignore its using directives.
1314 if (FoundDirect) {
1315 Found = true;
1316 continue;
1317 }
1318
1319 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1320 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1321 if (Visited.insert(Nom).second)
1322 Queue.push_back(Nom);
1323 }
1324 }
1325
1326 if (Found) {
1327 if (FoundTag && FoundNonTag)
1328 R.setAmbiguousQualifiedTagHiding();
1329 else
1330 R.resolveKind();
1331 }
1332
1333 return Found;
1334}
1335
Douglas Gregor39982192010-08-15 06:18:01 +00001336/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001337static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor39982192010-08-15 06:18:01 +00001338 CXXBasePath &Path,
1339 void *Name) {
1340 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001341
Douglas Gregor39982192010-08-15 06:18:01 +00001342 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1343 Path.Decls = BaseRecord->lookup(N);
1344 return Path.Decls.first != Path.Decls.second;
1345}
1346
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001347/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001348/// static members, nested types, and enumerators.
1349template<typename InputIterator>
1350static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1351 Decl *D = (*First)->getUnderlyingDecl();
1352 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1353 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001354
Douglas Gregorc0d24902010-10-22 22:08:47 +00001355 if (isa<CXXMethodDecl>(D)) {
1356 // Determine whether all of the methods are static.
1357 bool AllMethodsAreStatic = true;
1358 for(; First != Last; ++First) {
1359 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001360
Douglas Gregorc0d24902010-10-22 22:08:47 +00001361 if (!isa<CXXMethodDecl>(D)) {
1362 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1363 break;
1364 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001365
Douglas Gregorc0d24902010-10-22 22:08:47 +00001366 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1367 AllMethodsAreStatic = false;
1368 break;
1369 }
1370 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001371
Douglas Gregorc0d24902010-10-22 22:08:47 +00001372 if (AllMethodsAreStatic)
1373 return true;
1374 }
1375
1376 return false;
1377}
1378
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001379/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001380///
1381/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1382/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001383/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001384///
1385/// Different lookup criteria can find different names. For example, a
1386/// particular scope can have both a struct and a function of the same
1387/// name, and each can be found by certain lookup criteria. For more
1388/// information about lookup criteria, see the documentation for the
1389/// class LookupCriteria.
1390///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001391/// \param R captures both the lookup criteria and any lookup results found.
1392///
1393/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001394/// search. If the lookup criteria permits, name lookup may also search
1395/// in the parent contexts or (for C++ classes) base classes.
1396///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001397/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001398/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001399///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001400/// \returns true if lookup succeeded, false if it failed.
1401bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1402 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001403 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001404
John McCall27b18f82009-11-17 02:14:36 +00001405 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001406 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001407
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001408 // Make sure that the declaration context is complete.
1409 assert((!isa<TagDecl>(LookupCtx) ||
1410 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00001411 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001412 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1413 ->isBeingDefined()) &&
1414 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001415
Douglas Gregor34074322009-01-14 22:20:51 +00001416 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001417 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001418 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001419 if (isa<CXXRecordDecl>(LookupCtx))
1420 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001421 return true;
1422 }
Douglas Gregor34074322009-01-14 22:20:51 +00001423
John McCall6538c932009-10-10 05:48:19 +00001424 // Don't descend into implied contexts for redeclarations.
1425 // C++98 [namespace.qual]p6:
1426 // In a declaration for a namespace member in which the
1427 // declarator-id is a qualified-id, given that the qualified-id
1428 // for the namespace member has the form
1429 // nested-name-specifier unqualified-id
1430 // the unqualified-id shall name a member of the namespace
1431 // designated by the nested-name-specifier.
1432 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001433 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001434 return false;
1435
John McCall27b18f82009-11-17 02:14:36 +00001436 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001437 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001438 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001439
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001440 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001441 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001442 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001443 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001444 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001445
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001446 // If we're performing qualified name lookup into a dependent class,
1447 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001448 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001449 // template instantiation time (at which point all bases will be available)
1450 // or we have to fail.
1451 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1452 LookupRec->hasAnyDependentBases()) {
1453 R.setNotFoundInCurrentInstantiation();
1454 return false;
1455 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001456
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001457 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001458 CXXBasePaths Paths;
1459 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001460
1461 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001462 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001463 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001464 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001465 case LookupOrdinaryName:
1466 case LookupMemberName:
1467 case LookupRedeclarationWithLinkage:
1468 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1469 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001470
Douglas Gregor36d1b142009-10-06 17:59:45 +00001471 case LookupTagName:
1472 BaseCallback = &CXXRecordDecl::FindTagMember;
1473 break;
John McCall84d87672009-12-10 09:41:52 +00001474
Douglas Gregor39982192010-08-15 06:18:01 +00001475 case LookupAnyName:
1476 BaseCallback = &LookupAnyMember;
1477 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001478
John McCall84d87672009-12-10 09:41:52 +00001479 case LookupUsingDeclName:
1480 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001481
Douglas Gregor36d1b142009-10-06 17:59:45 +00001482 case LookupOperatorName:
1483 case LookupNamespaceName:
1484 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001485 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001486 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001487 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001488
Douglas Gregor36d1b142009-10-06 17:59:45 +00001489 case LookupNestedNameSpecifierName:
1490 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1491 break;
1492 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001493
John McCall27b18f82009-11-17 02:14:36 +00001494 if (!LookupRec->lookupInBases(BaseCallback,
1495 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001496 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001497
John McCall553c0792010-01-23 00:46:32 +00001498 R.setNamingClass(LookupRec);
1499
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001500 // C++ [class.member.lookup]p2:
1501 // [...] If the resulting set of declarations are not all from
1502 // sub-objects of the same type, or the set has a nonstatic member
1503 // and includes members from distinct sub-objects, there is an
1504 // ambiguity and the program is ill-formed. Otherwise that set is
1505 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001506 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001507 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001508 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001509
Douglas Gregor36d1b142009-10-06 17:59:45 +00001510 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001511 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001512 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001513
John McCall401982f2010-01-20 21:53:11 +00001514 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1515 // across all paths.
1516 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001517
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001518 // Determine whether we're looking at a distinct sub-object or not.
1519 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001520 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001521 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1522 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001523 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001524 }
1525
Douglas Gregorc0d24902010-10-22 22:08:47 +00001526 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001527 != Context.getCanonicalType(PathElement.Base->getType())) {
1528 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001529 // different types. If the declaration sets aren't the same, this
1530 // this lookup is ambiguous.
1531 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1532 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1533 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1534 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001535
Douglas Gregorc0d24902010-10-22 22:08:47 +00001536 while (FirstD != FirstPath->Decls.second &&
1537 CurrentD != Path->Decls.second) {
1538 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1539 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1540 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001541
Douglas Gregorc0d24902010-10-22 22:08:47 +00001542 ++FirstD;
1543 ++CurrentD;
1544 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001545
Douglas Gregorc0d24902010-10-22 22:08:47 +00001546 if (FirstD == FirstPath->Decls.second &&
1547 CurrentD == Path->Decls.second)
1548 continue;
1549 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001550
John McCall9f3059a2009-10-09 21:13:30 +00001551 R.setAmbiguousBaseSubobjectTypes(Paths);
1552 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001553 }
1554
Douglas Gregorc0d24902010-10-22 22:08:47 +00001555 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001556 // We have a different subobject of the same type.
1557
1558 // C++ [class.member.lookup]p5:
1559 // A static member, a nested type or an enumerator defined in
1560 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001561 // has more than one base class subobject of type T.
Douglas Gregorc0d24902010-10-22 22:08:47 +00001562 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001563 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001564
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001565 // We have found a nonstatic member name in multiple, distinct
1566 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001567 R.setAmbiguousBaseSubobjects(Paths);
1568 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001569 }
1570 }
1571
1572 // Lookup in a base class succeeded; return these results.
1573
John McCall9f3059a2009-10-09 21:13:30 +00001574 DeclContext::lookup_iterator I, E;
John McCall553c0792010-01-23 00:46:32 +00001575 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1576 NamedDecl *D = *I;
1577 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1578 D->getAccess());
1579 R.addDecl(D, AS);
1580 }
John McCall9f3059a2009-10-09 21:13:30 +00001581 R.resolveKind();
1582 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001583}
1584
1585/// @brief Performs name lookup for a name that was parsed in the
1586/// source code, and may contain a C++ scope specifier.
1587///
1588/// This routine is a convenience routine meant to be called from
1589/// contexts that receive a name and an optional C++ scope specifier
1590/// (e.g., "N::M::x"). It will then perform either qualified or
1591/// unqualified name lookup (with LookupQualifiedName or LookupName,
1592/// respectively) on the given name and return those results.
1593///
1594/// @param S The scope from which unqualified name lookup will
1595/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001596///
Douglas Gregore861bac2009-08-25 22:51:20 +00001597/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001598///
Douglas Gregore861bac2009-08-25 22:51:20 +00001599/// @param EnteringContext Indicates whether we are going to enter the
1600/// context of the scope-specifier SS (if present).
1601///
John McCall9f3059a2009-10-09 21:13:30 +00001602/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001603bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001604 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001605 if (SS && SS->isInvalid()) {
1606 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001607 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001608 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001609 }
Mike Stump11289f42009-09-09 15:08:12 +00001610
Douglas Gregore861bac2009-08-25 22:51:20 +00001611 if (SS && SS->isSet()) {
1612 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001613 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001614 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001615 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001616 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001617
John McCall27b18f82009-11-17 02:14:36 +00001618 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00001619 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001620 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001621
Douglas Gregore861bac2009-08-25 22:51:20 +00001622 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001623 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001624 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00001625 R.setNotFoundInCurrentInstantiation();
1626 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00001627 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001628 }
1629
Mike Stump11289f42009-09-09 15:08:12 +00001630 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001631 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001632}
1633
Douglas Gregor889ceb72009-02-03 19:21:40 +00001634
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001635/// @brief Produce a diagnostic describing the ambiguity that resulted
1636/// from name lookup.
1637///
1638/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001639///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001640/// @param Name The name of the entity that name lookup was
1641/// searching for.
1642///
1643/// @param NameLoc The location of the name within the source code.
1644///
1645/// @param LookupRange A source range that provides more
1646/// source-location information concerning the lookup itself. For
1647/// example, this range might highlight a nested-name-specifier that
1648/// precedes the name.
1649///
1650/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001651bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001652 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1653
John McCall27b18f82009-11-17 02:14:36 +00001654 DeclarationName Name = Result.getLookupName();
1655 SourceLocation NameLoc = Result.getNameLoc();
1656 SourceRange LookupRange = Result.getContextRange();
1657
John McCall6538c932009-10-10 05:48:19 +00001658 switch (Result.getAmbiguityKind()) {
1659 case LookupResult::AmbiguousBaseSubobjects: {
1660 CXXBasePaths *Paths = Result.getBasePaths();
1661 QualType SubobjectType = Paths->front().back().Base->getType();
1662 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1663 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1664 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001665
John McCall6538c932009-10-10 05:48:19 +00001666 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1667 while (isa<CXXMethodDecl>(*Found) &&
1668 cast<CXXMethodDecl>(*Found)->isStatic())
1669 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001670
John McCall6538c932009-10-10 05:48:19 +00001671 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001672
John McCall6538c932009-10-10 05:48:19 +00001673 return true;
1674 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001675
John McCall6538c932009-10-10 05:48:19 +00001676 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001677 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1678 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001679
John McCall6538c932009-10-10 05:48:19 +00001680 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001681 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001682 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1683 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001684 Path != PathEnd; ++Path) {
1685 Decl *D = *Path->Decls.first;
1686 if (DeclsPrinted.insert(D).second)
1687 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1688 }
1689
Douglas Gregor1c846b02009-01-16 00:38:09 +00001690 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001691 }
1692
John McCall6538c932009-10-10 05:48:19 +00001693 case LookupResult::AmbiguousTagHiding: {
1694 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001695
John McCall6538c932009-10-10 05:48:19 +00001696 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1697
1698 LookupResult::iterator DI, DE = Result.end();
1699 for (DI = Result.begin(); DI != DE; ++DI)
1700 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1701 TagDecls.insert(TD);
1702 Diag(TD->getLocation(), diag::note_hidden_tag);
1703 }
1704
1705 for (DI = Result.begin(); DI != DE; ++DI)
1706 if (!isa<TagDecl>(*DI))
1707 Diag((*DI)->getLocation(), diag::note_hiding_object);
1708
1709 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001710 LookupResult::Filter F = Result.makeFilter();
1711 while (F.hasNext()) {
1712 if (TagDecls.count(F.next()))
1713 F.erase();
1714 }
1715 F.done();
John McCall6538c932009-10-10 05:48:19 +00001716
1717 return true;
1718 }
1719
1720 case LookupResult::AmbiguousReference: {
1721 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001722
John McCall6538c932009-10-10 05:48:19 +00001723 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1724 for (; DI != DE; ++DI)
1725 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001726
John McCall6538c932009-10-10 05:48:19 +00001727 return true;
1728 }
1729 }
1730
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001731 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001732 return true;
1733}
Douglas Gregore254f902009-02-04 00:32:51 +00001734
John McCallf24d7bb2010-05-28 18:45:08 +00001735namespace {
1736 struct AssociatedLookup {
1737 AssociatedLookup(Sema &S,
1738 Sema::AssociatedNamespaceSet &Namespaces,
1739 Sema::AssociatedClassSet &Classes)
1740 : S(S), Namespaces(Namespaces), Classes(Classes) {
1741 }
1742
1743 Sema &S;
1744 Sema::AssociatedNamespaceSet &Namespaces;
1745 Sema::AssociatedClassSet &Classes;
1746 };
1747}
1748
Mike Stump11289f42009-09-09 15:08:12 +00001749static void
John McCallf24d7bb2010-05-28 18:45:08 +00001750addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001751
Douglas Gregor8b895222010-04-30 07:08:38 +00001752static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1753 DeclContext *Ctx) {
1754 // Add the associated namespace for this class.
1755
1756 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1757 // be a locally scoped record.
1758
Sebastian Redlbd595762010-08-31 20:53:31 +00001759 // We skip out of inline namespaces. The innermost non-inline namespace
1760 // contains all names of all its nested inline namespaces anyway, so we can
1761 // replace the entire inline namespace tree with its root.
1762 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1763 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00001764 Ctx = Ctx->getParent();
1765
John McCallc7e8e792009-08-07 22:18:02 +00001766 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001767 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001768}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001769
Mike Stump11289f42009-09-09 15:08:12 +00001770// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001771// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001772static void
John McCallf24d7bb2010-05-28 18:45:08 +00001773addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1774 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001775 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001776 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001777 switch (Arg.getKind()) {
1778 case TemplateArgument::Null:
1779 break;
Mike Stump11289f42009-09-09 15:08:12 +00001780
Douglas Gregor197e5f72009-07-08 07:51:57 +00001781 case TemplateArgument::Type:
1782 // [...] the namespaces and classes associated with the types of the
1783 // template arguments provided for template type parameters (excluding
1784 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001785 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001786 break;
Mike Stump11289f42009-09-09 15:08:12 +00001787
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001788 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001789 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00001790 // [...] the namespaces in which any template template arguments are
1791 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001792 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001793 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00001794 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001795 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001796 DeclContext *Ctx = ClassTemplate->getDeclContext();
1797 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001798 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001799 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001800 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001801 }
1802 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001803 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001804
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001805 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001806 case TemplateArgument::Integral:
1807 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001808 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001809 // associated namespaces. ]
1810 break;
Mike Stump11289f42009-09-09 15:08:12 +00001811
Douglas Gregor197e5f72009-07-08 07:51:57 +00001812 case TemplateArgument::Pack:
1813 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1814 PEnd = Arg.pack_end();
1815 P != PEnd; ++P)
John McCallf24d7bb2010-05-28 18:45:08 +00001816 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001817 break;
1818 }
1819}
1820
Douglas Gregore254f902009-02-04 00:32:51 +00001821// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001822// argument-dependent lookup with an argument of class type
1823// (C++ [basic.lookup.koenig]p2).
1824static void
John McCallf24d7bb2010-05-28 18:45:08 +00001825addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1826 CXXRecordDecl *Class) {
1827
1828 // Just silently ignore anything whose name is __va_list_tag.
1829 if (Class->getDeclName() == Result.S.VAListTagName)
1830 return;
1831
Douglas Gregore254f902009-02-04 00:32:51 +00001832 // C++ [basic.lookup.koenig]p2:
1833 // [...]
1834 // -- If T is a class type (including unions), its associated
1835 // classes are: the class itself; the class of which it is a
1836 // member, if any; and its direct and indirect base
1837 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001838 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001839
1840 // Add the class of which it is a member, if any.
1841 DeclContext *Ctx = Class->getDeclContext();
1842 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001843 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001844 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001845 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001846
Douglas Gregore254f902009-02-04 00:32:51 +00001847 // Add the class itself. If we've already seen this class, we don't
1848 // need to visit base classes.
John McCallf24d7bb2010-05-28 18:45:08 +00001849 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00001850 return;
1851
Mike Stump11289f42009-09-09 15:08:12 +00001852 // -- If T is a template-id, its associated namespaces and classes are
1853 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001854 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001855 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001856 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001857 // namespaces in which any template template arguments are defined; and
1858 // the classes in which any member templates used as template template
1859 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001860 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001861 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001862 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1863 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1864 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001865 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001866 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001867 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001868
Douglas Gregor197e5f72009-07-08 07:51:57 +00001869 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1870 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00001871 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001872 }
Mike Stump11289f42009-09-09 15:08:12 +00001873
John McCall67da35c2010-02-04 22:26:26 +00001874 // Only recurse into base classes for complete types.
1875 if (!Class->hasDefinition()) {
1876 // FIXME: we might need to instantiate templates here
1877 return;
1878 }
1879
Douglas Gregore254f902009-02-04 00:32:51 +00001880 // Add direct and indirect base classes along with their associated
1881 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001882 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00001883 Bases.push_back(Class);
1884 while (!Bases.empty()) {
1885 // Pop this class off the stack.
1886 Class = Bases.back();
1887 Bases.pop_back();
1888
1889 // Visit the base classes.
1890 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1891 BaseEnd = Class->bases_end();
1892 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001893 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001894 // In dependent contexts, we do ADL twice, and the first time around,
1895 // the base type might be a dependent TemplateSpecializationType, or a
1896 // TemplateTypeParmType. If that happens, simply ignore it.
1897 // FIXME: If we want to support export, we probably need to add the
1898 // namespace of the template in a TemplateSpecializationType, or even
1899 // the classes and namespaces of known non-dependent arguments.
1900 if (!BaseType)
1901 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001902 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001903 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00001904 // Find the associated namespace for this base class.
1905 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00001906 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001907
1908 // Make sure we visit the bases of this base class.
1909 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1910 Bases.push_back(BaseDecl);
1911 }
1912 }
1913 }
1914}
1915
1916// \brief Add the associated classes and namespaces for
1917// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001918// (C++ [basic.lookup.koenig]p2).
1919static void
John McCallf24d7bb2010-05-28 18:45:08 +00001920addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00001921 // C++ [basic.lookup.koenig]p2:
1922 //
1923 // For each argument type T in the function call, there is a set
1924 // of zero or more associated namespaces and a set of zero or more
1925 // associated classes to be considered. The sets of namespaces and
1926 // classes is determined entirely by the types of the function
1927 // arguments (and the namespace of any template template
1928 // argument). Typedef names and using-declarations used to specify
1929 // the types do not contribute to this set. The sets of namespaces
1930 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00001931
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001932 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00001933 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1934
Douglas Gregore254f902009-02-04 00:32:51 +00001935 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00001936 switch (T->getTypeClass()) {
1937
1938#define TYPE(Class, Base)
1939#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1940#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1941#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1942#define ABSTRACT_TYPE(Class, Base)
1943#include "clang/AST/TypeNodes.def"
1944 // T is canonical. We can also ignore dependent types because
1945 // we don't need to do ADL at the definition point, but if we
1946 // wanted to implement template export (or if we find some other
1947 // use for associated classes and namespaces...) this would be
1948 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00001949 break;
Douglas Gregore254f902009-02-04 00:32:51 +00001950
John McCall0af3d3b2010-05-28 06:08:54 +00001951 // -- If T is a pointer to U or an array of U, its associated
1952 // namespaces and classes are those associated with U.
1953 case Type::Pointer:
1954 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1955 continue;
1956 case Type::ConstantArray:
1957 case Type::IncompleteArray:
1958 case Type::VariableArray:
1959 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1960 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001961
John McCall0af3d3b2010-05-28 06:08:54 +00001962 // -- If T is a fundamental type, its associated sets of
1963 // namespaces and classes are both empty.
1964 case Type::Builtin:
1965 break;
1966
1967 // -- If T is a class type (including unions), its associated
1968 // classes are: the class itself; the class of which it is a
1969 // member, if any; and its direct and indirect base
1970 // classes. Its associated namespaces are the namespaces in
1971 // which its associated classes are defined.
1972 case Type::Record: {
1973 CXXRecordDecl *Class
1974 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001975 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00001976 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00001977 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00001978
John McCall0af3d3b2010-05-28 06:08:54 +00001979 // -- If T is an enumeration type, its associated namespace is
1980 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001981 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00001982 // it has no associated class.
1983 case Type::Enum: {
1984 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001985
John McCall0af3d3b2010-05-28 06:08:54 +00001986 DeclContext *Ctx = Enum->getDeclContext();
1987 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001988 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001989
John McCall0af3d3b2010-05-28 06:08:54 +00001990 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001991 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001992
John McCall0af3d3b2010-05-28 06:08:54 +00001993 break;
1994 }
1995
1996 // -- If T is a function type, its associated namespaces and
1997 // classes are those associated with the function parameter
1998 // types and those associated with the return type.
1999 case Type::FunctionProto: {
2000 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2001 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
2002 ArgEnd = Proto->arg_type_end();
2003 Arg != ArgEnd; ++Arg)
2004 Queue.push_back(Arg->getTypePtr());
2005 // fallthrough
2006 }
2007 case Type::FunctionNoProto: {
2008 const FunctionType *FnType = cast<FunctionType>(T);
2009 T = FnType->getResultType().getTypePtr();
2010 continue;
2011 }
2012
2013 // -- If T is a pointer to a member function of a class X, its
2014 // associated namespaces and classes are those associated
2015 // with the function parameter types and return type,
2016 // together with those associated with X.
2017 //
2018 // -- If T is a pointer to a data member of class X, its
2019 // associated namespaces and classes are those associated
2020 // with the member type together with those associated with
2021 // X.
2022 case Type::MemberPointer: {
2023 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2024
2025 // Queue up the class type into which this points.
2026 Queue.push_back(MemberPtr->getClass());
2027
2028 // And directly continue with the pointee type.
2029 T = MemberPtr->getPointeeType().getTypePtr();
2030 continue;
2031 }
2032
2033 // As an extension, treat this like a normal pointer.
2034 case Type::BlockPointer:
2035 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2036 continue;
2037
2038 // References aren't covered by the standard, but that's such an
2039 // obvious defect that we cover them anyway.
2040 case Type::LValueReference:
2041 case Type::RValueReference:
2042 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2043 continue;
2044
2045 // These are fundamental types.
2046 case Type::Vector:
2047 case Type::ExtVector:
2048 case Type::Complex:
2049 break;
2050
Douglas Gregor8e936662011-04-12 01:02:45 +00002051 // If T is an Objective-C object or interface type, or a pointer to an
2052 // object or interface type, the associated namespace is the global
2053 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002054 case Type::ObjCObject:
2055 case Type::ObjCInterface:
2056 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002057 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002058 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002059
2060 // Atomic types are just wrappers; use the associations of the
2061 // contained type.
2062 case Type::Atomic:
2063 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2064 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002065 }
2066
2067 if (Queue.empty()) break;
2068 T = Queue.back();
2069 Queue.pop_back();
Douglas Gregore254f902009-02-04 00:32:51 +00002070 }
Douglas Gregore254f902009-02-04 00:32:51 +00002071}
2072
2073/// \brief Find the associated classes and namespaces for
2074/// argument-dependent lookup for a call with the given set of
2075/// arguments.
2076///
2077/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002078/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002079/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002080void
Douglas Gregore254f902009-02-04 00:32:51 +00002081Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
2082 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00002083 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002084 AssociatedNamespaces.clear();
2085 AssociatedClasses.clear();
2086
John McCallf24d7bb2010-05-28 18:45:08 +00002087 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
2088
Douglas Gregore254f902009-02-04 00:32:51 +00002089 // C++ [basic.lookup.koenig]p2:
2090 // For each argument type T in the function call, there is a set
2091 // of zero or more associated namespaces and a set of zero or more
2092 // associated classes to be considered. The sets of namespaces and
2093 // classes is determined entirely by the types of the function
2094 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002095 // argument).
Douglas Gregore254f902009-02-04 00:32:51 +00002096 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
2097 Expr *Arg = Args[ArgIdx];
2098
2099 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002100 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002101 continue;
2102 }
2103
2104 // [...] In addition, if the argument is the name or address of a
2105 // set of overloaded functions and/or function templates, its
2106 // associated classes and namespaces are the union of those
2107 // associated with each of the members of the set: the namespace
2108 // in which the function or function template is defined and the
2109 // classes and namespaces associated with its (non-dependent)
2110 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002111 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002112 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002113 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002114 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002115
John McCallf24d7bb2010-05-28 18:45:08 +00002116 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2117 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002118
John McCallf24d7bb2010-05-28 18:45:08 +00002119 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2120 I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002121 // Look through any using declarations to find the underlying function.
2122 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002123
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002124 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2125 if (!FDecl)
2126 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002127
2128 // Add the classes and namespaces associated with the parameter
2129 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002130 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002131 }
2132 }
2133}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002134
2135/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2136/// an acceptable non-member overloaded operator for a call whose
2137/// arguments have types T1 (and, if non-empty, T2). This routine
2138/// implements the check in C++ [over.match.oper]p3b2 concerning
2139/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00002140static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002141IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2142 QualType T1, QualType T2,
2143 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00002144 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2145 return true;
2146
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002147 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2148 return true;
2149
John McCall9dd450b2009-09-21 23:43:11 +00002150 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002151 if (Proto->getNumArgs() < 1)
2152 return false;
2153
2154 if (T1->isEnumeralType()) {
2155 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002156 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002157 return true;
2158 }
2159
2160 if (Proto->getNumArgs() < 2)
2161 return false;
2162
2163 if (!T2.isNull() && T2->isEnumeralType()) {
2164 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002165 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002166 return true;
2167 }
2168
2169 return false;
2170}
2171
John McCall5cebab12009-11-18 07:57:50 +00002172NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002173 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002174 LookupNameKind NameKind,
2175 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002176 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002177 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002178 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002179}
2180
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002181/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002182ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002183 SourceLocation IdLoc,
2184 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002185 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002186 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002187 return cast_or_null<ObjCProtocolDecl>(D);
2188}
2189
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002190void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002191 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002192 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002193 // C++ [over.match.oper]p3:
2194 // -- The set of non-member candidates is the result of the
2195 // unqualified lookup of operator@ in the context of the
2196 // expression according to the usual rules for name lookup in
2197 // unqualified function calls (3.4.2) except that all member
2198 // functions are ignored. However, if no operand has a class
2199 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00002200 // that have a first parameter of type T1 or "reference to
2201 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002202 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00002203 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002204 // when T2 is an enumeration type, are candidate functions.
2205 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002206 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2207 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002208
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002209 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2210
John McCall9f3059a2009-10-09 21:13:30 +00002211 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002212 return;
2213
2214 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2215 Op != OpEnd; ++Op) {
Douglas Gregor645d76f2010-04-25 20:25:43 +00002216 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2217 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002218 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor645d76f2010-04-25 20:25:43 +00002219 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00002220 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor645d76f2010-04-25 20:25:43 +00002221 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor15448f82009-06-27 21:05:07 +00002222 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00002223 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00002224 // later?
2225 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor645d76f2010-04-25 20:25:43 +00002226 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor15448f82009-06-27 21:05:07 +00002227 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002228 }
2229}
2230
Alexis Hunt1da39282011-06-24 02:11:39 +00002231Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002232 CXXSpecialMember SM,
2233 bool ConstArg,
2234 bool VolatileArg,
2235 bool RValueThis,
2236 bool ConstThis,
2237 bool VolatileThis) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002238 RD = RD->getDefinition();
2239 assert((RD && !RD->isBeingDefined()) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002240 "doing special member lookup into record that isn't fully complete");
2241 if (RValueThis || ConstThis || VolatileThis)
2242 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2243 "constructors and destructors always have unqualified lvalue this");
2244 if (ConstArg || VolatileArg)
2245 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2246 "parameter-less special members can't have qualified arguments");
2247
2248 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002249 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002250 ID.AddInteger(SM);
2251 ID.AddInteger(ConstArg);
2252 ID.AddInteger(VolatileArg);
2253 ID.AddInteger(RValueThis);
2254 ID.AddInteger(ConstThis);
2255 ID.AddInteger(VolatileThis);
2256
2257 void *InsertPoint;
2258 SpecialMemberOverloadResult *Result =
2259 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2260
2261 // This was already cached
2262 if (Result)
2263 return Result;
2264
Alexis Huntba8e18d2011-06-07 00:11:58 +00002265 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2266 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002267 SpecialMemberCache.InsertNode(Result, InsertPoint);
2268
2269 if (SM == CXXDestructor) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002270 if (!RD->hasDeclaredDestructor())
2271 DeclareImplicitDestructor(RD);
2272 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002273 assert(DD && "record without a destructor");
2274 Result->setMethod(DD);
2275 Result->setSuccess(DD->isDeleted());
2276 Result->setConstParamMatch(false);
2277 return Result;
2278 }
2279
Alexis Hunteef8ee02011-06-10 03:50:41 +00002280 // Prepare for overload resolution. Here we construct a synthetic argument
2281 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002282 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002283 DeclarationName Name;
2284 Expr *Arg = 0;
2285 unsigned NumArgs;
2286
2287 if (SM == CXXDefaultConstructor) {
2288 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2289 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002290 if (RD->needsImplicitDefaultConstructor())
2291 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002292 } else {
2293 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2294 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Alexis Hunt1da39282011-06-24 02:11:39 +00002295 if (!RD->hasDeclaredCopyConstructor())
2296 DeclareImplicitCopyConstructor(RD);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002297 if (getLangOptions().CPlusPlus0x && RD->needsImplicitMoveConstructor())
2298 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002299 } else {
2300 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Alexis Hunt1da39282011-06-24 02:11:39 +00002301 if (!RD->hasDeclaredCopyAssignment())
2302 DeclareImplicitCopyAssignment(RD);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002303 if (getLangOptions().CPlusPlus0x && RD->needsImplicitMoveAssignment())
2304 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002305 }
2306
2307 QualType ArgType = CanTy;
2308 if (ConstArg)
2309 ArgType.addConst();
2310 if (VolatileArg)
2311 ArgType.addVolatile();
2312
2313 // This isn't /really/ specified by the standard, but it's implied
2314 // we should be working from an RValue in the case of move to ensure
2315 // that we prefer to bind to rvalue references, and an LValue in the
2316 // case of copy to ensure we don't bind to rvalue references.
2317 // Possibly an XValue is actually correct in the case of move, but
2318 // there is no semantic difference for class types in this restricted
2319 // case.
2320 ExprValueKind VK;
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002321 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002322 VK = VK_LValue;
2323 else
2324 VK = VK_RValue;
2325
2326 NumArgs = 1;
2327 Arg = new (Context) OpaqueValueExpr(SourceLocation(), ArgType, VK);
2328 }
2329
2330 // Create the object argument
2331 QualType ThisTy = CanTy;
2332 if (ConstThis)
2333 ThisTy.addConst();
2334 if (VolatileThis)
2335 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002336 Expr::Classification Classification =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002337 (new (Context) OpaqueValueExpr(SourceLocation(), ThisTy,
2338 RValueThis ? VK_RValue : VK_LValue))->
2339 Classify(Context);
2340
2341 // Now we perform lookup on the name we computed earlier and do overload
2342 // resolution. Lookup is only performed directly into the class since there
2343 // will always be a (possibly implicit) declaration to shadow any others.
2344 OverloadCandidateSet OCS((SourceLocation()));
2345 DeclContext::lookup_iterator I, E;
2346 Result->setConstParamMatch(false);
2347
Alexis Hunt1da39282011-06-24 02:11:39 +00002348 llvm::tie(I, E) = RD->lookup(Name);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002349 assert((I != E) &&
2350 "lookup for a constructor or assignment operator was empty");
2351 for ( ; I != E; ++I) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002352 Decl *Cand = *I;
Alexis Hunt080709f2011-06-23 00:26:20 +00002353
Alexis Hunt1da39282011-06-24 02:11:39 +00002354 if (Cand->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002355 continue;
2356
Alexis Hunt1da39282011-06-24 02:11:39 +00002357 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2358 // FIXME: [namespace.udecl]p15 says that we should only consider a
2359 // using declaration here if it does not match a declaration in the
2360 // derived class. We do not implement this correctly in other cases
2361 // either.
2362 Cand = U->getTargetDecl();
2363
2364 if (Cand->isInvalidDecl())
2365 continue;
2366 }
2367
2368 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002369 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Alexis Hunt1da39282011-06-24 02:11:39 +00002370 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Alexis Hunt080709f2011-06-23 00:26:20 +00002371 Classification, &Arg, NumArgs, OCS, true);
2372 else
2373 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public), &Arg,
2374 NumArgs, OCS, true);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002375
2376 // Here we're looking for a const parameter to speed up creation of
2377 // implicit copy methods.
2378 if ((SM == CXXCopyAssignment && M->isCopyAssignmentOperator()) ||
2379 (SM == CXXCopyConstructor &&
2380 cast<CXXConstructorDecl>(M)->isCopyConstructor())) {
2381 QualType ArgType = M->getType()->getAs<FunctionProtoType>()->getArgType(0);
Alexis Hunt491ec602011-06-21 23:42:56 +00002382 if (!ArgType->isReferenceType() ||
2383 ArgType->getPointeeType().isConstQualified())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002384 Result->setConstParamMatch(true);
2385 }
Alexis Hunt2949f022011-06-22 02:58:46 +00002386 } else if (FunctionTemplateDecl *Tmpl =
Alexis Hunt1da39282011-06-24 02:11:39 +00002387 dyn_cast<FunctionTemplateDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002388 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2389 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Alexis Hunt1da39282011-06-24 02:11:39 +00002390 RD, 0, ThisTy, Classification, &Arg, NumArgs,
Alexis Hunt080709f2011-06-23 00:26:20 +00002391 OCS, true);
2392 else
2393 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
2394 0, &Arg, NumArgs, OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002395 } else {
2396 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002397 }
2398 }
2399
2400 OverloadCandidateSet::iterator Best;
2401 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2402 case OR_Success:
2403 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2404 Result->setSuccess(true);
2405 break;
2406
2407 case OR_Deleted:
2408 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2409 Result->setSuccess(false);
2410 break;
2411
2412 case OR_Ambiguous:
2413 case OR_No_Viable_Function:
2414 Result->setMethod(0);
2415 Result->setSuccess(false);
2416 break;
2417 }
2418
2419 return Result;
2420}
2421
2422/// \brief Look up the default constructor for the given class.
2423CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002424 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002425 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2426 false, false);
2427
2428 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002429}
2430
Alexis Hunt491ec602011-06-21 23:42:56 +00002431/// \brief Look up the copying constructor for the given class.
2432CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
2433 unsigned Quals,
2434 bool *ConstParamMatch) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002435 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2436 "non-const, non-volatile qualifiers for copy ctor arg");
2437 SpecialMemberOverloadResult *Result =
2438 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2439 Quals & Qualifiers::Volatile, false, false, false);
2440
2441 if (ConstParamMatch)
2442 *ConstParamMatch = Result->hasConstParamMatch();
2443
2444 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2445}
2446
Sebastian Redl22653ba2011-08-30 19:58:05 +00002447/// \brief Look up the moving constructor for the given class.
2448CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class) {
2449 SpecialMemberOverloadResult *Result =
2450 LookupSpecialMember(Class, CXXMoveConstructor, false,
2451 false, false, false, false);
2452
2453 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2454}
2455
Douglas Gregor52b72822010-07-02 23:12:18 +00002456/// \brief Look up the constructors for the given class.
2457DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002458 // If the implicit constructors have not yet been declared, do so now.
Douglas Gregor9672f922010-07-03 00:47:00 +00002459 if (CanDeclareSpecialMemberFunction(Context, Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00002460 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002461 DeclareImplicitDefaultConstructor(Class);
2462 if (!Class->hasDeclaredCopyConstructor())
2463 DeclareImplicitCopyConstructor(Class);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002464 if (getLangOptions().CPlusPlus0x && Class->needsImplicitMoveConstructor())
2465 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00002466 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002467
Douglas Gregor52b72822010-07-02 23:12:18 +00002468 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2469 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2470 return Class->lookup(Name);
2471}
2472
Alexis Hunt491ec602011-06-21 23:42:56 +00002473/// \brief Look up the copying assignment operator for the given class.
2474CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2475 unsigned Quals, bool RValueThis,
2476 unsigned ThisQuals,
2477 bool *ConstParamMatch) {
2478 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2479 "non-const, non-volatile qualifiers for copy assignment arg");
2480 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2481 "non-const, non-volatile qualifiers for copy assignment this");
2482 SpecialMemberOverloadResult *Result =
2483 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2484 Quals & Qualifiers::Volatile, RValueThis,
2485 ThisQuals & Qualifiers::Const,
2486 ThisQuals & Qualifiers::Volatile);
2487
2488 if (ConstParamMatch)
2489 *ConstParamMatch = Result->hasConstParamMatch();
2490
2491 return Result->getMethod();
2492}
2493
Sebastian Redl22653ba2011-08-30 19:58:05 +00002494/// \brief Look up the moving assignment operator for the given class.
2495CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
2496 bool RValueThis,
2497 unsigned ThisQuals) {
2498 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2499 "non-const, non-volatile qualifiers for copy assignment this");
2500 SpecialMemberOverloadResult *Result =
2501 LookupSpecialMember(Class, CXXMoveAssignment, false, false, RValueThis,
2502 ThisQuals & Qualifiers::Const,
2503 ThisQuals & Qualifiers::Volatile);
2504
2505 return Result->getMethod();
2506}
2507
Douglas Gregore71edda2010-07-01 22:47:18 +00002508/// \brief Look for the destructor of the given class.
2509///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00002510/// During semantic analysis, this routine should be used in lieu of
2511/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00002512///
2513/// \returns The destructor for this class.
2514CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002515 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2516 false, false, false,
2517 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00002518}
2519
John McCall8fe68082010-01-26 07:16:45 +00002520void ADLResult::insert(NamedDecl *New) {
2521 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2522
2523 // If we haven't yet seen a decl for this key, or the last decl
2524 // was exactly this one, we're done.
2525 if (Old == 0 || Old == New) {
2526 Old = New;
2527 return;
2528 }
2529
2530 // Otherwise, decide which is a more recent redeclaration.
2531 FunctionDecl *OldFD, *NewFD;
2532 if (isa<FunctionTemplateDecl>(New)) {
2533 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2534 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2535 } else {
2536 OldFD = cast<FunctionDecl>(Old);
2537 NewFD = cast<FunctionDecl>(New);
2538 }
2539
2540 FunctionDecl *Cursor = NewFD;
2541 while (true) {
2542 Cursor = Cursor->getPreviousDeclaration();
2543
2544 // If we got to the end without finding OldFD, OldFD is the newer
2545 // declaration; leave things as they are.
2546 if (!Cursor) return;
2547
2548 // If we do find OldFD, then NewFD is newer.
2549 if (Cursor == OldFD) break;
2550
2551 // Otherwise, keep looking.
2552 }
2553
2554 Old = New;
2555}
2556
Sebastian Redlc057f422009-10-23 19:23:15 +00002557void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002558 Expr **Args, unsigned NumArgs,
Richard Smith02e85f32011-04-14 22:09:26 +00002559 ADLResult &Result,
2560 bool StdNamespaceIsAssociated) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002561 // Find all of the associated namespaces and classes based on the
2562 // arguments we have.
2563 AssociatedNamespaceSet AssociatedNamespaces;
2564 AssociatedClassSet AssociatedClasses;
Mike Stump11289f42009-09-09 15:08:12 +00002565 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCallc7e8e792009-08-07 22:18:02 +00002566 AssociatedNamespaces,
2567 AssociatedClasses);
Richard Smith02e85f32011-04-14 22:09:26 +00002568 if (StdNamespaceIsAssociated && StdNamespace)
2569 AssociatedNamespaces.insert(getStdNamespace());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002570
Sebastian Redlc057f422009-10-23 19:23:15 +00002571 QualType T1, T2;
2572 if (Operator) {
2573 T1 = Args[0]->getType();
2574 if (NumArgs >= 2)
2575 T2 = Args[1]->getType();
2576 }
2577
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002578 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002579 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2580 // and let Y be the lookup set produced by argument dependent
2581 // lookup (defined as follows). If X contains [...] then Y is
2582 // empty. Otherwise Y is the set of declarations found in the
2583 // namespaces associated with the argument types as described
2584 // below. The set of declarations found by the lookup of the name
2585 // is the union of X and Y.
2586 //
2587 // Here, we compute Y and add its members to the overloaded
2588 // candidate set.
2589 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00002590 NSEnd = AssociatedNamespaces.end();
2591 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002592 // When considering an associated namespace, the lookup is the
2593 // same as the lookup performed when the associated namespace is
2594 // used as a qualifier (3.4.3.2) except that:
2595 //
2596 // -- Any using-directives in the associated namespace are
2597 // ignored.
2598 //
John McCallc7e8e792009-08-07 22:18:02 +00002599 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002600 // associated classes are visible within their respective
2601 // namespaces even if they are not visible during an ordinary
2602 // lookup (11.4).
2603 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00002604 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00002605 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00002606 // If the only declaration here is an ordinary friend, consider
2607 // it only if it was declared in an associated classes.
2608 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00002609 DeclContext *LexDC = D->getLexicalDeclContext();
2610 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2611 continue;
2612 }
Mike Stump11289f42009-09-09 15:08:12 +00002613
John McCall91f61fc2010-01-26 06:04:06 +00002614 if (isa<UsingShadowDecl>(D))
2615 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002616
John McCall91f61fc2010-01-26 06:04:06 +00002617 if (isa<FunctionDecl>(D)) {
2618 if (Operator &&
2619 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2620 T1, T2, Context))
2621 continue;
John McCall8fe68082010-01-26 07:16:45 +00002622 } else if (!isa<FunctionTemplateDecl>(D))
2623 continue;
2624
2625 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002626 }
2627 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002628}
Douglas Gregor2d435302009-12-30 17:04:44 +00002629
2630//----------------------------------------------------------------------------
2631// Search for all visible declarations.
2632//----------------------------------------------------------------------------
2633VisibleDeclConsumer::~VisibleDeclConsumer() { }
2634
2635namespace {
2636
2637class ShadowContextRAII;
2638
2639class VisibleDeclsRecord {
2640public:
2641 /// \brief An entry in the shadow map, which is optimized to store a
2642 /// single declaration (the common case) but can also store a list
2643 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002644 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00002645
2646private:
2647 /// \brief A mapping from declaration names to the declarations that have
2648 /// this name within a particular scope.
2649 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2650
2651 /// \brief A list of shadow maps, which is used to model name hiding.
2652 std::list<ShadowMap> ShadowMaps;
2653
2654 /// \brief The declaration contexts we have already visited.
2655 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2656
2657 friend class ShadowContextRAII;
2658
2659public:
2660 /// \brief Determine whether we have already visited this context
2661 /// (and, if not, note that we are going to visit that context now).
2662 bool visitedContext(DeclContext *Ctx) {
2663 return !VisitedContexts.insert(Ctx);
2664 }
2665
Douglas Gregor39982192010-08-15 06:18:01 +00002666 bool alreadyVisitedContext(DeclContext *Ctx) {
2667 return VisitedContexts.count(Ctx);
2668 }
2669
Douglas Gregor2d435302009-12-30 17:04:44 +00002670 /// \brief Determine whether the given declaration is hidden in the
2671 /// current scope.
2672 ///
2673 /// \returns the declaration that hides the given declaration, or
2674 /// NULL if no such declaration exists.
2675 NamedDecl *checkHidden(NamedDecl *ND);
2676
2677 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002678 void add(NamedDecl *ND) {
2679 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2680 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002681};
2682
2683/// \brief RAII object that records when we've entered a shadow context.
2684class ShadowContextRAII {
2685 VisibleDeclsRecord &Visible;
2686
2687 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2688
2689public:
2690 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2691 Visible.ShadowMaps.push_back(ShadowMap());
2692 }
2693
2694 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00002695 Visible.ShadowMaps.pop_back();
2696 }
2697};
2698
2699} // end anonymous namespace
2700
Douglas Gregor2d435302009-12-30 17:04:44 +00002701NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002702 // Look through using declarations.
2703 ND = ND->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002704
Douglas Gregor2d435302009-12-30 17:04:44 +00002705 unsigned IDNS = ND->getIdentifierNamespace();
2706 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2707 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2708 SM != SMEnd; ++SM) {
2709 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2710 if (Pos == SM->end())
2711 continue;
2712
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002713 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor2d435302009-12-30 17:04:44 +00002714 IEnd = Pos->second.end();
2715 I != IEnd; ++I) {
2716 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +00002717 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002718 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00002719 Decl::IDNS_ObjCProtocol)))
2720 continue;
2721
2722 // Protocols are in distinct namespaces from everything else.
2723 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2724 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2725 (*I)->getIdentifierNamespace() != IDNS)
2726 continue;
2727
Douglas Gregor09bbc652010-01-14 15:47:35 +00002728 // Functions and function templates in the same scope overload
2729 // rather than hide. FIXME: Look for hiding based on function
2730 // signatures!
Douglas Gregor200c99d2010-01-14 03:35:48 +00002731 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002732 ND->isFunctionOrFunctionTemplate() &&
2733 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002734 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002735
Douglas Gregor2d435302009-12-30 17:04:44 +00002736 // We've found a declaration that hides this one.
2737 return *I;
2738 }
2739 }
2740
2741 return 0;
2742}
2743
2744static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2745 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002746 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002747 VisibleDeclConsumer &Consumer,
2748 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002749 if (!Ctx)
2750 return;
2751
Douglas Gregor2d435302009-12-30 17:04:44 +00002752 // Make sure we don't visit the same context twice.
2753 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2754 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002755
Douglas Gregor7454c562010-07-02 20:37:36 +00002756 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2757 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2758
Douglas Gregor2d435302009-12-30 17:04:44 +00002759 // Enumerate all of the results in this context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002760 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
Douglas Gregor2d435302009-12-30 17:04:44 +00002761 CurCtx = CurCtx->getNextContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002762 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
Douglas Gregor2d435302009-12-30 17:04:44 +00002763 DEnd = CurCtx->decls_end();
2764 D != DEnd; ++D) {
Douglas Gregora3b23b02010-12-09 21:44:02 +00002765 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00002766 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00002767 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002768 Visited.add(ND);
2769 }
Douglas Gregora3b23b02010-12-09 21:44:02 +00002770 } else if (ObjCForwardProtocolDecl *ForwardProto
2771 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
2772 for (ObjCForwardProtocolDecl::protocol_iterator
2773 P = ForwardProto->protocol_begin(),
2774 PEnd = ForwardProto->protocol_end();
2775 P != PEnd;
2776 ++P) {
Douglas Gregor4a814562011-12-14 16:03:29 +00002777 if (NamedDecl *ND = Result.getAcceptableDecl(*P)) {
2778 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
2779 Visited.add(ND);
Douglas Gregora3b23b02010-12-09 21:44:02 +00002780 }
2781 }
2782 }
Douglas Gregor04246572011-02-16 01:39:26 +00002783
Sebastian Redlbd595762010-08-31 20:53:31 +00002784 // Visit transparent contexts and inline namespaces inside this context.
Douglas Gregor2d435302009-12-30 17:04:44 +00002785 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
Sebastian Redlbd595762010-08-31 20:53:31 +00002786 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Douglas Gregor09bbc652010-01-14 15:47:35 +00002787 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002788 Consumer, Visited);
2789 }
2790 }
2791 }
2792
2793 // Traverse using directives for qualified name lookup.
2794 if (QualifiedNameLookup) {
2795 ShadowContextRAII Shadow(Visited);
2796 DeclContext::udir_iterator I, E;
2797 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002798 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002799 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002800 }
2801 }
2802
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002803 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00002804 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00002805 if (!Record->hasDefinition())
2806 return;
2807
Douglas Gregor2d435302009-12-30 17:04:44 +00002808 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2809 BEnd = Record->bases_end();
2810 B != BEnd; ++B) {
2811 QualType BaseType = B->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002812
Douglas Gregor2d435302009-12-30 17:04:44 +00002813 // Don't look into dependent bases, because name lookup can't look
2814 // there anyway.
2815 if (BaseType->isDependentType())
2816 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002817
Douglas Gregor2d435302009-12-30 17:04:44 +00002818 const RecordType *Record = BaseType->getAs<RecordType>();
2819 if (!Record)
2820 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002821
Douglas Gregor2d435302009-12-30 17:04:44 +00002822 // FIXME: It would be nice to be able to determine whether referencing
2823 // a particular member would be ambiguous. For example, given
2824 //
2825 // struct A { int member; };
2826 // struct B { int member; };
2827 // struct C : A, B { };
2828 //
2829 // void f(C *c) { c->### }
2830 //
2831 // accessing 'member' would result in an ambiguity. However, we
2832 // could be smart enough to qualify the member with the base
2833 // class, e.g.,
2834 //
2835 // c->B::member
2836 //
2837 // or
2838 //
2839 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002840
Douglas Gregor2d435302009-12-30 17:04:44 +00002841 // Find results in this base class (and its bases).
2842 ShadowContextRAII Shadow(Visited);
2843 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002844 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002845 }
2846 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002847
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002848 // Traverse the contexts of Objective-C classes.
2849 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2850 // Traverse categories.
2851 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2852 Category; Category = Category->getNextClassCategory()) {
2853 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002854 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002855 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002856 }
2857
2858 // Traverse protocols.
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002859 for (ObjCInterfaceDecl::all_protocol_iterator
2860 I = IFace->all_referenced_protocol_begin(),
2861 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002862 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002863 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002864 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002865 }
2866
2867 // Traverse the superclass.
2868 if (IFace->getSuperClass()) {
2869 ShadowContextRAII Shadow(Visited);
2870 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002871 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002872 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002873
Douglas Gregor0b59e802010-04-19 18:02:19 +00002874 // If there is an implementation, traverse it. We do this to find
2875 // synthesized ivars.
2876 if (IFace->getImplementation()) {
2877 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002878 LookupVisibleDecls(IFace->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00002879 QualifiedNameLookup, true, Consumer, Visited);
2880 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002881 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2882 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2883 E = Protocol->protocol_end(); I != E; ++I) {
2884 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002885 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002886 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002887 }
2888 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2889 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2890 E = Category->protocol_end(); I != E; ++I) {
2891 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002892 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002893 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002894 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002895
Douglas Gregor0b59e802010-04-19 18:02:19 +00002896 // If there is an implementation, traverse it.
2897 if (Category->getImplementation()) {
2898 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002899 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00002900 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002901 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002902 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002903}
2904
2905static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2906 UnqualUsingDirectiveSet &UDirs,
2907 VisibleDeclConsumer &Consumer,
2908 VisibleDeclsRecord &Visited) {
2909 if (!S)
2910 return;
2911
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002912 if (!S->getEntity() ||
2913 (!S->getParent() &&
Douglas Gregor39982192010-08-15 06:18:01 +00002914 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002915 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2916 // Walk through the declarations in this Scope.
2917 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2918 D != DEnd; ++D) {
John McCall48871652010-08-21 09:40:31 +00002919 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor4a814562011-12-14 16:03:29 +00002920 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00002921 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002922 Visited.add(ND);
2923 }
2924 }
2925 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002926
Douglas Gregor66230062010-03-15 14:33:29 +00002927 // FIXME: C++ [temp.local]p8
Douglas Gregor2d435302009-12-30 17:04:44 +00002928 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00002929 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002930 // Look into this scope's declaration context, along with any of its
2931 // parent lookup contexts (e.g., enclosing classes), up to the point
2932 // where we hit the context stored in the next outer scope.
2933 Entity = (DeclContext *)S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00002934 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002935
Douglas Gregorea166062010-03-15 15:26:48 +00002936 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00002937 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002938 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2939 if (Method->isInstanceMethod()) {
2940 // For instance methods, look for ivars in the method's interface.
2941 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2942 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00002943 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002944 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Fariborz Jahanian97d744b2011-08-31 22:24:06 +00002945 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00002946 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002947 }
2948
2949 // We've already performed all of the name lookup that we need
2950 // to for Objective-C methods; the next context will be the
2951 // outer scope.
2952 break;
2953 }
2954
Douglas Gregor2d435302009-12-30 17:04:44 +00002955 if (Ctx->isFunctionOrMethod())
2956 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002957
2958 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002959 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002960 }
2961 } else if (!S->getParent()) {
2962 // Look into the translation unit scope. We walk through the translation
2963 // unit's declaration context, because the Scope itself won't have all of
2964 // the declarations if we loaded a precompiled header.
2965 // FIXME: We would like the translation unit's Scope object to point to the
2966 // translation unit, so we don't need this special "if" branch. However,
2967 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002968 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00002969 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002970 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00002971 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002972 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002973 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002974 }
2975
Douglas Gregor2d435302009-12-30 17:04:44 +00002976 if (Entity) {
2977 // Lookup visible declarations in any namespaces found by using
2978 // directives.
2979 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2980 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2981 for (; UI != UEnd; ++UI)
2982 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002983 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002984 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002985 }
2986
2987 // Lookup names in the parent scope.
2988 ShadowContextRAII Shadow(Visited);
2989 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2990}
2991
2992void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00002993 VisibleDeclConsumer &Consumer,
2994 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002995 // Determine the set of using directives available during
2996 // unqualified name lookup.
2997 Scope *Initial = S;
2998 UnqualUsingDirectiveSet UDirs;
2999 if (getLangOptions().CPlusPlus) {
3000 // Find the first namespace or translation-unit scope.
3001 while (S && !isNamespaceOrTranslationUnitScope(S))
3002 S = S->getParent();
3003
3004 UDirs.visitScopeChain(Initial, S);
3005 }
3006 UDirs.done();
3007
3008 // Look for visible declarations.
3009 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3010 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003011 if (!IncludeGlobalScope)
3012 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003013 ShadowContextRAII Shadow(Visited);
3014 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3015}
3016
3017void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003018 VisibleDeclConsumer &Consumer,
3019 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003020 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3021 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003022 if (!IncludeGlobalScope)
3023 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003024 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003025 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003026 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003027}
3028
Chris Lattner43e7f312011-02-18 02:08:43 +00003029/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003030/// If GnuLabelLoc is a valid source location, then this is a definition
3031/// of an __label__ label name, otherwise it is a normal label definition
3032/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003033LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003034 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003035 // Do a lookup to see if we have a label with this name already.
Chris Lattner43e7f312011-02-18 02:08:43 +00003036 NamedDecl *Res = 0;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003037
3038 if (GnuLabelLoc.isValid()) {
3039 // Local label definitions always shadow existing labels.
3040 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3041 Scope *S = CurScope;
3042 PushOnScopeChains(Res, S, true);
3043 return cast<LabelDecl>(Res);
3044 }
3045
3046 // Not a GNU local label.
3047 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3048 // If we found a label, check to see if it is in the same context as us.
3049 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003050 if (Res && Res->getDeclContext() != CurContext)
3051 Res = 0;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003052 if (Res == 0) {
3053 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003054 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3055 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003056 assert(S && "Not in a function?");
3057 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003058 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003059 return cast<LabelDecl>(Res);
3060}
3061
3062//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003063// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003064//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003065
3066namespace {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003067
3068typedef llvm::StringMap<TypoCorrection, llvm::BumpPtrAllocator> TypoResultsMap;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003069typedef std::map<unsigned, TypoResultsMap *> TypoEditDistanceMap;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003070
3071static const unsigned MaxTypoDistanceResultSets = 5;
3072
Douglas Gregor2d435302009-12-30 17:04:44 +00003073class TypoCorrectionConsumer : public VisibleDeclConsumer {
3074 /// \brief The name written that is a typo in the source.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003075 StringRef Typo;
Douglas Gregor2d435302009-12-30 17:04:44 +00003076
3077 /// \brief The results found that have the smallest edit distance
3078 /// found (so far) with the typo name.
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003079 ///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003080 /// The pointer value being set to the current DeclContext indicates
3081 /// whether there is a keyword with this name.
3082 TypoEditDistanceMap BestResults;
Douglas Gregor2d435302009-12-30 17:04:44 +00003083
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003084 /// \brief The worst of the best N edit distances found so far.
3085 unsigned MaxEditDistance;
3086
3087 Sema &SemaRef;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003088
Douglas Gregor2d435302009-12-30 17:04:44 +00003089public:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003090 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003091 : Typo(Typo->getName()),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003092 MaxEditDistance((std::numeric_limits<unsigned>::max)()),
3093 SemaRef(SemaRef) { }
Douglas Gregor2d435302009-12-30 17:04:44 +00003094
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003095 ~TypoCorrectionConsumer() {
3096 for (TypoEditDistanceMap::iterator I = BestResults.begin(),
3097 IEnd = BestResults.end();
3098 I != IEnd;
3099 ++I)
3100 delete I->second;
3101 }
3102
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003103 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3104 bool InBaseClass);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003105 void FoundName(StringRef Name);
3106 void addKeywordResult(StringRef Keyword);
3107 void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003108 NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003109 void addCorrection(TypoCorrection Correction);
Douglas Gregor2d435302009-12-30 17:04:44 +00003110
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003111 typedef TypoResultsMap::iterator result_iterator;
3112 typedef TypoEditDistanceMap::iterator distance_iterator;
3113 distance_iterator begin() { return BestResults.begin(); }
3114 distance_iterator end() { return BestResults.end(); }
3115 void erase(distance_iterator I) { BestResults.erase(I); }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003116 unsigned size() const { return BestResults.size(); }
3117 bool empty() const { return BestResults.empty(); }
Douglas Gregor2d435302009-12-30 17:04:44 +00003118
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003119 TypoCorrection &operator[](StringRef Name) {
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003120 return (*BestResults.begin()->second)[Name];
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003121 }
3122
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003123 unsigned getMaxEditDistance() const {
3124 return MaxEditDistance;
3125 }
3126
3127 unsigned getBestEditDistance() {
3128 return (BestResults.empty()) ? MaxEditDistance : BestResults.begin()->first;
3129 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003130};
3131
3132}
3133
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003134void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003135 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003136 // Don't consider hidden names for typo correction.
3137 if (Hiding)
3138 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003139
Douglas Gregor2d435302009-12-30 17:04:44 +00003140 // Only consider entities with identifiers for names, ignoring
3141 // special names (constructors, overloaded operators, selectors,
3142 // etc.).
3143 IdentifierInfo *Name = ND->getIdentifier();
3144 if (!Name)
3145 return;
3146
Douglas Gregor57756ea2010-10-14 22:11:03 +00003147 FoundName(Name->getName());
3148}
3149
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003150void TypoCorrectionConsumer::FoundName(StringRef Name) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003151 // Use a simple length-based heuristic to determine the minimum possible
3152 // edit distance. If the minimum isn't good enough, bail out early.
3153 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003154 if (MinED > MaxEditDistance || (MinED && Typo.size() / MinED < 3))
Douglas Gregor93910a52010-10-19 19:39:10 +00003155 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003156
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003157 // Compute an upper bound on the allowable edit distance, so that the
3158 // edit-distance algorithm can short-circuit.
Jay Foad72e705e2011-04-23 09:06:00 +00003159 unsigned UpperBound =
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003160 std::min(unsigned((Typo.size() + 2) / 3), MaxEditDistance);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003161
Douglas Gregor2d435302009-12-30 17:04:44 +00003162 // Compute the edit distance between the typo and the name of this
3163 // entity. If this edit distance is not worse than the best edit
3164 // distance we've seen so far, add it to the list of results.
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003165 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003166
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003167 if (ED > MaxEditDistance) {
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003168 // This result is worse than the best results we've seen so far;
3169 // ignore it.
3170 return;
3171 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003172
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003173 addName(Name, NULL, ED);
Douglas Gregor2d435302009-12-30 17:04:44 +00003174}
3175
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003176void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003177 // Compute the edit distance between the typo and this keyword.
3178 // If this edit distance is not worse than the best edit
3179 // distance we've seen so far, add it to the list of results.
3180 unsigned ED = Typo.edit_distance(Keyword);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003181 if (ED > MaxEditDistance) {
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003182 // This result is worse than the best results we've seen so far;
3183 // ignore it.
3184 return;
3185 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003186
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003187 addName(Keyword, NULL, ED, NULL, true);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003188}
3189
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003190void TypoCorrectionConsumer::addName(StringRef Name,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003191 NamedDecl *ND,
3192 unsigned Distance,
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003193 NestedNameSpecifier *NNS,
3194 bool isKeyword) {
3195 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
3196 if (isKeyword) TC.makeKeyword();
3197 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003198}
3199
3200void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003201 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003202 TypoResultsMap *& Map = BestResults[Correction.getEditDistance()];
3203 if (!Map)
3204 Map = new TypoResultsMap;
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003205
3206 TypoCorrection &CurrentCorrection = (*Map)[Name];
3207 if (!CurrentCorrection ||
3208 // FIXME: The following should be rolled up into an operator< on
3209 // TypoCorrection with a more principled definition.
3210 CurrentCorrection.isKeyword() < Correction.isKeyword() ||
3211 Correction.getAsString(SemaRef.getLangOptions()) <
3212 CurrentCorrection.getAsString(SemaRef.getLangOptions()))
3213 CurrentCorrection = Correction;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003214
3215 while (BestResults.size() > MaxTypoDistanceResultSets) {
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003216 TypoEditDistanceMap::iterator Last = BestResults.end();
3217 --Last;
3218 delete Last->second;
3219 BestResults.erase(Last);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003220 }
3221}
3222
3223namespace {
3224
3225class SpecifierInfo {
3226 public:
3227 DeclContext* DeclCtx;
3228 NestedNameSpecifier* NameSpecifier;
3229 unsigned EditDistance;
3230
3231 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3232 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3233};
3234
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003235typedef SmallVector<DeclContext*, 4> DeclContextList;
3236typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003237
3238class NamespaceSpecifierSet {
3239 ASTContext &Context;
3240 DeclContextList CurContextChain;
3241 bool isSorted;
3242
3243 SpecifierInfoList Specifiers;
3244 llvm::SmallSetVector<unsigned, 4> Distances;
3245 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3246
3247 /// \brief Helper for building the list of DeclContexts between the current
3248 /// context and the top of the translation unit
3249 static DeclContextList BuildContextChain(DeclContext *Start);
3250
3251 void SortNamespaces();
3252
3253 public:
3254 explicit NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext)
Benjamin Kramerde1d6232011-07-05 09:46:31 +00003255 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
3256 isSorted(true) {}
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003257
3258 /// \brief Add the namespace to the set, computing the corresponding
3259 /// NestedNameSpecifier and its distance in the process.
3260 void AddNamespace(NamespaceDecl *ND);
3261
3262 typedef SpecifierInfoList::iterator iterator;
3263 iterator begin() {
3264 if (!isSorted) SortNamespaces();
3265 return Specifiers.begin();
3266 }
3267 iterator end() { return Specifiers.end(); }
3268};
3269
3270}
3271
3272DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003273 assert(Start && "Bulding a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003274 DeclContextList Chain;
3275 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3276 DC = DC->getLookupParent()) {
3277 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3278 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3279 !(ND && ND->isAnonymousNamespace()))
3280 Chain.push_back(DC->getPrimaryContext());
3281 }
3282 return Chain;
3283}
3284
3285void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003286 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003287 sortedDistances.append(Distances.begin(), Distances.end());
3288
3289 if (sortedDistances.size() > 1)
3290 std::sort(sortedDistances.begin(), sortedDistances.end());
3291
3292 Specifiers.clear();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003293 for (SmallVector<unsigned, 4>::iterator DI = sortedDistances.begin(),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003294 DIEnd = sortedDistances.end();
3295 DI != DIEnd; ++DI) {
3296 SpecifierInfoList &SpecList = DistanceMap[*DI];
3297 Specifiers.append(SpecList.begin(), SpecList.end());
3298 }
3299
3300 isSorted = true;
3301}
3302
3303void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003304 DeclContext *Ctx = cast<DeclContext>(ND);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003305 NestedNameSpecifier *NNS = NULL;
3306 unsigned NumSpecifiers = 0;
3307 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
3308
3309 // Eliminate common elements from the two DeclContext chains
3310 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3311 CEnd = CurContextChain.rend();
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003312 C != CEnd && !NamespaceDeclChain.empty() &&
3313 NamespaceDeclChain.back() == *C; ++C) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003314 NamespaceDeclChain.pop_back();
3315 }
3316
3317 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3318 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3319 CEnd = NamespaceDeclChain.rend();
3320 C != CEnd; ++C) {
3321 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3322 if (ND) {
3323 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3324 ++NumSpecifiers;
3325 }
3326 }
3327
3328 isSorted = false;
3329 Distances.insert(NumSpecifiers);
3330 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003331}
3332
Douglas Gregord507d772010-10-20 03:06:34 +00003333/// \brief Perform name lookup for a possible result for typo correction.
3334static void LookupPotentialTypoResult(Sema &SemaRef,
3335 LookupResult &Res,
3336 IdentifierInfo *Name,
3337 Scope *S, CXXScopeSpec *SS,
3338 DeclContext *MemberContext,
3339 bool EnteringContext,
3340 Sema::CorrectTypoContext CTC) {
3341 Res.suppressDiagnostics();
3342 Res.clear();
3343 Res.setLookupName(Name);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003344 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00003345 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
3346 if (CTC == Sema::CTC_ObjCIvarLookup) {
3347 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3348 Res.addDecl(Ivar);
3349 Res.resolveKind();
3350 return;
3351 }
3352 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003353
Douglas Gregord507d772010-10-20 03:06:34 +00003354 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3355 Res.addDecl(Prop);
3356 Res.resolveKind();
3357 return;
3358 }
3359 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003360
Douglas Gregord507d772010-10-20 03:06:34 +00003361 SemaRef.LookupQualifiedName(Res, MemberContext);
3362 return;
3363 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003364
3365 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00003366 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003367
Douglas Gregord507d772010-10-20 03:06:34 +00003368 // Fake ivar lookup; this should really be part of
3369 // LookupParsedName.
3370 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3371 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003372 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00003373 (Res.isSingleResult() &&
3374 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003375 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00003376 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3377 Res.addDecl(IV);
3378 Res.resolveKind();
3379 }
3380 }
3381 }
3382}
3383
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003384/// \brief Add keywords to the consumer as possible typo corrections.
3385static void AddKeywordsToConsumer(Sema &SemaRef,
3386 TypoCorrectionConsumer &Consumer,
3387 Scope *S, Sema::CorrectTypoContext CTC) {
3388 // Add context-dependent keywords.
3389 bool WantTypeSpecifiers = false;
3390 bool WantExpressionKeywords = false;
3391 bool WantCXXNamedCasts = false;
3392 bool WantRemainingKeywords = false;
3393 switch (CTC) {
3394 case Sema::CTC_Unknown:
3395 WantTypeSpecifiers = true;
3396 WantExpressionKeywords = true;
3397 WantCXXNamedCasts = true;
3398 WantRemainingKeywords = true;
3399
3400 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
3401 if (Method->getClassInterface() &&
3402 Method->getClassInterface()->getSuperClass())
3403 Consumer.addKeywordResult("super");
3404
3405 break;
3406
3407 case Sema::CTC_NoKeywords:
3408 break;
3409
3410 case Sema::CTC_Type:
3411 WantTypeSpecifiers = true;
3412 break;
3413
3414 case Sema::CTC_ObjCMessageReceiver:
3415 Consumer.addKeywordResult("super");
3416 // Fall through to handle message receivers like expressions.
3417
3418 case Sema::CTC_Expression:
3419 if (SemaRef.getLangOptions().CPlusPlus)
3420 WantTypeSpecifiers = true;
3421 WantExpressionKeywords = true;
3422 // Fall through to get C++ named casts.
3423
3424 case Sema::CTC_CXXCasts:
3425 WantCXXNamedCasts = true;
3426 break;
3427
3428 case Sema::CTC_ObjCPropertyLookup:
3429 // FIXME: Add "isa"?
3430 break;
3431
3432 case Sema::CTC_MemberLookup:
3433 if (SemaRef.getLangOptions().CPlusPlus)
3434 Consumer.addKeywordResult("template");
3435 break;
3436
3437 case Sema::CTC_ObjCIvarLookup:
3438 break;
3439 }
3440
3441 if (WantTypeSpecifiers) {
3442 // Add type-specifier keywords to the set of results.
3443 const char *CTypeSpecs[] = {
3444 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00003445 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003446 "_Complex", "_Imaginary",
3447 // storage-specifiers as well
3448 "extern", "inline", "static", "typedef"
3449 };
3450
3451 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3452 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3453 Consumer.addKeywordResult(CTypeSpecs[I]);
3454
3455 if (SemaRef.getLangOptions().C99)
3456 Consumer.addKeywordResult("restrict");
3457 if (SemaRef.getLangOptions().Bool || SemaRef.getLangOptions().CPlusPlus)
3458 Consumer.addKeywordResult("bool");
Douglas Gregor3b22a882011-07-01 21:27:45 +00003459 else if (SemaRef.getLangOptions().C99)
3460 Consumer.addKeywordResult("_Bool");
3461
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003462 if (SemaRef.getLangOptions().CPlusPlus) {
3463 Consumer.addKeywordResult("class");
3464 Consumer.addKeywordResult("typename");
3465 Consumer.addKeywordResult("wchar_t");
3466
3467 if (SemaRef.getLangOptions().CPlusPlus0x) {
3468 Consumer.addKeywordResult("char16_t");
3469 Consumer.addKeywordResult("char32_t");
3470 Consumer.addKeywordResult("constexpr");
3471 Consumer.addKeywordResult("decltype");
3472 Consumer.addKeywordResult("thread_local");
3473 }
3474 }
3475
3476 if (SemaRef.getLangOptions().GNUMode)
3477 Consumer.addKeywordResult("typeof");
3478 }
3479
3480 if (WantCXXNamedCasts && SemaRef.getLangOptions().CPlusPlus) {
3481 Consumer.addKeywordResult("const_cast");
3482 Consumer.addKeywordResult("dynamic_cast");
3483 Consumer.addKeywordResult("reinterpret_cast");
3484 Consumer.addKeywordResult("static_cast");
3485 }
3486
3487 if (WantExpressionKeywords) {
3488 Consumer.addKeywordResult("sizeof");
3489 if (SemaRef.getLangOptions().Bool || SemaRef.getLangOptions().CPlusPlus) {
3490 Consumer.addKeywordResult("false");
3491 Consumer.addKeywordResult("true");
3492 }
3493
3494 if (SemaRef.getLangOptions().CPlusPlus) {
3495 const char *CXXExprs[] = {
3496 "delete", "new", "operator", "throw", "typeid"
3497 };
3498 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3499 for (unsigned I = 0; I != NumCXXExprs; ++I)
3500 Consumer.addKeywordResult(CXXExprs[I]);
3501
3502 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3503 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3504 Consumer.addKeywordResult("this");
3505
3506 if (SemaRef.getLangOptions().CPlusPlus0x) {
3507 Consumer.addKeywordResult("alignof");
3508 Consumer.addKeywordResult("nullptr");
3509 }
3510 }
3511 }
3512
3513 if (WantRemainingKeywords) {
3514 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3515 // Statements.
3516 const char *CStmts[] = {
3517 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3518 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3519 for (unsigned I = 0; I != NumCStmts; ++I)
3520 Consumer.addKeywordResult(CStmts[I]);
3521
3522 if (SemaRef.getLangOptions().CPlusPlus) {
3523 Consumer.addKeywordResult("catch");
3524 Consumer.addKeywordResult("try");
3525 }
3526
3527 if (S && S->getBreakParent())
3528 Consumer.addKeywordResult("break");
3529
3530 if (S && S->getContinueParent())
3531 Consumer.addKeywordResult("continue");
3532
3533 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3534 Consumer.addKeywordResult("case");
3535 Consumer.addKeywordResult("default");
3536 }
3537 } else {
3538 if (SemaRef.getLangOptions().CPlusPlus) {
3539 Consumer.addKeywordResult("namespace");
3540 Consumer.addKeywordResult("template");
3541 }
3542
3543 if (S && S->isClassScope()) {
3544 Consumer.addKeywordResult("explicit");
3545 Consumer.addKeywordResult("friend");
3546 Consumer.addKeywordResult("mutable");
3547 Consumer.addKeywordResult("private");
3548 Consumer.addKeywordResult("protected");
3549 Consumer.addKeywordResult("public");
3550 Consumer.addKeywordResult("virtual");
3551 }
3552 }
3553
3554 if (SemaRef.getLangOptions().CPlusPlus) {
3555 Consumer.addKeywordResult("using");
3556
3557 if (SemaRef.getLangOptions().CPlusPlus0x)
3558 Consumer.addKeywordResult("static_assert");
3559 }
3560 }
3561}
3562
Douglas Gregor2d435302009-12-30 17:04:44 +00003563/// \brief Try to "correct" a typo in the source code by finding
3564/// visible declarations whose names are similar to the name that was
3565/// present in the source code.
3566///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003567/// \param TypoName the \c DeclarationNameInfo structure that contains
3568/// the name that was present in the source code along with its location.
3569///
3570/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00003571///
3572/// \param S the scope in which name lookup occurs.
3573///
3574/// \param SS the nested-name-specifier that precedes the name we're
3575/// looking for, if present.
3576///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003577/// \param MemberContext if non-NULL, the context in which to look for
3578/// a member access expression.
3579///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003580/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00003581/// the nested-name-specifier SS.
3582///
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003583/// \param CTC The context in which typo correction occurs, which impacts the
3584/// set of keywords permitted.
3585///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003586/// \param OPT when non-NULL, the search for visible declarations will
3587/// also walk the protocols in the qualified interfaces of \p OPT.
3588///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003589/// \returns a \c TypoCorrection containing the corrected name if the typo
3590/// along with information such as the \c NamedDecl where the corrected name
3591/// was declared, and any additional \c NestedNameSpecifier needed to access
3592/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3593TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3594 Sema::LookupNameKind LookupKind,
3595 Scope *S, CXXScopeSpec *SS,
3596 DeclContext *MemberContext,
3597 bool EnteringContext,
3598 CorrectTypoContext CTC,
3599 const ObjCObjectPointerType *OPT) {
Douglas Gregor8ed0c0b2010-07-09 17:35:33 +00003600 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003601 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003602
Francois Pichet9c391132011-12-03 15:55:29 +00003603 // In Microsoft mode, don't perform typo correction in a template member
3604 // function dependent context because it interferes with the "lookup into
3605 // dependent bases of class templates" feature.
3606 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
3607 isa<CXXMethodDecl>(CurContext))
3608 return TypoCorrection();
3609
Douglas Gregor2d435302009-12-30 17:04:44 +00003610 // We only attempt to correct typos for identifiers.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003611 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor2d435302009-12-30 17:04:44 +00003612 if (!Typo)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003613 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00003614
3615 // If the scope specifier itself was invalid, don't try to correct
3616 // typos.
3617 if (SS && SS->isInvalid())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003618 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00003619
3620 // Never try to correct typos during template deduction or
3621 // instantiation.
3622 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003623 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003624
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003625 NamespaceSpecifierSet Namespaces(Context, CurContext);
3626
3627 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003628
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003629 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor87074f12010-10-20 01:32:02 +00003630 bool IsUnqualifiedLookup = false;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003631 if (MemberContext) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003632 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003633
3634 // Look in qualified interfaces.
3635 if (OPT) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003636 for (ObjCObjectPointerType::qual_iterator
3637 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003638 I != E; ++I)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003639 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003640 }
3641 } else if (SS && SS->isSet()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003642 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
3643 if (!DC)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003644 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003645
Douglas Gregor87074f12010-10-20 01:32:02 +00003646 // Provide a stop gap for files that are just seriously broken. Trying
3647 // to correct all typos can turn into a HUGE performance penalty, causing
3648 // some files to take minutes to get rejected by the parser.
3649 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003650 return TypoCorrection();
Douglas Gregor87074f12010-10-20 01:32:02 +00003651 ++TyposCorrected;
3652
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003653 LookupVisibleDecls(DC, LookupKind, Consumer);
Douglas Gregor2d435302009-12-30 17:04:44 +00003654 } else {
Douglas Gregor87074f12010-10-20 01:32:02 +00003655 IsUnqualifiedLookup = true;
3656 UnqualifiedTyposCorrectedMap::iterator Cached
3657 = UnqualifiedTyposCorrected.find(Typo);
3658 if (Cached == UnqualifiedTyposCorrected.end()) {
3659 // Provide a stop gap for files that are just seriously broken. Trying
3660 // to correct all typos can turn into a HUGE performance penalty, causing
3661 // some files to take minutes to get rejected by the parser.
3662 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003663 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003664
Douglas Gregor87074f12010-10-20 01:32:02 +00003665 // For unqualified lookup, look through all of the names that we have
3666 // seen in this translation unit.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003667 for (IdentifierTable::iterator I = Context.Idents.begin(),
Douglas Gregor87074f12010-10-20 01:32:02 +00003668 IEnd = Context.Idents.end();
3669 I != IEnd; ++I)
3670 Consumer.FoundName(I->getKey());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003671
Douglas Gregor87074f12010-10-20 01:32:02 +00003672 // Walk through identifiers in external identifier sources.
3673 if (IdentifierInfoLookup *External
Douglas Gregor57756ea2010-10-14 22:11:03 +00003674 = Context.Idents.getExternalIdentifierLookup()) {
Ted Kremenekb4ea9a82010-11-07 06:11:33 +00003675 llvm::OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Douglas Gregor87074f12010-10-20 01:32:02 +00003676 do {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003677 StringRef Name = Iter->Next();
Douglas Gregor87074f12010-10-20 01:32:02 +00003678 if (Name.empty())
3679 break;
Douglas Gregor57756ea2010-10-14 22:11:03 +00003680
Douglas Gregor87074f12010-10-20 01:32:02 +00003681 Consumer.FoundName(Name);
3682 } while (true);
3683 }
3684 } else {
3685 // Use the cached value, unless it's a keyword. In the keyword case, we'll
3686 // end up adding the keyword below.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003687 if (!Cached->second)
3688 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003689
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003690 if (!Cached->second.isKeyword())
3691 Consumer.addCorrection(Cached->second);
Douglas Gregor57756ea2010-10-14 22:11:03 +00003692 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003693 }
3694
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003695 AddKeywordsToConsumer(*this, Consumer, S, CTC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003696
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003697 // If we haven't found anything, we're done.
Douglas Gregor87074f12010-10-20 01:32:02 +00003698 if (Consumer.empty()) {
3699 // If this was an unqualified lookup, note that no correction was found.
3700 if (IsUnqualifiedLookup)
3701 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003702
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003703 return TypoCorrection();
Douglas Gregor87074f12010-10-20 01:32:02 +00003704 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003705
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003706 // Make sure that the user typed at least 3 characters for each correction
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003707 // made. Otherwise, we don't even both looking at the results.
3708 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregor87074f12010-10-20 01:32:02 +00003709 if (ED > 0 && Typo->getName().size() / ED < 3) {
3710 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregoraf1daa92010-10-27 14:20:34 +00003711 if (IsUnqualifiedLookup)
Douglas Gregor87074f12010-10-20 01:32:02 +00003712 (void)UnqualifiedTyposCorrected[Typo];
3713
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003714 return TypoCorrection();
3715 }
3716
3717 // Build the NestedNameSpecifiers for the KnownNamespaces
3718 if (getLangOptions().CPlusPlus) {
3719 // Load any externally-known namespaces.
3720 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003721 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003722 LoadedExternalKnownNamespaces = true;
3723 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
3724 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
3725 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
3726 }
3727
3728 for (llvm::DenseMap<NamespaceDecl*, bool>::iterator
3729 KNI = KnownNamespaces.begin(),
3730 KNIEnd = KnownNamespaces.end();
3731 KNI != KNIEnd; ++KNI)
3732 Namespaces.AddNamespace(KNI->first);
Douglas Gregor87074f12010-10-20 01:32:02 +00003733 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003734
3735 // Weed out any names that could not be found by name lookup.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003736 llvm::SmallPtrSet<IdentifierInfo*, 16> QualifiedResults;
3737 LookupResult TmpRes(*this, TypoName, LookupKind);
3738 TmpRes.suppressDiagnostics();
3739 while (!Consumer.empty()) {
3740 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3741 unsigned ED = DI->first;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003742 for (TypoCorrectionConsumer::result_iterator I = DI->second->begin(),
3743 IEnd = DI->second->end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003744 I != IEnd; /* Increment in loop. */) {
3745 // If the item already has been looked up or is a keyword, keep it
3746 if (I->second.isResolved()) {
3747 ++I;
3748 continue;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003749 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003750
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003751 // Perform name lookup on this name.
3752 IdentifierInfo *Name = I->second.getCorrectionAsIdentifierInfo();
3753 LookupPotentialTypoResult(*this, TmpRes, Name, S, SS, MemberContext,
3754 EnteringContext, CTC);
3755
3756 switch (TmpRes.getResultKind()) {
3757 case LookupResult::NotFound:
3758 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain5a43b462011-09-07 20:25:59 +00003759 case LookupResult::FoundUnresolvedValue:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003760 QualifiedResults.insert(Name);
3761 // We didn't find this name in our scope, or didn't like what we found;
3762 // ignore it.
3763 {
3764 TypoCorrectionConsumer::result_iterator Next = I;
3765 ++Next;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003766 DI->second->erase(I);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003767 I = Next;
3768 }
3769 break;
3770
3771 case LookupResult::Ambiguous:
3772 // We don't deal with ambiguities.
3773 return TypoCorrection();
3774
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003775 case LookupResult::FoundOverloaded: {
3776 // Store all of the Decls for overloaded symbols
3777 for (LookupResult::iterator TRD = TmpRes.begin(),
3778 TRDEnd = TmpRes.end();
3779 TRD != TRDEnd; ++TRD)
3780 I->second.addCorrectionDecl(*TRD);
3781 ++I;
3782 break;
3783 }
3784
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003785 case LookupResult::Found:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003786 I->second.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
3787 ++I;
3788 break;
3789 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003790 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003791
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003792 if (DI->second->empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003793 Consumer.erase(DI);
3794 else if (!getLangOptions().CPlusPlus || QualifiedResults.empty() || !ED)
3795 // If there are results in the closest possible bucket, stop
3796 break;
3797
3798 // Only perform the qualified lookups for C++
3799 if (getLangOptions().CPlusPlus) {
3800 TmpRes.suppressDiagnostics();
3801 for (llvm::SmallPtrSet<IdentifierInfo*,
3802 16>::iterator QRI = QualifiedResults.begin(),
3803 QRIEnd = QualifiedResults.end();
3804 QRI != QRIEnd; ++QRI) {
3805 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
3806 NIEnd = Namespaces.end();
3807 NI != NIEnd; ++NI) {
3808 DeclContext *Ctx = NI->DeclCtx;
3809 unsigned QualifiedED = ED + NI->EditDistance;
3810
3811 // Stop searching once the namespaces are too far away to create
3812 // acceptable corrections for this identifier (since the namespaces
3813 // are sorted in ascending order by edit distance)
3814 if (QualifiedED > Consumer.getMaxEditDistance()) break;
3815
3816 TmpRes.clear();
3817 TmpRes.setLookupName(*QRI);
3818 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
3819
3820 switch (TmpRes.getResultKind()) {
3821 case LookupResult::Found:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003822 Consumer.addName((*QRI)->getName(), TmpRes.getAsSingle<NamedDecl>(),
3823 QualifiedED, NI->NameSpecifier);
3824 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003825 case LookupResult::FoundOverloaded: {
3826 TypoCorrection corr(&Context.Idents.get((*QRI)->getName()), NULL,
3827 NI->NameSpecifier, QualifiedED);
3828 for (LookupResult::iterator TRD = TmpRes.begin(),
3829 TRDEnd = TmpRes.end();
3830 TRD != TRDEnd; ++TRD)
3831 corr.addCorrectionDecl(*TRD);
3832 Consumer.addCorrection(corr);
3833 break;
3834 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003835 case LookupResult::NotFound:
3836 case LookupResult::NotFoundInCurrentInstantiation:
3837 case LookupResult::Ambiguous:
Kaelyn Uhrain5a43b462011-09-07 20:25:59 +00003838 case LookupResult::FoundUnresolvedValue:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003839 break;
3840 }
3841 }
3842 }
3843 }
3844
3845 QualifiedResults.clear();
3846 }
3847
3848 // No corrections remain...
3849 if (Consumer.empty()) return TypoCorrection();
3850
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003851 TypoResultsMap &BestResults = *Consumer.begin()->second;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003852 ED = Consumer.begin()->first;
3853
3854 if (ED > 0 && Typo->getName().size() / ED < 3) {
3855 // If this was an unqualified lookup, note that no correction was found.
3856 if (IsUnqualifiedLookup)
3857 (void)UnqualifiedTyposCorrected[Typo];
3858
3859 return TypoCorrection();
3860 }
3861
3862 // If we have multiple possible corrections, eliminate the ones where we
3863 // added namespace qualifiers to try to resolve the ambiguity (and to favor
3864 // corrections without additional namespace qualifiers)
3865 if (getLangOptions().CPlusPlus && BestResults.size() > 1) {
3866 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003867 for (TypoCorrectionConsumer::result_iterator I = DI->second->begin(),
3868 IEnd = DI->second->end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003869 I != IEnd; /* Increment in loop. */) {
3870 if (I->second.getCorrectionSpecifier() != NULL) {
3871 TypoCorrectionConsumer::result_iterator Cur = I;
3872 ++I;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003873 DI->second->erase(Cur);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003874 } else ++I;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003875 }
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003876 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003877
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003878 // If only a single name remains, return that result.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003879 if (BestResults.size() == 1) {
3880 const llvm::StringMapEntry<TypoCorrection> &Correction = *(BestResults.begin());
3881 const TypoCorrection &Result = Correction.second;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003882
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00003883 // Don't correct to a keyword that's the same as the typo; the keyword
3884 // wasn't actually in scope.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003885 if (ED == 0 && Result.isKeyword()) return TypoCorrection();
3886
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003887 // Record the correction for unqualified lookup.
3888 if (IsUnqualifiedLookup)
3889 UnqualifiedTyposCorrected[Typo] = Result;
3890
3891 return Result;
3892 }
3893 else if (BestResults.size() > 1 && CTC == CTC_ObjCMessageReceiver
3894 && BestResults["super"].isKeyword()) {
3895 // Prefer 'super' when we're completing in a message-receiver
3896 // context.
3897
3898 // Don't correct to a keyword that's the same as the typo; the keyword
3899 // wasn't actually in scope.
3900 if (ED == 0) return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003901
Douglas Gregor87074f12010-10-20 01:32:02 +00003902 // Record the correction for unqualified lookup.
3903 if (IsUnqualifiedLookup)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003904 UnqualifiedTyposCorrected[Typo] = BestResults["super"];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003905
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003906 return BestResults["super"];
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003907 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003908
Douglas Gregor87074f12010-10-20 01:32:02 +00003909 if (IsUnqualifiedLookup)
3910 (void)UnqualifiedTyposCorrected[Typo];
3911
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003912 return TypoCorrection();
3913}
3914
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003915void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
3916 if (!CDecl) return;
3917
3918 if (isKeyword())
3919 CorrectionDecls.clear();
3920
3921 CorrectionDecls.push_back(CDecl);
3922
3923 if (!CorrectionName)
3924 CorrectionName = CDecl->getDeclName();
3925}
3926
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003927std::string TypoCorrection::getAsString(const LangOptions &LO) const {
3928 if (CorrectionNameSpec) {
3929 std::string tmpBuffer;
3930 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
3931 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
3932 return PrefixOStream.str() + CorrectionName.getAsString();
3933 }
3934
3935 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00003936}