blob: 8e950ac20792952d2acd46bf6a29f68ab72a96b9 [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"
Douglas Gregorcdd11d42012-02-01 17:04:21 +000034#include "llvm/ADT/SetVector.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"
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +000039#include "llvm/ADT/edit_distance.h"
John McCall6538c932009-10-10 05:48:19 +000040#include "llvm/Support/ErrorHandling.h"
Douglas Gregor0afa7f62010-10-14 20:34:08 +000041#include <limits>
Douglas Gregor2d435302009-12-30 17:04:44 +000042#include <list>
Douglas Gregor1c846b02009-01-16 00:38:09 +000043#include <set>
Douglas Gregor889ceb72009-02-03 19:21:40 +000044#include <vector>
45#include <iterator>
46#include <utility>
47#include <algorithm>
Douglas Gregorc2fa1692011-06-28 16:20:02 +000048#include <map>
Douglas Gregor34074322009-01-14 22:20:51 +000049
50using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000051using namespace sema;
Douglas Gregor34074322009-01-14 22:20:51 +000052
John McCallf6c8a4e2009-11-10 07:01:13 +000053namespace {
54 class UnqualUsingEntry {
55 const DeclContext *Nominated;
56 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000057
John McCallf6c8a4e2009-11-10 07:01:13 +000058 public:
59 UnqualUsingEntry(const DeclContext *Nominated,
60 const DeclContext *CommonAncestor)
61 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
62 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000063
John McCallf6c8a4e2009-11-10 07:01:13 +000064 const DeclContext *getCommonAncestor() const {
65 return CommonAncestor;
66 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000067
John McCallf6c8a4e2009-11-10 07:01:13 +000068 const DeclContext *getNominatedNamespace() const {
69 return Nominated;
70 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000071
John McCallf6c8a4e2009-11-10 07:01:13 +000072 // Sort by the pointer value of the common ancestor.
73 struct Comparator {
74 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
75 return L.getCommonAncestor() < R.getCommonAncestor();
76 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000077
John McCallf6c8a4e2009-11-10 07:01:13 +000078 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
79 return E.getCommonAncestor() < DC;
80 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000081
John McCallf6c8a4e2009-11-10 07:01:13 +000082 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
83 return DC < E.getCommonAncestor();
84 }
85 };
86 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000087
John McCallf6c8a4e2009-11-10 07:01:13 +000088 /// A collection of using directives, as used by C++ unqualified
89 /// lookup.
90 class UnqualUsingDirectiveSet {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000091 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000092
John McCallf6c8a4e2009-11-10 07:01:13 +000093 ListTy list;
94 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000095
John McCallf6c8a4e2009-11-10 07:01:13 +000096 public:
97 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +000098
John McCallf6c8a4e2009-11-10 07:01:13 +000099 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000100 // C++ [namespace.udir]p1:
John McCallf6c8a4e2009-11-10 07:01:13 +0000101 // During unqualified name lookup, the names appear as if they
102 // were declared in the nearest enclosing namespace which contains
103 // both the using-directive and the nominated namespace.
104 DeclContext *InnermostFileDC
105 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
106 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +0000107
John McCallf6c8a4e2009-11-10 07:01:13 +0000108 for (; S; S = S->getParent()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000109 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
110 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
111 visit(Ctx, EffectiveDC);
112 } else {
113 Scope::udir_iterator I = S->using_directives_begin(),
114 End = S->using_directives_end();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000115
John McCallf6c8a4e2009-11-10 07:01:13 +0000116 for (; I != End; ++I)
John McCall48871652010-08-21 09:40:31 +0000117 visit(*I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000118 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000119 }
120 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000121
122 // Visits a context and collect all of its using directives
123 // recursively. Treats all using directives as if they were
124 // declared in the context.
125 //
126 // A given context is only every visited once, so it is important
127 // that contexts be visited from the inside out in order to get
128 // the effective DCs right.
129 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
130 if (!visited.insert(DC))
131 return;
132
133 addUsingDirectives(DC, EffectiveDC);
134 }
135
136 // Visits a using directive and collects all of its using
137 // directives recursively. Treats all using directives as if they
138 // were declared in the effective DC.
139 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
140 DeclContext *NS = UD->getNominatedNamespace();
141 if (!visited.insert(NS))
142 return;
143
144 addUsingDirective(UD, EffectiveDC);
145 addUsingDirectives(NS, EffectiveDC);
146 }
147
148 // Adds all the using directives in a context (and those nominated
149 // by its using directives, transitively) as if they appeared in
150 // the given effective context.
151 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000152 SmallVector<DeclContext*,4> queue;
John McCallf6c8a4e2009-11-10 07:01:13 +0000153 while (true) {
154 DeclContext::udir_iterator I, End;
155 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
156 UsingDirectiveDecl *UD = *I;
157 DeclContext *NS = UD->getNominatedNamespace();
158 if (visited.insert(NS)) {
159 addUsingDirective(UD, EffectiveDC);
160 queue.push_back(NS);
161 }
162 }
163
164 if (queue.empty())
165 return;
166
167 DC = queue.back();
168 queue.pop_back();
169 }
170 }
171
172 // Add a using directive as if it had been declared in the given
173 // context. This helps implement C++ [namespace.udir]p3:
174 // The using-directive is transitive: if a scope contains a
175 // using-directive that nominates a second namespace that itself
176 // contains using-directives, the effect is as if the
177 // using-directives from the second namespace also appeared in
178 // the first.
179 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
180 // Find the common ancestor between the effective context and
181 // the nominated namespace.
182 DeclContext *Common = UD->getNominatedNamespace();
183 while (!Common->Encloses(EffectiveDC))
184 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000185 Common = Common->getPrimaryContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000186
John McCallf6c8a4e2009-11-10 07:01:13 +0000187 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
188 }
189
190 void done() {
191 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
192 }
193
John McCallf6c8a4e2009-11-10 07:01:13 +0000194 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000195
John McCallf6c8a4e2009-11-10 07:01:13 +0000196 const_iterator begin() const { return list.begin(); }
197 const_iterator end() const { return list.end(); }
198
199 std::pair<const_iterator,const_iterator>
200 getNamespacesFor(DeclContext *DC) const {
John McCall9757d032009-11-10 09:20:04 +0000201 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCallf6c8a4e2009-11-10 07:01:13 +0000202 UnqualUsingEntry::Comparator());
203 }
204 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000205}
206
Douglas Gregor889ceb72009-02-03 19:21:40 +0000207// Retrieve the set of identifier namespaces that correspond to a
208// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000209static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
210 bool CPlusPlus,
211 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000212 unsigned IDNS = 0;
213 switch (NameKind) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +0000214 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000215 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000216 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000217 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000218 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000219 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000220 if (Redeclaration)
221 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCallea305ed2009-12-18 10:40:03 +0000222 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000223 break;
224
John McCallb9467b62010-04-24 01:30:58 +0000225 case Sema::LookupOperatorName:
226 // Operator lookup is its own crazy thing; it is not the same
227 // as (e.g.) looking up an operator name for redeclaration.
228 assert(!Redeclaration && "cannot do redeclaration operator lookup");
229 IDNS = Decl::IDNS_NonMemberOperator;
230 break;
231
Douglas Gregor889ceb72009-02-03 19:21:40 +0000232 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000233 if (CPlusPlus) {
234 IDNS = Decl::IDNS_Type;
235
236 // When looking for a redeclaration of a tag name, we add:
237 // 1) TagFriend to find undeclared friend decls
238 // 2) Namespace because they can't "overload" with tag decls.
239 // 3) Tag because it includes class templates, which can't
240 // "overload" with tag decls.
241 if (Redeclaration)
242 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
243 } else {
244 IDNS = Decl::IDNS_Tag;
245 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000246 break;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000247 case Sema::LookupLabel:
248 IDNS = Decl::IDNS_Label;
249 break;
250
Douglas Gregor889ceb72009-02-03 19:21:40 +0000251 case Sema::LookupMemberName:
252 IDNS = Decl::IDNS_Member;
253 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000254 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000255 break;
256
257 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000258 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
259 break;
260
Douglas Gregor889ceb72009-02-03 19:21:40 +0000261 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000262 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000263 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000264
John McCall84d87672009-12-10 09:41:52 +0000265 case Sema::LookupUsingDeclName:
266 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
267 | Decl::IDNS_Member | Decl::IDNS_Using;
268 break;
269
Douglas Gregor79947a22009-04-24 00:11:27 +0000270 case Sema::LookupObjCProtocolName:
271 IDNS = Decl::IDNS_ObjCProtocol;
272 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000273
Douglas Gregor39982192010-08-15 06:18:01 +0000274 case Sema::LookupAnyName:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000275 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor39982192010-08-15 06:18:01 +0000276 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
277 | Decl::IDNS_Type;
278 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000279 }
280 return IDNS;
281}
282
John McCallea305ed2009-12-18 10:40:03 +0000283void LookupResult::configure() {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000284 IDNS = getIDNS(LookupKind, SemaRef.getLangOptions().CPlusPlus,
John McCallea305ed2009-12-18 10:40:03 +0000285 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000286
287 // If we're looking for one of the allocation or deallocation
288 // operators, make sure that the implicitly-declared new and delete
289 // operators can be found.
290 if (!isForRedeclaration()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000291 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000292 case OO_New:
293 case OO_Delete:
294 case OO_Array_New:
295 case OO_Array_Delete:
296 SemaRef.DeclareGlobalNewDelete();
297 break;
298
299 default:
300 break;
301 }
302 }
John McCallea305ed2009-12-18 10:40:03 +0000303}
304
Daniel Dunbar9e19f132012-03-08 01:43:06 +0000305void LookupResult::sanityImpl() const {
306 // Note that this function is never called by NDEBUG builds. See
307 // LookupResult::sanity().
John McCall19c1bfd2010-08-25 05:32:35 +0000308 assert(ResultKind != NotFound || Decls.size() == 0);
309 assert(ResultKind != Found || Decls.size() == 1);
310 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
311 (Decls.size() == 1 &&
312 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
313 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
314 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000315 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
316 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall19c1bfd2010-08-25 05:32:35 +0000317 assert((Paths != NULL) == (ResultKind == Ambiguous &&
318 (Ambiguity == AmbiguousBaseSubobjectTypes ||
319 Ambiguity == AmbiguousBaseSubobjects)));
320}
John McCall19c1bfd2010-08-25 05:32:35 +0000321
John McCall9f3059a2009-10-09 21:13:30 +0000322// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000323void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000324 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000325}
326
Douglas Gregor4a814562011-12-14 16:03:29 +0000327static NamedDecl *getVisibleDecl(NamedDecl *D);
328
329NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
330 return getVisibleDecl(D);
331}
332
John McCall283b9012009-11-22 00:44:51 +0000333/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000334void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000335 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000336
John McCall9f3059a2009-10-09 21:13:30 +0000337 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000338 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000339 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000340 return;
341 }
342
John McCall283b9012009-11-22 00:44:51 +0000343 // If there's a single decl, we need to examine it to decide what
344 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000345 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000346 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
347 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000348 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000349 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000350 ResultKind = FoundUnresolvedValue;
351 return;
352 }
John McCall9f3059a2009-10-09 21:13:30 +0000353
John McCall6538c932009-10-10 05:48:19 +0000354 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000355 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000356
John McCall9f3059a2009-10-09 21:13:30 +0000357 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor13e65872010-08-11 14:45:53 +0000358 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000359
John McCall9f3059a2009-10-09 21:13:30 +0000360 bool Ambiguous = false;
361 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000362 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000363
364 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000365
John McCall9f3059a2009-10-09 21:13:30 +0000366 unsigned I = 0;
367 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000368 NamedDecl *D = Decls[I]->getUnderlyingDecl();
369 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000370
Douglas Gregor13e65872010-08-11 14:45:53 +0000371 // Redeclarations of types via typedef can occur both within a scope
372 // and, through using declarations and directives, across scopes. There is
373 // no ambiguity if they all refer to the same type, so unique based on the
374 // canonical type.
375 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
376 if (!TD->getDeclContext()->isRecord()) {
377 QualType T = SemaRef.Context.getTypeDeclType(TD);
378 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
379 // The type is not unique; pull something off the back and continue
380 // at this index.
381 Decls[I] = Decls[--N];
382 continue;
383 }
384 }
385 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000386
John McCallf0f1cf02009-11-17 07:50:12 +0000387 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000388 // If it's not unique, pull something off the back (and
389 // continue at this index).
390 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000391 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000392 }
393
Douglas Gregor13e65872010-08-11 14:45:53 +0000394 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000395
Douglas Gregor13e65872010-08-11 14:45:53 +0000396 if (isa<UnresolvedUsingValueDecl>(D)) {
397 HasUnresolved = true;
398 } else if (isa<TagDecl>(D)) {
399 if (HasTag)
400 Ambiguous = true;
401 UniqueTagIndex = I;
402 HasTag = true;
403 } else if (isa<FunctionTemplateDecl>(D)) {
404 HasFunction = true;
405 HasFunctionTemplate = true;
406 } else if (isa<FunctionDecl>(D)) {
407 HasFunction = true;
408 } else {
409 if (HasNonFunction)
410 Ambiguous = true;
411 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000412 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000413 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000414 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000415
John McCall9f3059a2009-10-09 21:13:30 +0000416 // C++ [basic.scope.hiding]p2:
417 // A class name or enumeration name can be hidden by the name of
418 // an object, function, or enumerator declared in the same
419 // scope. If a class or enumeration name and an object, function,
420 // or enumerator are declared in the same scope (in any order)
421 // with the same name, the class or enumeration name is hidden
422 // wherever the object, function, or enumerator name is visible.
423 // But it's still an error if there are distinct tag types found,
424 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000425 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000426 (HasFunction || HasNonFunction || HasUnresolved)) {
427 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
428 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
429 Decls[UniqueTagIndex] = Decls[--N];
430 else
431 Ambiguous = true;
432 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000433
John McCall9f3059a2009-10-09 21:13:30 +0000434 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000435
John McCall80053822009-12-03 00:58:24 +0000436 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000437 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000438
John McCall9f3059a2009-10-09 21:13:30 +0000439 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000440 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000441 else if (HasUnresolved)
442 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000443 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000444 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000445 else
John McCall27b18f82009-11-17 02:14:36 +0000446 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000447}
448
John McCall5cebab12009-11-18 07:57:50 +0000449void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000450 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000451 DeclContext::lookup_iterator DI, DE;
452 for (I = P.begin(), E = P.end(); I != E; ++I)
453 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
454 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000455}
456
John McCall5cebab12009-11-18 07:57:50 +0000457void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000458 Paths = new CXXBasePaths;
459 Paths->swap(P);
460 addDeclsFromBasePaths(*Paths);
461 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000462 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000463}
464
John McCall5cebab12009-11-18 07:57:50 +0000465void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000466 Paths = new CXXBasePaths;
467 Paths->swap(P);
468 addDeclsFromBasePaths(*Paths);
469 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000470 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000471}
472
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000473void LookupResult::print(raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000474 Out << Decls.size() << " result(s)";
475 if (isAmbiguous()) Out << ", ambiguous";
476 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000477
John McCall9f3059a2009-10-09 21:13:30 +0000478 for (iterator I = begin(), E = end(); I != E; ++I) {
479 Out << "\n";
480 (*I)->print(Out, 2);
481 }
482}
483
Douglas Gregord3a59182010-02-12 05:48:04 +0000484/// \brief Lookup a builtin function, when name lookup would otherwise
485/// fail.
486static bool LookupBuiltin(Sema &S, LookupResult &R) {
487 Sema::LookupNameKind NameKind = R.getLookupKind();
488
489 // If we didn't find a use of this identifier, and if the identifier
490 // corresponds to a compiler builtin, create the decl object for the builtin
491 // now, injecting it into translation unit scope, and return it.
492 if (NameKind == Sema::LookupOrdinaryName ||
493 NameKind == Sema::LookupRedeclarationWithLinkage) {
494 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
495 if (II) {
496 // If this is a builtin on this (or all) targets, create the decl.
497 if (unsigned BuiltinID = II->getBuiltinID()) {
498 // In C++, we don't have any predefined library functions like
499 // 'malloc'. Instead, we'll just error.
500 if (S.getLangOptions().CPlusPlus &&
501 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
502 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000503
504 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
505 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000506 R.isForRedeclaration(),
507 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000508 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000509 return true;
510 }
511
512 if (R.isForRedeclaration()) {
513 // If we're redeclaring this function anyway, forget that
514 // this was a builtin at all.
515 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
516 }
517
518 return false;
Douglas Gregord3a59182010-02-12 05:48:04 +0000519 }
520 }
521 }
522
523 return false;
524}
525
Douglas Gregor7454c562010-07-02 20:37:36 +0000526/// \brief Determine whether we can declare a special member function within
527/// the class at this point.
528static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
529 const CXXRecordDecl *Class) {
John McCall2ded5d22010-08-11 23:52:36 +0000530 // Don't do it if the class is invalid.
531 if (Class->isInvalidDecl())
532 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000533
Douglas Gregor7454c562010-07-02 20:37:36 +0000534 // We need to have a definition for the class.
535 if (!Class->getDefinition() || Class->isDependentContext())
536 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000537
Douglas Gregor7454c562010-07-02 20:37:36 +0000538 // We can't be in the middle of defining the class.
539 if (const RecordType *RecordTy
540 = Context.getTypeDeclType(Class)->getAs<RecordType>())
541 return !RecordTy->isBeingDefined();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000542
Douglas Gregor7454c562010-07-02 20:37:36 +0000543 return false;
544}
545
546void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000547 if (!CanDeclareSpecialMemberFunction(Context, Class))
548 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000549
550 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000551 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000552 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000553
Douglas Gregora6d69502010-07-02 23:41:54 +0000554 // If the copy constructor has not yet been declared, do so now.
555 if (!Class->hasDeclaredCopyConstructor())
556 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000557
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000558 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000559 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000560 DeclareImplicitCopyAssignment(Class);
561
Sebastian Redl22653ba2011-08-30 19:58:05 +0000562 if (getLangOptions().CPlusPlus0x) {
563 // If the move constructor has not yet been declared, do so now.
564 if (Class->needsImplicitMoveConstructor())
565 DeclareImplicitMoveConstructor(Class); // might not actually do it
566
567 // If the move assignment operator has not yet been declared, do so now.
568 if (Class->needsImplicitMoveAssignment())
569 DeclareImplicitMoveAssignment(Class); // might not actually do it
570 }
571
Douglas Gregor7454c562010-07-02 20:37:36 +0000572 // If the destructor has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000573 if (!Class->hasDeclaredDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000574 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000575}
576
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000577/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000578/// special member function.
579static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
580 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000581 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000582 case DeclarationName::CXXDestructorName:
583 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000584
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000585 case DeclarationName::CXXOperatorName:
586 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000587
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000588 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000589 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000590 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000591
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000592 return false;
593}
594
595/// \brief If there are any implicit member functions with the given name
596/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000597static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000598 DeclarationName Name,
599 const DeclContext *DC) {
600 if (!DC)
601 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000602
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000603 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000604 case DeclarationName::CXXConstructorName:
605 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor9672f922010-07-03 00:47:00 +0000606 if (Record->getDefinition() &&
607 CanDeclareSpecialMemberFunction(S.Context, Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000608 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000609 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000610 S.DeclareImplicitDefaultConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000611 if (!Record->hasDeclaredCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000612 S.DeclareImplicitCopyConstructor(Class);
613 if (S.getLangOptions().CPlusPlus0x &&
614 Record->needsImplicitMoveConstructor())
615 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000616 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000617 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000618
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000619 case DeclarationName::CXXDestructorName:
620 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
621 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
622 CanDeclareSpecialMemberFunction(S.Context, Record))
623 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000624 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000625
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000626 case DeclarationName::CXXOperatorName:
627 if (Name.getCXXOverloadedOperator() != OO_Equal)
628 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000629
Sebastian Redl22653ba2011-08-30 19:58:05 +0000630 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
631 if (Record->getDefinition() &&
632 CanDeclareSpecialMemberFunction(S.Context, Record)) {
633 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
634 if (!Record->hasDeclaredCopyAssignment())
635 S.DeclareImplicitCopyAssignment(Class);
636 if (S.getLangOptions().CPlusPlus0x &&
637 Record->needsImplicitMoveAssignment())
638 S.DeclareImplicitMoveAssignment(Class);
639 }
640 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000641 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000642
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000643 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000644 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000645 }
646}
Douglas Gregor7454c562010-07-02 20:37:36 +0000647
John McCall9f3059a2009-10-09 21:13:30 +0000648// Adds all qualifying matches for a name within a decl context to the
649// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000650static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000651 bool Found = false;
652
Douglas Gregor7454c562010-07-02 20:37:36 +0000653 // Lazily declare C++ special member functions.
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000654 if (S.getLangOptions().CPlusPlus)
655 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000656
Douglas Gregor7454c562010-07-02 20:37:36 +0000657 // Perform lookup into this declaration context.
John McCallf6c8a4e2009-11-10 07:01:13 +0000658 DeclContext::lookup_const_iterator I, E;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000659 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall401982f2010-01-20 21:53:11 +0000660 NamedDecl *D = *I;
Douglas Gregor4a814562011-12-14 16:03:29 +0000661 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000662 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000663 Found = true;
664 }
665 }
John McCall9f3059a2009-10-09 21:13:30 +0000666
Douglas Gregord3a59182010-02-12 05:48:04 +0000667 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
668 return true;
669
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000670 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000671 != DeclarationName::CXXConversionFunctionName ||
672 R.getLookupName().getCXXNameType()->isDependentType() ||
673 !isa<CXXRecordDecl>(DC))
674 return Found;
675
676 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000677 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000678 // name lookup. Instead, any conversion function templates visible in the
679 // context of the use are considered. [...]
680 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000681 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000682 return Found;
683
684 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000685 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
Chandler Carruth3a693b72010-01-31 11:44:02 +0000686 UEnd = Unresolved->end(); U != UEnd; ++U) {
687 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
688 if (!ConvTemplate)
689 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000690
Chandler Carruth3a693b72010-01-31 11:44:02 +0000691 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000692 // add the conversion function template. When we deduce template
693 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000694 // type of the new declaration with the type of the function template.
695 if (R.isForRedeclaration()) {
696 R.addDecl(ConvTemplate);
697 Found = true;
698 continue;
699 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000700
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000701 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000702 // [...] For each such operator, if argument deduction succeeds
703 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000704 // name lookup.
705 //
706 // When referencing a conversion function for any purpose other than
707 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000708 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000709 // specialization into the result set. We do this to avoid forcing all
710 // callers to perform special deduction for conversion functions.
John McCall19c1bfd2010-08-25 05:32:35 +0000711 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruth3a693b72010-01-31 11:44:02 +0000712 FunctionDecl *Specialization = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000713
714 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000715 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
716 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000717
Chandler Carruth3a693b72010-01-31 11:44:02 +0000718 // Compute the type of the function that we would expect the conversion
719 // function to have, if it were to match the name given.
720 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000721 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
722 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
Sebastian Redl7c6c9e92011-03-06 10:52:04 +0000723 EPI.ExceptionSpecType = EST_None;
John McCalldb40c7f2010-12-14 08:05:40 +0000724 EPI.NumExceptions = 0;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000725 QualType ExpectedType
726 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
John McCalldb40c7f2010-12-14 08:05:40 +0000727 0, 0, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000728
Chandler Carruth3a693b72010-01-31 11:44:02 +0000729 // Perform template argument deduction against the type that we would
730 // expect the function to have.
731 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
732 Specialization, Info)
733 == Sema::TDK_Success) {
734 R.addDecl(Specialization);
735 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000736 }
737 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000738
John McCall9f3059a2009-10-09 21:13:30 +0000739 return Found;
740}
741
John McCallf6c8a4e2009-11-10 07:01:13 +0000742// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000743static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000744CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000745 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000746
747 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
748
John McCallf6c8a4e2009-11-10 07:01:13 +0000749 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000750 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000751
John McCallf6c8a4e2009-11-10 07:01:13 +0000752 // Perform direct name lookup into the namespaces nominated by the
753 // using directives whose common ancestor is this namespace.
754 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
755 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000756
John McCallf6c8a4e2009-11-10 07:01:13 +0000757 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000758 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000759 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000760
761 R.resolveKind();
762
763 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000764}
765
766static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000767 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000768 return Ctx->isFileContext();
769 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000770}
Douglas Gregored8f2882009-01-30 01:04:22 +0000771
Douglas Gregor66230062010-03-15 14:33:29 +0000772// Find the next outer declaration context from this scope. This
773// routine actually returns the semantic outer context, which may
774// differ from the lexical context (encoded directly in the Scope
775// stack) when we are parsing a member of a class template. In this
776// case, the second element of the pair will be true, to indicate that
777// name lookup should continue searching in this semantic context when
778// it leaves the current template parameter scope.
779static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
780 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
781 DeclContext *Lexical = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000782 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000783 OuterS = OuterS->getParent()) {
784 if (OuterS->getEntity()) {
Douglas Gregorea166062010-03-15 15:26:48 +0000785 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor66230062010-03-15 14:33:29 +0000786 break;
787 }
788 }
789
790 // C++ [temp.local]p8:
791 // In the definition of a member of a class template that appears
792 // outside of the namespace containing the class template
793 // definition, the name of a template-parameter hides the name of
794 // a member of this namespace.
795 //
796 // Example:
797 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000798 // namespace N {
799 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000800 //
801 // template<class T> class B {
802 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000803 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000804 // }
805 //
806 // template<class C> void N::B<C>::f(C) {
807 // C b; // C is the template parameter, not N::C
808 // }
809 //
810 // In this example, the lexical context we return is the
811 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000812 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000813 !S->getParent()->isTemplateParamScope())
814 return std::make_pair(Lexical, false);
815
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000816 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000817 // For the example, this is the scope for the template parameters of
818 // template<class C>.
819 Scope *OutermostTemplateScope = S->getParent();
820 while (OutermostTemplateScope->getParent() &&
821 OutermostTemplateScope->getParent()->isTemplateParamScope())
822 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000823
Douglas Gregor66230062010-03-15 14:33:29 +0000824 // Find the namespace context in which the original scope occurs. In
825 // the example, this is namespace N.
826 DeclContext *Semantic = DC;
827 while (!Semantic->isFileContext())
828 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000829
Douglas Gregor66230062010-03-15 14:33:29 +0000830 // Find the declaration context just outside of the template
831 // parameter scope. This is the context in which the template is
832 // being lexically declaration (a namespace context). In the
833 // example, this is the global scope.
834 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
835 Lexical->Encloses(Semantic))
836 return std::make_pair(Semantic, true);
837
838 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000839}
840
John McCall27b18f82009-11-17 02:14:36 +0000841bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCallea305ed2009-12-18 10:40:03 +0000842 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000843
844 DeclarationName Name = R.getLookupName();
845
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000846 // If this is the name of an implicitly-declared special member function,
847 // go through the scope stack to implicitly declare
848 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
849 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
850 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
851 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
852 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000853
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000854 // Implicitly declare member functions with the name we're looking for, if in
855 // fact we are in a scope where it matters.
856
Douglas Gregor889ceb72009-02-03 19:21:40 +0000857 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000858 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000859 I = IdResolver.begin(Name),
860 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000861
Douglas Gregor889ceb72009-02-03 19:21:40 +0000862 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000863 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000864 // ...During unqualified name lookup (3.4.1), the names appear as if
865 // they were declared in the nearest enclosing namespace which contains
866 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000867 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000868 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000869 //
870 // For example:
871 // namespace A { int i; }
872 // void foo() {
873 // int i;
874 // {
875 // using namespace A;
876 // ++i; // finds local 'i', A::i appears at global scope
877 // }
878 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000879 //
Douglas Gregor66230062010-03-15 14:33:29 +0000880 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor700792c2009-02-05 19:25:20 +0000881 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor3e51e172010-05-20 20:58:56 +0000882 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
883
Douglas Gregor889ceb72009-02-03 19:21:40 +0000884 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000885 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000886 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000887 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
John McCall9f3059a2009-10-09 21:13:30 +0000888 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +0000889 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000890 }
891 }
John McCall9f3059a2009-10-09 21:13:30 +0000892 if (Found) {
893 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000894 if (S->isClassScope())
895 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
896 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000897 return true;
898 }
899
Douglas Gregor66230062010-03-15 14:33:29 +0000900 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
901 S->getParent() && !S->getParent()->isTemplateParamScope()) {
902 // We've just searched the last template parameter scope and
903 // found nothing, so look into the the contexts between the
904 // lexical and semantic declaration contexts returned by
905 // findOuterContext(). This implements the name lookup behavior
906 // of C++ [temp.local]p8.
907 Ctx = OutsideOfTemplateParamDC;
908 OutsideOfTemplateParamDC = 0;
909 }
910
911 if (Ctx) {
912 DeclContext *OuterCtx;
913 bool SearchAfterTemplateScope;
914 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
915 if (SearchAfterTemplateScope)
916 OutsideOfTemplateParamDC = OuterCtx;
917
Douglas Gregorea166062010-03-15 15:26:48 +0000918 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000919 // We do not directly look into transparent contexts, since
920 // those entities will be found in the nearest enclosing
921 // non-transparent context.
922 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000923 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000924
925 // We do not look directly into function or method contexts,
926 // since all of the local variables and parameters of the
927 // function/method are present within the Scope.
928 if (Ctx->isFunctionOrMethod()) {
929 // If we have an Objective-C instance method, look for ivars
930 // in the corresponding interface.
931 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
932 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
933 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
934 ObjCInterfaceDecl *ClassDeclared;
935 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000936 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +0000937 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000938 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
939 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +0000940 R.resolveKind();
941 return true;
942 }
943 }
944 }
945 }
946
947 continue;
948 }
949
Douglas Gregor7f737c02009-09-10 16:57:35 +0000950 // Perform qualified name lookup into this context.
951 // FIXME: In some cases, we know that every name that could be found by
952 // this qualified name lookup will also be on the identifier chain. For
953 // example, inside a class without any base classes, we never need to
954 // perform qualified lookup because all of the members are on top of the
955 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000956 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +0000957 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000958 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000959 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000960 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000961
John McCallf6c8a4e2009-11-10 07:01:13 +0000962 // Stop if we ran out of scopes.
963 // FIXME: This really, really shouldn't be happening.
964 if (!S) return false;
965
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +0000966 // If we are looking for members, no need to look into global/namespace scope.
967 if (R.getLookupKind() == LookupMemberName)
968 return false;
969
Douglas Gregor700792c2009-02-05 19:25:20 +0000970 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000971 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000972 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000973 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
974 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000975
John McCallf6c8a4e2009-11-10 07:01:13 +0000976 UnqualUsingDirectiveSet UDirs;
977 UDirs.visitScopeChain(Initial, S);
978 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000979
Douglas Gregor700792c2009-02-05 19:25:20 +0000980 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000981 // Unqualified name lookup in C++ requires looking into scopes
982 // that aren't strictly lexical, and therefore we walk through the
983 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000984
Douglas Gregor889ceb72009-02-03 19:21:40 +0000985 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000986 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000987 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000988 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000989 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000990 // We found something. Look for anything else in our scope
991 // with this same name and in an acceptable identifier
992 // namespace, so that we can construct an overload set if we
993 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000994 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +0000995 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000996 }
997 }
998
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000999 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +00001000 R.resolveKind();
1001 return true;
1002 }
1003
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001004 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1005 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1006 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1007 // We've just searched the last template parameter scope and
1008 // found nothing, so look into the the contexts between the
1009 // lexical and semantic declaration contexts returned by
1010 // findOuterContext(). This implements the name lookup behavior
1011 // of C++ [temp.local]p8.
1012 Ctx = OutsideOfTemplateParamDC;
1013 OutsideOfTemplateParamDC = 0;
1014 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001015
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001016 if (Ctx) {
1017 DeclContext *OuterCtx;
1018 bool SearchAfterTemplateScope;
1019 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1020 if (SearchAfterTemplateScope)
1021 OutsideOfTemplateParamDC = OuterCtx;
1022
1023 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1024 // We do not directly look into transparent contexts, since
1025 // those entities will be found in the nearest enclosing
1026 // non-transparent context.
1027 if (Ctx->isTransparentContext())
1028 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001029
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001030 // If we have a context, and it's not a context stashed in the
1031 // template parameter scope for an out-of-line definition, also
1032 // look into that context.
1033 if (!(Found && S && S->isTemplateParamScope())) {
1034 assert(Ctx->isFileContext() &&
1035 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001036
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001037 // Look into context considering using-directives.
1038 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1039 Found = true;
1040 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001041
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001042 if (Found) {
1043 R.resolveKind();
1044 return true;
1045 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001046
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001047 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1048 return false;
1049 }
1050 }
1051
Douglas Gregor3ce74932010-02-05 07:07:10 +00001052 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001053 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001054 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001055
John McCall9f3059a2009-10-09 21:13:30 +00001056 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001057}
1058
Douglas Gregor4a814562011-12-14 16:03:29 +00001059/// \brief Retrieve the visible declaration corresponding to D, if any.
1060///
1061/// This routine determines whether the declaration D is visible in the current
1062/// module, with the current imports. If not, it checks whether any
1063/// redeclaration of D is visible, and if so, returns that declaration.
1064///
1065/// \returns D, or a visible previous declaration of D, whichever is more recent
1066/// and visible. If no declaration of D is visible, returns null.
1067static NamedDecl *getVisibleDecl(NamedDecl *D) {
1068 if (LookupResult::isVisible(D))
1069 return D;
1070
Douglas Gregor54079202012-01-06 22:05:37 +00001071 for (Decl::redecl_iterator RD = D->redecls_begin(), RDEnd = D->redecls_end();
1072 RD != RDEnd; ++RD) {
1073 if (NamedDecl *ND = dyn_cast<NamedDecl>(*RD)) {
1074 if (LookupResult::isVisible(ND))
1075 return ND;
1076 }
Douglas Gregor4a814562011-12-14 16:03:29 +00001077 }
1078
1079 return 0;
1080}
1081
Douglas Gregor34074322009-01-14 22:20:51 +00001082/// @brief Perform unqualified name lookup starting from a given
1083/// scope.
1084///
1085/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1086/// used to find names within the current scope. For example, 'x' in
1087/// @code
1088/// int x;
1089/// int f() {
1090/// return x; // unqualified name look finds 'x' in the global scope
1091/// }
1092/// @endcode
1093///
1094/// Different lookup criteria can find different names. For example, a
1095/// particular scope can have both a struct and a function of the same
1096/// name, and each can be found by certain lookup criteria. For more
1097/// information about lookup criteria, see the documentation for the
1098/// class LookupCriteria.
1099///
1100/// @param S The scope from which unqualified name lookup will
1101/// begin. If the lookup criteria permits, name lookup may also search
1102/// in the parent scopes.
1103///
1104/// @param Name The name of the entity that we are searching for.
1105///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001106/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001107/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001108/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +00001109///
1110/// @returns The result of name lookup, which includes zero or more
1111/// declarations and possibly additional information used to diagnose
1112/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +00001113bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1114 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001115 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001116
John McCall27b18f82009-11-17 02:14:36 +00001117 LookupNameKind NameKind = R.getLookupKind();
1118
Douglas Gregor34074322009-01-14 22:20:51 +00001119 if (!getLangOptions().CPlusPlus) {
1120 // Unqualified name lookup in C/Objective-C is purely lexical, so
1121 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001122 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001123 // Find the nearest non-transparent declaration scope.
1124 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +00001125 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +00001126 static_cast<DeclContext *>(S->getEntity())
1127 ->isTransparentContext()))
1128 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001129 }
1130
John McCallea305ed2009-12-18 10:40:03 +00001131 unsigned IDNS = R.getIdentifierNamespace();
1132
Douglas Gregor34074322009-01-14 22:20:51 +00001133 // Scan up the scope chain looking for a decl that matches this
1134 // identifier that is in the appropriate namespace. This search
1135 // should not take long, as shadowing of names is uncommon, and
1136 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001137 bool LeftStartingScope = false;
1138
Douglas Gregored8f2882009-01-30 01:04:22 +00001139 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001140 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001141 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001142 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001143 if (NameKind == LookupRedeclarationWithLinkage) {
1144 // Determine whether this (or a previous) declaration is
1145 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001146 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001147 LeftStartingScope = true;
1148
1149 // If we found something outside of our starting scope that
1150 // does not have linkage, skip it.
1151 if (LeftStartingScope && !((*I)->hasLinkage()))
1152 continue;
1153 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001154 else if (NameKind == LookupObjCImplicitSelfParam &&
1155 !isa<ImplicitParamDecl>(*I))
1156 continue;
1157
Douglas Gregor2a5d1482011-12-02 20:08:44 +00001158 // If this declaration is module-private and it came from an AST
1159 // file, we can't see it.
Douglas Gregor5c193c72012-01-05 01:11:47 +00001160 NamedDecl *D = R.isHiddenDeclarationVisible()? *I : getVisibleDecl(*I);
Douglas Gregor4a814562011-12-14 16:03:29 +00001161 if (!D)
Douglas Gregor2a5d1482011-12-02 20:08:44 +00001162 continue;
Douglas Gregor4a814562011-12-14 16:03:29 +00001163
1164 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001165
Douglas Gregorb59643b2012-01-03 23:26:26 +00001166 // Check whether there are any other declarations with the same name
1167 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001168 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001169 // Find the scope in which this declaration was declared (if it
1170 // actually exists in a Scope).
1171 while (S && !S->isDeclScope(D))
1172 S = S->getParent();
1173
1174 // If the scope containing the declaration is the translation unit,
1175 // then we'll need to perform our checks based on the matching
1176 // DeclContexts rather than matching scopes.
1177 if (S && isNamespaceOrTranslationUnitScope(S))
1178 S = 0;
1179
1180 // Compute the DeclContext, if we need it.
1181 DeclContext *DC = 0;
1182 if (!S)
1183 DC = (*I)->getDeclContext()->getRedeclContext();
1184
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001185 IdentifierResolver::iterator LastI = I;
1186 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001187 if (S) {
1188 // Match based on scope.
1189 if (!S->isDeclScope(*LastI))
1190 break;
1191 } else {
1192 // Match based on DeclContext.
1193 DeclContext *LastDC
1194 = (*LastI)->getDeclContext()->getRedeclContext();
1195 if (!LastDC->Equals(DC))
1196 break;
1197 }
1198
1199 // If the declaration isn't in the right namespace, skip it.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001200 if (!(*LastI)->isInIdentifierNamespace(IDNS))
1201 continue;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001202
Douglas Gregor5c193c72012-01-05 01:11:47 +00001203 D = R.isHiddenDeclarationVisible()? *LastI : getVisibleDecl(*LastI);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001204 if (D)
1205 R.addDecl(D);
1206 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001207
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001208 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001209 }
John McCall9f3059a2009-10-09 21:13:30 +00001210 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001211 }
Douglas Gregor34074322009-01-14 22:20:51 +00001212 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001213 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001214 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001215 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001216 }
1217
1218 // If we didn't find a use of this identifier, and if the identifier
1219 // corresponds to a compiler builtin, create the decl object for the builtin
1220 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001221 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1222 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001223
Axel Naumann016538a2011-02-24 16:47:47 +00001224 // If we didn't find a use of this identifier, the ExternalSource
1225 // may be able to handle the situation.
1226 // Note: some lookup failures are expected!
1227 // See e.g. R.isForRedeclaration().
1228 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001229}
1230
John McCall6538c932009-10-10 05:48:19 +00001231/// @brief Perform qualified name lookup in the namespaces nominated by
1232/// using directives by the given context.
1233///
1234/// C++98 [namespace.qual]p2:
1235/// Given X::m (where X is a user-declared namespace), or given ::m
1236/// (where X is the global namespace), let S be the set of all
1237/// declarations of m in X and in the transitive closure of all
1238/// namespaces nominated by using-directives in X and its used
1239/// namespaces, except that using-directives are ignored in any
1240/// namespace, including X, directly containing one or more
1241/// declarations of m. No namespace is searched more than once in
1242/// the lookup of a name. If S is the empty set, the program is
1243/// ill-formed. Otherwise, if S has exactly one member, or if the
1244/// context of the reference is a using-declaration
1245/// (namespace.udecl), S is the required set of declarations of
1246/// m. Otherwise if the use of m is not one that allows a unique
1247/// declaration to be chosen from S, the program is ill-formed.
1248/// C++98 [namespace.qual]p5:
1249/// During the lookup of a qualified namespace member name, if the
1250/// lookup finds more than one declaration of the member, and if one
1251/// declaration introduces a class name or enumeration name and the
1252/// other declarations either introduce the same object, the same
1253/// enumerator or a set of functions, the non-type name hides the
1254/// class or enumeration name if and only if the declarations are
1255/// from the same namespace; otherwise (the declarations are from
1256/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001257static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001258 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001259 assert(StartDC->isFileContext() && "start context is not a file context");
1260
1261 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1262 DeclContext::udir_iterator E = StartDC->using_directives_end();
1263
1264 if (I == E) return false;
1265
1266 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001267 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001268 Visited.insert(StartDC);
1269
1270 // We have not yet looked into these namespaces, much less added
1271 // their "using-children" to the queue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001272 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001273
1274 // We have already looked into the initial namespace; seed the queue
1275 // with its using-children.
1276 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +00001277 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001278 if (Visited.insert(ND))
John McCall6538c932009-10-10 05:48:19 +00001279 Queue.push_back(ND);
1280 }
1281
1282 // The easiest way to implement the restriction in [namespace.qual]p5
1283 // is to check whether any of the individual results found a tag
1284 // and, if so, to declare an ambiguity if the final result is not
1285 // a tag.
1286 bool FoundTag = false;
1287 bool FoundNonTag = false;
1288
John McCall5cebab12009-11-18 07:57:50 +00001289 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001290
1291 bool Found = false;
1292 while (!Queue.empty()) {
1293 NamespaceDecl *ND = Queue.back();
1294 Queue.pop_back();
1295
1296 // We go through some convolutions here to avoid copying results
1297 // between LookupResults.
1298 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001299 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001300 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001301
1302 if (FoundDirect) {
1303 // First do any local hiding.
1304 DirectR.resolveKind();
1305
1306 // If the local result is a tag, remember that.
1307 if (DirectR.isSingleTagDecl())
1308 FoundTag = true;
1309 else
1310 FoundNonTag = true;
1311
1312 // Append the local results to the total results if necessary.
1313 if (UseLocal) {
1314 R.addAllDecls(LocalR);
1315 LocalR.clear();
1316 }
1317 }
1318
1319 // If we find names in this namespace, ignore its using directives.
1320 if (FoundDirect) {
1321 Found = true;
1322 continue;
1323 }
1324
1325 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1326 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001327 if (Visited.insert(Nom))
John McCall6538c932009-10-10 05:48:19 +00001328 Queue.push_back(Nom);
1329 }
1330 }
1331
1332 if (Found) {
1333 if (FoundTag && FoundNonTag)
1334 R.setAmbiguousQualifiedTagHiding();
1335 else
1336 R.resolveKind();
1337 }
1338
1339 return Found;
1340}
1341
Douglas Gregor39982192010-08-15 06:18:01 +00001342/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001343static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor39982192010-08-15 06:18:01 +00001344 CXXBasePath &Path,
1345 void *Name) {
1346 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001347
Douglas Gregor39982192010-08-15 06:18:01 +00001348 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1349 Path.Decls = BaseRecord->lookup(N);
1350 return Path.Decls.first != Path.Decls.second;
1351}
1352
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001353/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001354/// static members, nested types, and enumerators.
1355template<typename InputIterator>
1356static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1357 Decl *D = (*First)->getUnderlyingDecl();
1358 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1359 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001360
Douglas Gregorc0d24902010-10-22 22:08:47 +00001361 if (isa<CXXMethodDecl>(D)) {
1362 // Determine whether all of the methods are static.
1363 bool AllMethodsAreStatic = true;
1364 for(; First != Last; ++First) {
1365 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001366
Douglas Gregorc0d24902010-10-22 22:08:47 +00001367 if (!isa<CXXMethodDecl>(D)) {
1368 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1369 break;
1370 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001371
Douglas Gregorc0d24902010-10-22 22:08:47 +00001372 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1373 AllMethodsAreStatic = false;
1374 break;
1375 }
1376 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001377
Douglas Gregorc0d24902010-10-22 22:08:47 +00001378 if (AllMethodsAreStatic)
1379 return true;
1380 }
1381
1382 return false;
1383}
1384
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001385/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001386///
1387/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1388/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001389/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001390///
1391/// Different lookup criteria can find different names. For example, a
1392/// particular scope can have both a struct and a function of the same
1393/// name, and each can be found by certain lookup criteria. For more
1394/// information about lookup criteria, see the documentation for the
1395/// class LookupCriteria.
1396///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001397/// \param R captures both the lookup criteria and any lookup results found.
1398///
1399/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001400/// search. If the lookup criteria permits, name lookup may also search
1401/// in the parent contexts or (for C++ classes) base classes.
1402///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001403/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001404/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001405///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001406/// \returns true if lookup succeeded, false if it failed.
1407bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1408 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001409 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001410
John McCall27b18f82009-11-17 02:14:36 +00001411 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001412 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001413
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001414 // Make sure that the declaration context is complete.
1415 assert((!isa<TagDecl>(LookupCtx) ||
1416 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00001417 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001418 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1419 ->isBeingDefined()) &&
1420 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001421
Douglas Gregor34074322009-01-14 22:20:51 +00001422 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001423 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001424 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001425 if (isa<CXXRecordDecl>(LookupCtx))
1426 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001427 return true;
1428 }
Douglas Gregor34074322009-01-14 22:20:51 +00001429
John McCall6538c932009-10-10 05:48:19 +00001430 // Don't descend into implied contexts for redeclarations.
1431 // C++98 [namespace.qual]p6:
1432 // In a declaration for a namespace member in which the
1433 // declarator-id is a qualified-id, given that the qualified-id
1434 // for the namespace member has the form
1435 // nested-name-specifier unqualified-id
1436 // the unqualified-id shall name a member of the namespace
1437 // designated by the nested-name-specifier.
1438 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001439 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001440 return false;
1441
John McCall27b18f82009-11-17 02:14:36 +00001442 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001443 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001444 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001445
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001446 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001447 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001448 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001449 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001450 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001451
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001452 // If we're performing qualified name lookup into a dependent class,
1453 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001454 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001455 // template instantiation time (at which point all bases will be available)
1456 // or we have to fail.
1457 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1458 LookupRec->hasAnyDependentBases()) {
1459 R.setNotFoundInCurrentInstantiation();
1460 return false;
1461 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001462
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001463 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001464 CXXBasePaths Paths;
1465 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001466
1467 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001468 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001469 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001470 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001471 case LookupOrdinaryName:
1472 case LookupMemberName:
1473 case LookupRedeclarationWithLinkage:
1474 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1475 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001476
Douglas Gregor36d1b142009-10-06 17:59:45 +00001477 case LookupTagName:
1478 BaseCallback = &CXXRecordDecl::FindTagMember;
1479 break;
John McCall84d87672009-12-10 09:41:52 +00001480
Douglas Gregor39982192010-08-15 06:18:01 +00001481 case LookupAnyName:
1482 BaseCallback = &LookupAnyMember;
1483 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001484
John McCall84d87672009-12-10 09:41:52 +00001485 case LookupUsingDeclName:
1486 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001487
Douglas Gregor36d1b142009-10-06 17:59:45 +00001488 case LookupOperatorName:
1489 case LookupNamespaceName:
1490 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001491 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001492 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001493 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001494
Douglas Gregor36d1b142009-10-06 17:59:45 +00001495 case LookupNestedNameSpecifierName:
1496 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1497 break;
1498 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001499
John McCall27b18f82009-11-17 02:14:36 +00001500 if (!LookupRec->lookupInBases(BaseCallback,
1501 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001502 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001503
John McCall553c0792010-01-23 00:46:32 +00001504 R.setNamingClass(LookupRec);
1505
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001506 // C++ [class.member.lookup]p2:
1507 // [...] If the resulting set of declarations are not all from
1508 // sub-objects of the same type, or the set has a nonstatic member
1509 // and includes members from distinct sub-objects, there is an
1510 // ambiguity and the program is ill-formed. Otherwise that set is
1511 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001512 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001513 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001514 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001515
Douglas Gregor36d1b142009-10-06 17:59:45 +00001516 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001517 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001518 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001519
John McCall401982f2010-01-20 21:53:11 +00001520 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1521 // across all paths.
1522 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001523
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001524 // Determine whether we're looking at a distinct sub-object or not.
1525 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001526 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001527 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1528 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001529 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001530 }
1531
Douglas Gregorc0d24902010-10-22 22:08:47 +00001532 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001533 != Context.getCanonicalType(PathElement.Base->getType())) {
1534 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001535 // different types. If the declaration sets aren't the same, this
1536 // this lookup is ambiguous.
1537 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1538 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1539 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1540 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001541
Douglas Gregorc0d24902010-10-22 22:08:47 +00001542 while (FirstD != FirstPath->Decls.second &&
1543 CurrentD != Path->Decls.second) {
1544 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1545 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1546 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001547
Douglas Gregorc0d24902010-10-22 22:08:47 +00001548 ++FirstD;
1549 ++CurrentD;
1550 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001551
Douglas Gregorc0d24902010-10-22 22:08:47 +00001552 if (FirstD == FirstPath->Decls.second &&
1553 CurrentD == Path->Decls.second)
1554 continue;
1555 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001556
John McCall9f3059a2009-10-09 21:13:30 +00001557 R.setAmbiguousBaseSubobjectTypes(Paths);
1558 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001559 }
1560
Douglas Gregorc0d24902010-10-22 22:08:47 +00001561 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001562 // We have a different subobject of the same type.
1563
1564 // C++ [class.member.lookup]p5:
1565 // A static member, a nested type or an enumerator defined in
1566 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001567 // has more than one base class subobject of type T.
Douglas Gregorc0d24902010-10-22 22:08:47 +00001568 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001569 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001570
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001571 // We have found a nonstatic member name in multiple, distinct
1572 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001573 R.setAmbiguousBaseSubobjects(Paths);
1574 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001575 }
1576 }
1577
1578 // Lookup in a base class succeeded; return these results.
1579
John McCall9f3059a2009-10-09 21:13:30 +00001580 DeclContext::lookup_iterator I, E;
John McCall553c0792010-01-23 00:46:32 +00001581 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1582 NamedDecl *D = *I;
1583 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1584 D->getAccess());
1585 R.addDecl(D, AS);
1586 }
John McCall9f3059a2009-10-09 21:13:30 +00001587 R.resolveKind();
1588 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001589}
1590
1591/// @brief Performs name lookup for a name that was parsed in the
1592/// source code, and may contain a C++ scope specifier.
1593///
1594/// This routine is a convenience routine meant to be called from
1595/// contexts that receive a name and an optional C++ scope specifier
1596/// (e.g., "N::M::x"). It will then perform either qualified or
1597/// unqualified name lookup (with LookupQualifiedName or LookupName,
1598/// respectively) on the given name and return those results.
1599///
1600/// @param S The scope from which unqualified name lookup will
1601/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001602///
Douglas Gregore861bac2009-08-25 22:51:20 +00001603/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001604///
Douglas Gregore861bac2009-08-25 22:51:20 +00001605/// @param EnteringContext Indicates whether we are going to enter the
1606/// context of the scope-specifier SS (if present).
1607///
John McCall9f3059a2009-10-09 21:13:30 +00001608/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001609bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001610 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001611 if (SS && SS->isInvalid()) {
1612 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001613 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001614 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001615 }
Mike Stump11289f42009-09-09 15:08:12 +00001616
Douglas Gregore861bac2009-08-25 22:51:20 +00001617 if (SS && SS->isSet()) {
1618 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001619 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001620 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001621 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001622 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001623
John McCall27b18f82009-11-17 02:14:36 +00001624 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00001625 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001626 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001627
Douglas Gregore861bac2009-08-25 22:51:20 +00001628 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001629 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001630 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00001631 R.setNotFoundInCurrentInstantiation();
1632 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00001633 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001634 }
1635
Mike Stump11289f42009-09-09 15:08:12 +00001636 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001637 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001638}
1639
Douglas Gregor889ceb72009-02-03 19:21:40 +00001640
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001641/// @brief Produce a diagnostic describing the ambiguity that resulted
1642/// from name lookup.
1643///
1644/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001645///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001646/// @param Name The name of the entity that name lookup was
1647/// searching for.
1648///
1649/// @param NameLoc The location of the name within the source code.
1650///
1651/// @param LookupRange A source range that provides more
1652/// source-location information concerning the lookup itself. For
1653/// example, this range might highlight a nested-name-specifier that
1654/// precedes the name.
1655///
1656/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001657bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001658 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1659
John McCall27b18f82009-11-17 02:14:36 +00001660 DeclarationName Name = Result.getLookupName();
1661 SourceLocation NameLoc = Result.getNameLoc();
1662 SourceRange LookupRange = Result.getContextRange();
1663
John McCall6538c932009-10-10 05:48:19 +00001664 switch (Result.getAmbiguityKind()) {
1665 case LookupResult::AmbiguousBaseSubobjects: {
1666 CXXBasePaths *Paths = Result.getBasePaths();
1667 QualType SubobjectType = Paths->front().back().Base->getType();
1668 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1669 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1670 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001671
John McCall6538c932009-10-10 05:48:19 +00001672 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1673 while (isa<CXXMethodDecl>(*Found) &&
1674 cast<CXXMethodDecl>(*Found)->isStatic())
1675 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001676
John McCall6538c932009-10-10 05:48:19 +00001677 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001678
John McCall6538c932009-10-10 05:48:19 +00001679 return true;
1680 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001681
John McCall6538c932009-10-10 05:48:19 +00001682 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001683 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1684 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001685
John McCall6538c932009-10-10 05:48:19 +00001686 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001687 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001688 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1689 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001690 Path != PathEnd; ++Path) {
1691 Decl *D = *Path->Decls.first;
1692 if (DeclsPrinted.insert(D).second)
1693 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1694 }
1695
Douglas Gregor1c846b02009-01-16 00:38:09 +00001696 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001697 }
1698
John McCall6538c932009-10-10 05:48:19 +00001699 case LookupResult::AmbiguousTagHiding: {
1700 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001701
John McCall6538c932009-10-10 05:48:19 +00001702 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1703
1704 LookupResult::iterator DI, DE = Result.end();
1705 for (DI = Result.begin(); DI != DE; ++DI)
1706 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1707 TagDecls.insert(TD);
1708 Diag(TD->getLocation(), diag::note_hidden_tag);
1709 }
1710
1711 for (DI = Result.begin(); DI != DE; ++DI)
1712 if (!isa<TagDecl>(*DI))
1713 Diag((*DI)->getLocation(), diag::note_hiding_object);
1714
1715 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001716 LookupResult::Filter F = Result.makeFilter();
1717 while (F.hasNext()) {
1718 if (TagDecls.count(F.next()))
1719 F.erase();
1720 }
1721 F.done();
John McCall6538c932009-10-10 05:48:19 +00001722
1723 return true;
1724 }
1725
1726 case LookupResult::AmbiguousReference: {
1727 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001728
John McCall6538c932009-10-10 05:48:19 +00001729 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1730 for (; DI != DE; ++DI)
1731 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001732
John McCall6538c932009-10-10 05:48:19 +00001733 return true;
1734 }
1735 }
1736
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001737 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001738}
Douglas Gregore254f902009-02-04 00:32:51 +00001739
John McCallf24d7bb2010-05-28 18:45:08 +00001740namespace {
1741 struct AssociatedLookup {
1742 AssociatedLookup(Sema &S,
1743 Sema::AssociatedNamespaceSet &Namespaces,
1744 Sema::AssociatedClassSet &Classes)
1745 : S(S), Namespaces(Namespaces), Classes(Classes) {
1746 }
1747
1748 Sema &S;
1749 Sema::AssociatedNamespaceSet &Namespaces;
1750 Sema::AssociatedClassSet &Classes;
1751 };
1752}
1753
Mike Stump11289f42009-09-09 15:08:12 +00001754static void
John McCallf24d7bb2010-05-28 18:45:08 +00001755addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001756
Douglas Gregor8b895222010-04-30 07:08:38 +00001757static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1758 DeclContext *Ctx) {
1759 // Add the associated namespace for this class.
1760
1761 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1762 // be a locally scoped record.
1763
Sebastian Redlbd595762010-08-31 20:53:31 +00001764 // We skip out of inline namespaces. The innermost non-inline namespace
1765 // contains all names of all its nested inline namespaces anyway, so we can
1766 // replace the entire inline namespace tree with its root.
1767 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1768 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00001769 Ctx = Ctx->getParent();
1770
John McCallc7e8e792009-08-07 22:18:02 +00001771 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001772 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001773}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001774
Mike Stump11289f42009-09-09 15:08:12 +00001775// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001776// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001777static void
John McCallf24d7bb2010-05-28 18:45:08 +00001778addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1779 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001780 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001781 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001782 switch (Arg.getKind()) {
1783 case TemplateArgument::Null:
1784 break;
Mike Stump11289f42009-09-09 15:08:12 +00001785
Douglas Gregor197e5f72009-07-08 07:51:57 +00001786 case TemplateArgument::Type:
1787 // [...] the namespaces and classes associated with the types of the
1788 // template arguments provided for template type parameters (excluding
1789 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001790 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001791 break;
Mike Stump11289f42009-09-09 15:08:12 +00001792
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001793 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001794 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00001795 // [...] the namespaces in which any template template arguments are
1796 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001797 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001798 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00001799 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001800 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001801 DeclContext *Ctx = ClassTemplate->getDeclContext();
1802 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001803 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001804 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001805 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001806 }
1807 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001808 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001809
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001810 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001811 case TemplateArgument::Integral:
1812 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001813 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001814 // associated namespaces. ]
1815 break;
Mike Stump11289f42009-09-09 15:08:12 +00001816
Douglas Gregor197e5f72009-07-08 07:51:57 +00001817 case TemplateArgument::Pack:
1818 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1819 PEnd = Arg.pack_end();
1820 P != PEnd; ++P)
John McCallf24d7bb2010-05-28 18:45:08 +00001821 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001822 break;
1823 }
1824}
1825
Douglas Gregore254f902009-02-04 00:32:51 +00001826// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001827// argument-dependent lookup with an argument of class type
1828// (C++ [basic.lookup.koenig]p2).
1829static void
John McCallf24d7bb2010-05-28 18:45:08 +00001830addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1831 CXXRecordDecl *Class) {
1832
1833 // Just silently ignore anything whose name is __va_list_tag.
1834 if (Class->getDeclName() == Result.S.VAListTagName)
1835 return;
1836
Douglas Gregore254f902009-02-04 00:32:51 +00001837 // C++ [basic.lookup.koenig]p2:
1838 // [...]
1839 // -- If T is a class type (including unions), its associated
1840 // classes are: the class itself; the class of which it is a
1841 // member, if any; and its direct and indirect base
1842 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001843 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001844
1845 // Add the class of which it is a member, if any.
1846 DeclContext *Ctx = Class->getDeclContext();
1847 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001848 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001849 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001850 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001851
Douglas Gregore254f902009-02-04 00:32:51 +00001852 // Add the class itself. If we've already seen this class, we don't
1853 // need to visit base classes.
John McCallf24d7bb2010-05-28 18:45:08 +00001854 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00001855 return;
1856
Mike Stump11289f42009-09-09 15:08:12 +00001857 // -- If T is a template-id, its associated namespaces and classes are
1858 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001859 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001860 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001861 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001862 // namespaces in which any template template arguments are defined; and
1863 // the classes in which any member templates used as template template
1864 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001865 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001866 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001867 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1868 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1869 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001870 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001871 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001872 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001873
Douglas Gregor197e5f72009-07-08 07:51:57 +00001874 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1875 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00001876 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001877 }
Mike Stump11289f42009-09-09 15:08:12 +00001878
John McCall67da35c2010-02-04 22:26:26 +00001879 // Only recurse into base classes for complete types.
1880 if (!Class->hasDefinition()) {
1881 // FIXME: we might need to instantiate templates here
1882 return;
1883 }
1884
Douglas Gregore254f902009-02-04 00:32:51 +00001885 // Add direct and indirect base classes along with their associated
1886 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001887 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00001888 Bases.push_back(Class);
1889 while (!Bases.empty()) {
1890 // Pop this class off the stack.
1891 Class = Bases.back();
1892 Bases.pop_back();
1893
1894 // Visit the base classes.
1895 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1896 BaseEnd = Class->bases_end();
1897 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001898 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001899 // In dependent contexts, we do ADL twice, and the first time around,
1900 // the base type might be a dependent TemplateSpecializationType, or a
1901 // TemplateTypeParmType. If that happens, simply ignore it.
1902 // FIXME: If we want to support export, we probably need to add the
1903 // namespace of the template in a TemplateSpecializationType, or even
1904 // the classes and namespaces of known non-dependent arguments.
1905 if (!BaseType)
1906 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001907 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001908 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00001909 // Find the associated namespace for this base class.
1910 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00001911 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001912
1913 // Make sure we visit the bases of this base class.
1914 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1915 Bases.push_back(BaseDecl);
1916 }
1917 }
1918 }
1919}
1920
1921// \brief Add the associated classes and namespaces for
1922// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001923// (C++ [basic.lookup.koenig]p2).
1924static void
John McCallf24d7bb2010-05-28 18:45:08 +00001925addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00001926 // C++ [basic.lookup.koenig]p2:
1927 //
1928 // For each argument type T in the function call, there is a set
1929 // of zero or more associated namespaces and a set of zero or more
1930 // associated classes to be considered. The sets of namespaces and
1931 // classes is determined entirely by the types of the function
1932 // arguments (and the namespace of any template template
1933 // argument). Typedef names and using-declarations used to specify
1934 // the types do not contribute to this set. The sets of namespaces
1935 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00001936
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001937 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00001938 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1939
Douglas Gregore254f902009-02-04 00:32:51 +00001940 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00001941 switch (T->getTypeClass()) {
1942
1943#define TYPE(Class, Base)
1944#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1945#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1946#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1947#define ABSTRACT_TYPE(Class, Base)
1948#include "clang/AST/TypeNodes.def"
1949 // T is canonical. We can also ignore dependent types because
1950 // we don't need to do ADL at the definition point, but if we
1951 // wanted to implement template export (or if we find some other
1952 // use for associated classes and namespaces...) this would be
1953 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00001954 break;
Douglas Gregore254f902009-02-04 00:32:51 +00001955
John McCall0af3d3b2010-05-28 06:08:54 +00001956 // -- If T is a pointer to U or an array of U, its associated
1957 // namespaces and classes are those associated with U.
1958 case Type::Pointer:
1959 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1960 continue;
1961 case Type::ConstantArray:
1962 case Type::IncompleteArray:
1963 case Type::VariableArray:
1964 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1965 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001966
John McCall0af3d3b2010-05-28 06:08:54 +00001967 // -- If T is a fundamental type, its associated sets of
1968 // namespaces and classes are both empty.
1969 case Type::Builtin:
1970 break;
1971
1972 // -- If T is a class type (including unions), its associated
1973 // classes are: the class itself; the class of which it is a
1974 // member, if any; and its direct and indirect base
1975 // classes. Its associated namespaces are the namespaces in
1976 // which its associated classes are defined.
1977 case Type::Record: {
1978 CXXRecordDecl *Class
1979 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001980 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00001981 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00001982 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00001983
John McCall0af3d3b2010-05-28 06:08:54 +00001984 // -- If T is an enumeration type, its associated namespace is
1985 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001986 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00001987 // it has no associated class.
1988 case Type::Enum: {
1989 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001990
John McCall0af3d3b2010-05-28 06:08:54 +00001991 DeclContext *Ctx = Enum->getDeclContext();
1992 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001993 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001994
John McCall0af3d3b2010-05-28 06:08:54 +00001995 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001996 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001997
John McCall0af3d3b2010-05-28 06:08:54 +00001998 break;
1999 }
2000
2001 // -- If T is a function type, its associated namespaces and
2002 // classes are those associated with the function parameter
2003 // types and those associated with the return type.
2004 case Type::FunctionProto: {
2005 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2006 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
2007 ArgEnd = Proto->arg_type_end();
2008 Arg != ArgEnd; ++Arg)
2009 Queue.push_back(Arg->getTypePtr());
2010 // fallthrough
2011 }
2012 case Type::FunctionNoProto: {
2013 const FunctionType *FnType = cast<FunctionType>(T);
2014 T = FnType->getResultType().getTypePtr();
2015 continue;
2016 }
2017
2018 // -- If T is a pointer to a member function of a class X, its
2019 // associated namespaces and classes are those associated
2020 // with the function parameter types and return type,
2021 // together with those associated with X.
2022 //
2023 // -- If T is a pointer to a data member of class X, its
2024 // associated namespaces and classes are those associated
2025 // with the member type together with those associated with
2026 // X.
2027 case Type::MemberPointer: {
2028 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2029
2030 // Queue up the class type into which this points.
2031 Queue.push_back(MemberPtr->getClass());
2032
2033 // And directly continue with the pointee type.
2034 T = MemberPtr->getPointeeType().getTypePtr();
2035 continue;
2036 }
2037
2038 // As an extension, treat this like a normal pointer.
2039 case Type::BlockPointer:
2040 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2041 continue;
2042
2043 // References aren't covered by the standard, but that's such an
2044 // obvious defect that we cover them anyway.
2045 case Type::LValueReference:
2046 case Type::RValueReference:
2047 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2048 continue;
2049
2050 // These are fundamental types.
2051 case Type::Vector:
2052 case Type::ExtVector:
2053 case Type::Complex:
2054 break;
2055
Douglas Gregor8e936662011-04-12 01:02:45 +00002056 // If T is an Objective-C object or interface type, or a pointer to an
2057 // object or interface type, the associated namespace is the global
2058 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002059 case Type::ObjCObject:
2060 case Type::ObjCInterface:
2061 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002062 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002063 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002064
2065 // Atomic types are just wrappers; use the associations of the
2066 // contained type.
2067 case Type::Atomic:
2068 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2069 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002070 }
2071
2072 if (Queue.empty()) break;
2073 T = Queue.back();
2074 Queue.pop_back();
Douglas Gregore254f902009-02-04 00:32:51 +00002075 }
Douglas Gregore254f902009-02-04 00:32:51 +00002076}
2077
2078/// \brief Find the associated classes and namespaces for
2079/// argument-dependent lookup for a call with the given set of
2080/// arguments.
2081///
2082/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002083/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002084/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002085void
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002086Sema::FindAssociatedClassesAndNamespaces(llvm::ArrayRef<Expr *> Args,
Douglas Gregore254f902009-02-04 00:32:51 +00002087 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00002088 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002089 AssociatedNamespaces.clear();
2090 AssociatedClasses.clear();
2091
John McCallf24d7bb2010-05-28 18:45:08 +00002092 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
2093
Douglas Gregore254f902009-02-04 00:32:51 +00002094 // C++ [basic.lookup.koenig]p2:
2095 // For each argument type T in the function call, there is a set
2096 // of zero or more associated namespaces and a set of zero or more
2097 // associated classes to be considered. The sets of namespaces and
2098 // classes is determined entirely by the types of the function
2099 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002100 // argument).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002101 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregore254f902009-02-04 00:32:51 +00002102 Expr *Arg = Args[ArgIdx];
2103
2104 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002105 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002106 continue;
2107 }
2108
2109 // [...] In addition, if the argument is the name or address of a
2110 // set of overloaded functions and/or function templates, its
2111 // associated classes and namespaces are the union of those
2112 // associated with each of the members of the set: the namespace
2113 // in which the function or function template is defined and the
2114 // classes and namespaces associated with its (non-dependent)
2115 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002116 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002117 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002118 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002119 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002120
John McCallf24d7bb2010-05-28 18:45:08 +00002121 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2122 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002123
John McCallf24d7bb2010-05-28 18:45:08 +00002124 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2125 I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002126 // Look through any using declarations to find the underlying function.
2127 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002128
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002129 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2130 if (!FDecl)
2131 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002132
2133 // Add the classes and namespaces associated with the parameter
2134 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002135 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002136 }
2137 }
2138}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002139
2140/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2141/// an acceptable non-member overloaded operator for a call whose
2142/// arguments have types T1 (and, if non-empty, T2). This routine
2143/// implements the check in C++ [over.match.oper]p3b2 concerning
2144/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00002145static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002146IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2147 QualType T1, QualType T2,
2148 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00002149 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2150 return true;
2151
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002152 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2153 return true;
2154
John McCall9dd450b2009-09-21 23:43:11 +00002155 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002156 if (Proto->getNumArgs() < 1)
2157 return false;
2158
2159 if (T1->isEnumeralType()) {
2160 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002161 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002162 return true;
2163 }
2164
2165 if (Proto->getNumArgs() < 2)
2166 return false;
2167
2168 if (!T2.isNull() && T2->isEnumeralType()) {
2169 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002170 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002171 return true;
2172 }
2173
2174 return false;
2175}
2176
John McCall5cebab12009-11-18 07:57:50 +00002177NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002178 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002179 LookupNameKind NameKind,
2180 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002181 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002182 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002183 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002184}
2185
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002186/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002187ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002188 SourceLocation IdLoc,
2189 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002190 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002191 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002192 return cast_or_null<ObjCProtocolDecl>(D);
2193}
2194
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002195void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002196 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002197 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002198 // C++ [over.match.oper]p3:
2199 // -- The set of non-member candidates is the result of the
2200 // unqualified lookup of operator@ in the context of the
2201 // expression according to the usual rules for name lookup in
2202 // unqualified function calls (3.4.2) except that all member
2203 // functions are ignored. However, if no operand has a class
2204 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00002205 // that have a first parameter of type T1 or "reference to
2206 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002207 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00002208 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002209 // when T2 is an enumeration type, are candidate functions.
2210 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002211 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2212 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002213
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002214 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2215
John McCall9f3059a2009-10-09 21:13:30 +00002216 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002217 return;
2218
2219 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2220 Op != OpEnd; ++Op) {
Douglas Gregor645d76f2010-04-25 20:25:43 +00002221 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2222 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002223 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor645d76f2010-04-25 20:25:43 +00002224 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00002225 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor645d76f2010-04-25 20:25:43 +00002226 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor15448f82009-06-27 21:05:07 +00002227 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00002228 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00002229 // later?
2230 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor645d76f2010-04-25 20:25:43 +00002231 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor15448f82009-06-27 21:05:07 +00002232 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002233 }
2234}
2235
Alexis Hunt1da39282011-06-24 02:11:39 +00002236Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002237 CXXSpecialMember SM,
2238 bool ConstArg,
2239 bool VolatileArg,
2240 bool RValueThis,
2241 bool ConstThis,
2242 bool VolatileThis) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002243 RD = RD->getDefinition();
2244 assert((RD && !RD->isBeingDefined()) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002245 "doing special member lookup into record that isn't fully complete");
2246 if (RValueThis || ConstThis || VolatileThis)
2247 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2248 "constructors and destructors always have unqualified lvalue this");
2249 if (ConstArg || VolatileArg)
2250 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2251 "parameter-less special members can't have qualified arguments");
2252
2253 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002254 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002255 ID.AddInteger(SM);
2256 ID.AddInteger(ConstArg);
2257 ID.AddInteger(VolatileArg);
2258 ID.AddInteger(RValueThis);
2259 ID.AddInteger(ConstThis);
2260 ID.AddInteger(VolatileThis);
2261
2262 void *InsertPoint;
2263 SpecialMemberOverloadResult *Result =
2264 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2265
2266 // This was already cached
2267 if (Result)
2268 return Result;
2269
Alexis Huntba8e18d2011-06-07 00:11:58 +00002270 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2271 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002272 SpecialMemberCache.InsertNode(Result, InsertPoint);
2273
2274 if (SM == CXXDestructor) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002275 if (!RD->hasDeclaredDestructor())
2276 DeclareImplicitDestructor(RD);
2277 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002278 assert(DD && "record without a destructor");
2279 Result->setMethod(DD);
Richard Smithd951a1d2012-02-18 02:02:13 +00002280 Result->setSuccess(!DD->isDeleted());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002281 Result->setConstParamMatch(false);
2282 return Result;
2283 }
2284
Alexis Hunteef8ee02011-06-10 03:50:41 +00002285 // Prepare for overload resolution. Here we construct a synthetic argument
2286 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002287 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002288 DeclarationName Name;
2289 Expr *Arg = 0;
2290 unsigned NumArgs;
2291
2292 if (SM == CXXDefaultConstructor) {
2293 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2294 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002295 if (RD->needsImplicitDefaultConstructor())
2296 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002297 } else {
2298 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2299 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Alexis Hunt1da39282011-06-24 02:11:39 +00002300 if (!RD->hasDeclaredCopyConstructor())
2301 DeclareImplicitCopyConstructor(RD);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002302 if (getLangOptions().CPlusPlus0x && RD->needsImplicitMoveConstructor())
2303 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002304 } else {
2305 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Alexis Hunt1da39282011-06-24 02:11:39 +00002306 if (!RD->hasDeclaredCopyAssignment())
2307 DeclareImplicitCopyAssignment(RD);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002308 if (getLangOptions().CPlusPlus0x && RD->needsImplicitMoveAssignment())
2309 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002310 }
2311
2312 QualType ArgType = CanTy;
2313 if (ConstArg)
2314 ArgType.addConst();
2315 if (VolatileArg)
2316 ArgType.addVolatile();
2317
2318 // This isn't /really/ specified by the standard, but it's implied
2319 // we should be working from an RValue in the case of move to ensure
2320 // that we prefer to bind to rvalue references, and an LValue in the
2321 // case of copy to ensure we don't bind to rvalue references.
2322 // Possibly an XValue is actually correct in the case of move, but
2323 // there is no semantic difference for class types in this restricted
2324 // case.
2325 ExprValueKind VK;
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002326 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002327 VK = VK_LValue;
2328 else
2329 VK = VK_RValue;
2330
2331 NumArgs = 1;
2332 Arg = new (Context) OpaqueValueExpr(SourceLocation(), ArgType, VK);
2333 }
2334
2335 // Create the object argument
2336 QualType ThisTy = CanTy;
2337 if (ConstThis)
2338 ThisTy.addConst();
2339 if (VolatileThis)
2340 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002341 Expr::Classification Classification =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002342 (new (Context) OpaqueValueExpr(SourceLocation(), ThisTy,
2343 RValueThis ? VK_RValue : VK_LValue))->
2344 Classify(Context);
2345
2346 // Now we perform lookup on the name we computed earlier and do overload
2347 // resolution. Lookup is only performed directly into the class since there
2348 // will always be a (possibly implicit) declaration to shadow any others.
2349 OverloadCandidateSet OCS((SourceLocation()));
2350 DeclContext::lookup_iterator I, E;
2351 Result->setConstParamMatch(false);
2352
Alexis Hunt1da39282011-06-24 02:11:39 +00002353 llvm::tie(I, E) = RD->lookup(Name);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002354 assert((I != E) &&
2355 "lookup for a constructor or assignment operator was empty");
2356 for ( ; I != E; ++I) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002357 Decl *Cand = *I;
Alexis Hunt080709f2011-06-23 00:26:20 +00002358
Alexis Hunt1da39282011-06-24 02:11:39 +00002359 if (Cand->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002360 continue;
2361
Alexis Hunt1da39282011-06-24 02:11:39 +00002362 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2363 // FIXME: [namespace.udecl]p15 says that we should only consider a
2364 // using declaration here if it does not match a declaration in the
2365 // derived class. We do not implement this correctly in other cases
2366 // either.
2367 Cand = U->getTargetDecl();
2368
2369 if (Cand->isInvalidDecl())
2370 continue;
2371 }
2372
2373 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002374 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Alexis Hunt1da39282011-06-24 02:11:39 +00002375 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002376 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2377 OCS, true);
Alexis Hunt080709f2011-06-23 00:26:20 +00002378 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002379 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2380 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002381
2382 // Here we're looking for a const parameter to speed up creation of
2383 // implicit copy methods.
2384 if ((SM == CXXCopyAssignment && M->isCopyAssignmentOperator()) ||
2385 (SM == CXXCopyConstructor &&
2386 cast<CXXConstructorDecl>(M)->isCopyConstructor())) {
2387 QualType ArgType = M->getType()->getAs<FunctionProtoType>()->getArgType(0);
Alexis Hunt491ec602011-06-21 23:42:56 +00002388 if (!ArgType->isReferenceType() ||
2389 ArgType->getPointeeType().isConstQualified())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002390 Result->setConstParamMatch(true);
2391 }
Alexis Hunt2949f022011-06-22 02:58:46 +00002392 } else if (FunctionTemplateDecl *Tmpl =
Alexis Hunt1da39282011-06-24 02:11:39 +00002393 dyn_cast<FunctionTemplateDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002394 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2395 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002396 RD, 0, ThisTy, Classification,
2397 llvm::makeArrayRef(&Arg, NumArgs),
Alexis Hunt080709f2011-06-23 00:26:20 +00002398 OCS, true);
2399 else
2400 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002401 0, llvm::makeArrayRef(&Arg, NumArgs),
2402 OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002403 } else {
2404 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002405 }
2406 }
2407
2408 OverloadCandidateSet::iterator Best;
2409 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2410 case OR_Success:
2411 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2412 Result->setSuccess(true);
2413 break;
2414
2415 case OR_Deleted:
2416 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2417 Result->setSuccess(false);
2418 break;
2419
2420 case OR_Ambiguous:
2421 case OR_No_Viable_Function:
2422 Result->setMethod(0);
2423 Result->setSuccess(false);
2424 break;
2425 }
2426
2427 return Result;
2428}
2429
2430/// \brief Look up the default constructor for the given class.
2431CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002432 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002433 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2434 false, false);
2435
2436 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002437}
2438
Alexis Hunt491ec602011-06-21 23:42:56 +00002439/// \brief Look up the copying constructor for the given class.
2440CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
2441 unsigned Quals,
2442 bool *ConstParamMatch) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002443 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2444 "non-const, non-volatile qualifiers for copy ctor arg");
2445 SpecialMemberOverloadResult *Result =
2446 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2447 Quals & Qualifiers::Volatile, false, false, false);
2448
2449 if (ConstParamMatch)
2450 *ConstParamMatch = Result->hasConstParamMatch();
2451
2452 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2453}
2454
Sebastian Redl22653ba2011-08-30 19:58:05 +00002455/// \brief Look up the moving constructor for the given class.
2456CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class) {
2457 SpecialMemberOverloadResult *Result =
2458 LookupSpecialMember(Class, CXXMoveConstructor, false,
2459 false, false, false, false);
2460
2461 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2462}
2463
Douglas Gregor52b72822010-07-02 23:12:18 +00002464/// \brief Look up the constructors for the given class.
2465DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002466 // If the implicit constructors have not yet been declared, do so now.
Douglas Gregor9672f922010-07-03 00:47:00 +00002467 if (CanDeclareSpecialMemberFunction(Context, Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00002468 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002469 DeclareImplicitDefaultConstructor(Class);
2470 if (!Class->hasDeclaredCopyConstructor())
2471 DeclareImplicitCopyConstructor(Class);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002472 if (getLangOptions().CPlusPlus0x && Class->needsImplicitMoveConstructor())
2473 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00002474 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002475
Douglas Gregor52b72822010-07-02 23:12:18 +00002476 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2477 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2478 return Class->lookup(Name);
2479}
2480
Alexis Hunt491ec602011-06-21 23:42:56 +00002481/// \brief Look up the copying assignment operator for the given class.
2482CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2483 unsigned Quals, bool RValueThis,
2484 unsigned ThisQuals,
2485 bool *ConstParamMatch) {
2486 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2487 "non-const, non-volatile qualifiers for copy assignment arg");
2488 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2489 "non-const, non-volatile qualifiers for copy assignment this");
2490 SpecialMemberOverloadResult *Result =
2491 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2492 Quals & Qualifiers::Volatile, RValueThis,
2493 ThisQuals & Qualifiers::Const,
2494 ThisQuals & Qualifiers::Volatile);
2495
2496 if (ConstParamMatch)
2497 *ConstParamMatch = Result->hasConstParamMatch();
2498
2499 return Result->getMethod();
2500}
2501
Sebastian Redl22653ba2011-08-30 19:58:05 +00002502/// \brief Look up the moving assignment operator for the given class.
2503CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
2504 bool RValueThis,
2505 unsigned ThisQuals) {
2506 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2507 "non-const, non-volatile qualifiers for copy assignment this");
2508 SpecialMemberOverloadResult *Result =
2509 LookupSpecialMember(Class, CXXMoveAssignment, false, false, RValueThis,
2510 ThisQuals & Qualifiers::Const,
2511 ThisQuals & Qualifiers::Volatile);
2512
2513 return Result->getMethod();
2514}
2515
Douglas Gregore71edda2010-07-01 22:47:18 +00002516/// \brief Look for the destructor of the given class.
2517///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00002518/// During semantic analysis, this routine should be used in lieu of
2519/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00002520///
2521/// \returns The destructor for this class.
2522CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002523 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2524 false, false, false,
2525 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00002526}
2527
Richard Smithbcc22fc2012-03-09 08:00:36 +00002528/// LookupLiteralOperator - Determine which literal operator should be used for
2529/// a user-defined literal, per C++11 [lex.ext].
2530///
2531/// Normal overload resolution is not used to select which literal operator to
2532/// call for a user-defined literal. Look up the provided literal operator name,
2533/// and filter the results to the appropriate set for the given argument types.
2534Sema::LiteralOperatorLookupResult
2535Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2536 ArrayRef<QualType> ArgTys,
2537 bool AllowRawAndTemplate) {
2538 LookupName(R, S);
2539 assert(R.getResultKind() != LookupResult::Ambiguous &&
2540 "literal operator lookup can't be ambiguous");
2541
2542 // Filter the lookup results appropriately.
2543 LookupResult::Filter F = R.makeFilter();
2544
2545 bool FoundTemplate = false;
2546 bool FoundRaw = false;
2547 bool FoundExactMatch = false;
2548
2549 while (F.hasNext()) {
2550 Decl *D = F.next();
2551 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2552 D = USD->getTargetDecl();
2553
2554 bool IsTemplate = isa<FunctionTemplateDecl>(D);
2555 bool IsRaw = false;
2556 bool IsExactMatch = false;
2557
2558 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2559 if (FD->getNumParams() == 1 &&
2560 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2561 IsRaw = true;
2562 else {
2563 IsExactMatch = true;
2564 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2565 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2566 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2567 IsExactMatch = false;
2568 break;
2569 }
2570 }
2571 }
2572 }
2573
2574 if (IsExactMatch) {
2575 FoundExactMatch = true;
2576 AllowRawAndTemplate = false;
2577 if (FoundRaw || FoundTemplate) {
2578 // Go through again and remove the raw and template decls we've
2579 // already found.
2580 F.restart();
2581 FoundRaw = FoundTemplate = false;
2582 }
2583 } else if (AllowRawAndTemplate && (IsTemplate || IsRaw)) {
2584 FoundTemplate |= IsTemplate;
2585 FoundRaw |= IsRaw;
2586 } else {
2587 F.erase();
2588 }
2589 }
2590
2591 F.done();
2592
2593 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2594 // parameter type, that is used in preference to a raw literal operator
2595 // or literal operator template.
2596 if (FoundExactMatch)
2597 return LOLR_Cooked;
2598
2599 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2600 // operator template, but not both.
2601 if (FoundRaw && FoundTemplate) {
2602 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
2603 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2604 Decl *D = *I;
2605 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2606 D = USD->getTargetDecl();
2607 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2608 D = FunTmpl->getTemplatedDecl();
2609 NoteOverloadCandidate(cast<FunctionDecl>(D));
2610 }
2611 return LOLR_Error;
2612 }
2613
2614 if (FoundRaw)
2615 return LOLR_Raw;
2616
2617 if (FoundTemplate)
2618 return LOLR_Template;
2619
2620 // Didn't find anything we could use.
2621 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2622 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
2623 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRawAndTemplate;
2624 return LOLR_Error;
2625}
2626
John McCall8fe68082010-01-26 07:16:45 +00002627void ADLResult::insert(NamedDecl *New) {
2628 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2629
2630 // If we haven't yet seen a decl for this key, or the last decl
2631 // was exactly this one, we're done.
2632 if (Old == 0 || Old == New) {
2633 Old = New;
2634 return;
2635 }
2636
2637 // Otherwise, decide which is a more recent redeclaration.
2638 FunctionDecl *OldFD, *NewFD;
2639 if (isa<FunctionTemplateDecl>(New)) {
2640 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2641 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2642 } else {
2643 OldFD = cast<FunctionDecl>(Old);
2644 NewFD = cast<FunctionDecl>(New);
2645 }
2646
2647 FunctionDecl *Cursor = NewFD;
2648 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002649 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00002650
2651 // If we got to the end without finding OldFD, OldFD is the newer
2652 // declaration; leave things as they are.
2653 if (!Cursor) return;
2654
2655 // If we do find OldFD, then NewFD is newer.
2656 if (Cursor == OldFD) break;
2657
2658 // Otherwise, keep looking.
2659 }
2660
2661 Old = New;
2662}
2663
Sebastian Redlc057f422009-10-23 19:23:15 +00002664void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Richard Smithe06a2c12012-02-25 06:24:24 +00002665 SourceLocation Loc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002666 llvm::ArrayRef<Expr *> Args,
Richard Smith02e85f32011-04-14 22:09:26 +00002667 ADLResult &Result,
2668 bool StdNamespaceIsAssociated) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002669 // Find all of the associated namespaces and classes based on the
2670 // arguments we have.
2671 AssociatedNamespaceSet AssociatedNamespaces;
2672 AssociatedClassSet AssociatedClasses;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002673 FindAssociatedClassesAndNamespaces(Args,
John McCallc7e8e792009-08-07 22:18:02 +00002674 AssociatedNamespaces,
2675 AssociatedClasses);
Richard Smith02e85f32011-04-14 22:09:26 +00002676 if (StdNamespaceIsAssociated && StdNamespace)
2677 AssociatedNamespaces.insert(getStdNamespace());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002678
Sebastian Redlc057f422009-10-23 19:23:15 +00002679 QualType T1, T2;
2680 if (Operator) {
2681 T1 = Args[0]->getType();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002682 if (Args.size() >= 2)
Sebastian Redlc057f422009-10-23 19:23:15 +00002683 T2 = Args[1]->getType();
2684 }
2685
Richard Smithe06a2c12012-02-25 06:24:24 +00002686 // Try to complete all associated classes, in case they contain a
2687 // declaration of a friend function.
2688 for (AssociatedClassSet::iterator C = AssociatedClasses.begin(),
2689 CEnd = AssociatedClasses.end();
2690 C != CEnd; ++C)
2691 RequireCompleteType(Loc, Context.getRecordType(*C), 0);
2692
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002693 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002694 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2695 // and let Y be the lookup set produced by argument dependent
2696 // lookup (defined as follows). If X contains [...] then Y is
2697 // empty. Otherwise Y is the set of declarations found in the
2698 // namespaces associated with the argument types as described
2699 // below. The set of declarations found by the lookup of the name
2700 // is the union of X and Y.
2701 //
2702 // Here, we compute Y and add its members to the overloaded
2703 // candidate set.
2704 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00002705 NSEnd = AssociatedNamespaces.end();
2706 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002707 // When considering an associated namespace, the lookup is the
2708 // same as the lookup performed when the associated namespace is
2709 // used as a qualifier (3.4.3.2) except that:
2710 //
2711 // -- Any using-directives in the associated namespace are
2712 // ignored.
2713 //
John McCallc7e8e792009-08-07 22:18:02 +00002714 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002715 // associated classes are visible within their respective
2716 // namespaces even if they are not visible during an ordinary
2717 // lookup (11.4).
2718 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00002719 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00002720 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00002721 // If the only declaration here is an ordinary friend, consider
2722 // it only if it was declared in an associated classes.
2723 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00002724 DeclContext *LexDC = D->getLexicalDeclContext();
2725 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2726 continue;
2727 }
Mike Stump11289f42009-09-09 15:08:12 +00002728
John McCall91f61fc2010-01-26 06:04:06 +00002729 if (isa<UsingShadowDecl>(D))
2730 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002731
John McCall91f61fc2010-01-26 06:04:06 +00002732 if (isa<FunctionDecl>(D)) {
2733 if (Operator &&
2734 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2735 T1, T2, Context))
2736 continue;
John McCall8fe68082010-01-26 07:16:45 +00002737 } else if (!isa<FunctionTemplateDecl>(D))
2738 continue;
2739
2740 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002741 }
2742 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002743}
Douglas Gregor2d435302009-12-30 17:04:44 +00002744
2745//----------------------------------------------------------------------------
2746// Search for all visible declarations.
2747//----------------------------------------------------------------------------
2748VisibleDeclConsumer::~VisibleDeclConsumer() { }
2749
2750namespace {
2751
2752class ShadowContextRAII;
2753
2754class VisibleDeclsRecord {
2755public:
2756 /// \brief An entry in the shadow map, which is optimized to store a
2757 /// single declaration (the common case) but can also store a list
2758 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002759 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00002760
2761private:
2762 /// \brief A mapping from declaration names to the declarations that have
2763 /// this name within a particular scope.
2764 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2765
2766 /// \brief A list of shadow maps, which is used to model name hiding.
2767 std::list<ShadowMap> ShadowMaps;
2768
2769 /// \brief The declaration contexts we have already visited.
2770 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2771
2772 friend class ShadowContextRAII;
2773
2774public:
2775 /// \brief Determine whether we have already visited this context
2776 /// (and, if not, note that we are going to visit that context now).
2777 bool visitedContext(DeclContext *Ctx) {
2778 return !VisitedContexts.insert(Ctx);
2779 }
2780
Douglas Gregor39982192010-08-15 06:18:01 +00002781 bool alreadyVisitedContext(DeclContext *Ctx) {
2782 return VisitedContexts.count(Ctx);
2783 }
2784
Douglas Gregor2d435302009-12-30 17:04:44 +00002785 /// \brief Determine whether the given declaration is hidden in the
2786 /// current scope.
2787 ///
2788 /// \returns the declaration that hides the given declaration, or
2789 /// NULL if no such declaration exists.
2790 NamedDecl *checkHidden(NamedDecl *ND);
2791
2792 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002793 void add(NamedDecl *ND) {
2794 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2795 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002796};
2797
2798/// \brief RAII object that records when we've entered a shadow context.
2799class ShadowContextRAII {
2800 VisibleDeclsRecord &Visible;
2801
2802 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2803
2804public:
2805 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2806 Visible.ShadowMaps.push_back(ShadowMap());
2807 }
2808
2809 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00002810 Visible.ShadowMaps.pop_back();
2811 }
2812};
2813
2814} // end anonymous namespace
2815
Douglas Gregor2d435302009-12-30 17:04:44 +00002816NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002817 // Look through using declarations.
2818 ND = ND->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002819
Douglas Gregor2d435302009-12-30 17:04:44 +00002820 unsigned IDNS = ND->getIdentifierNamespace();
2821 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2822 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2823 SM != SMEnd; ++SM) {
2824 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2825 if (Pos == SM->end())
2826 continue;
2827
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002828 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor2d435302009-12-30 17:04:44 +00002829 IEnd = Pos->second.end();
2830 I != IEnd; ++I) {
2831 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +00002832 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002833 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00002834 Decl::IDNS_ObjCProtocol)))
2835 continue;
2836
2837 // Protocols are in distinct namespaces from everything else.
2838 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2839 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2840 (*I)->getIdentifierNamespace() != IDNS)
2841 continue;
2842
Douglas Gregor09bbc652010-01-14 15:47:35 +00002843 // Functions and function templates in the same scope overload
2844 // rather than hide. FIXME: Look for hiding based on function
2845 // signatures!
Douglas Gregor200c99d2010-01-14 03:35:48 +00002846 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002847 ND->isFunctionOrFunctionTemplate() &&
2848 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002849 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002850
Douglas Gregor2d435302009-12-30 17:04:44 +00002851 // We've found a declaration that hides this one.
2852 return *I;
2853 }
2854 }
2855
2856 return 0;
2857}
2858
2859static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2860 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002861 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002862 VisibleDeclConsumer &Consumer,
2863 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002864 if (!Ctx)
2865 return;
2866
Douglas Gregor2d435302009-12-30 17:04:44 +00002867 // Make sure we don't visit the same context twice.
2868 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2869 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002870
Douglas Gregor7454c562010-07-02 20:37:36 +00002871 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2872 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2873
Douglas Gregor2d435302009-12-30 17:04:44 +00002874 // Enumerate all of the results in this context.
Douglas Gregore57e7522012-01-07 09:11:48 +00002875 llvm::SmallVector<DeclContext *, 2> Contexts;
2876 Ctx->collectAllContexts(Contexts);
2877 for (unsigned I = 0, N = Contexts.size(); I != N; ++I) {
2878 DeclContext *CurCtx = Contexts[I];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002879 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
Douglas Gregor2d435302009-12-30 17:04:44 +00002880 DEnd = CurCtx->decls_end();
2881 D != DEnd; ++D) {
Douglas Gregora3b23b02010-12-09 21:44:02 +00002882 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00002883 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00002884 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002885 Visited.add(ND);
2886 }
Douglas Gregora3b23b02010-12-09 21:44:02 +00002887 }
Douglas Gregor04246572011-02-16 01:39:26 +00002888
Sebastian Redlbd595762010-08-31 20:53:31 +00002889 // Visit transparent contexts and inline namespaces inside this context.
Douglas Gregor2d435302009-12-30 17:04:44 +00002890 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
Sebastian Redlbd595762010-08-31 20:53:31 +00002891 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Douglas Gregor09bbc652010-01-14 15:47:35 +00002892 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002893 Consumer, Visited);
2894 }
2895 }
2896 }
2897
2898 // Traverse using directives for qualified name lookup.
2899 if (QualifiedNameLookup) {
2900 ShadowContextRAII Shadow(Visited);
2901 DeclContext::udir_iterator I, E;
2902 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002903 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002904 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002905 }
2906 }
2907
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002908 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00002909 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00002910 if (!Record->hasDefinition())
2911 return;
2912
Douglas Gregor2d435302009-12-30 17:04:44 +00002913 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2914 BEnd = Record->bases_end();
2915 B != BEnd; ++B) {
2916 QualType BaseType = B->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002917
Douglas Gregor2d435302009-12-30 17:04:44 +00002918 // Don't look into dependent bases, because name lookup can't look
2919 // there anyway.
2920 if (BaseType->isDependentType())
2921 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002922
Douglas Gregor2d435302009-12-30 17:04:44 +00002923 const RecordType *Record = BaseType->getAs<RecordType>();
2924 if (!Record)
2925 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002926
Douglas Gregor2d435302009-12-30 17:04:44 +00002927 // FIXME: It would be nice to be able to determine whether referencing
2928 // a particular member would be ambiguous. For example, given
2929 //
2930 // struct A { int member; };
2931 // struct B { int member; };
2932 // struct C : A, B { };
2933 //
2934 // void f(C *c) { c->### }
2935 //
2936 // accessing 'member' would result in an ambiguity. However, we
2937 // could be smart enough to qualify the member with the base
2938 // class, e.g.,
2939 //
2940 // c->B::member
2941 //
2942 // or
2943 //
2944 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002945
Douglas Gregor2d435302009-12-30 17:04:44 +00002946 // Find results in this base class (and its bases).
2947 ShadowContextRAII Shadow(Visited);
2948 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002949 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002950 }
2951 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002952
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002953 // Traverse the contexts of Objective-C classes.
2954 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2955 // Traverse categories.
2956 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2957 Category; Category = Category->getNextClassCategory()) {
2958 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002959 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002960 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002961 }
2962
2963 // Traverse protocols.
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002964 for (ObjCInterfaceDecl::all_protocol_iterator
2965 I = IFace->all_referenced_protocol_begin(),
2966 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002967 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002968 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002969 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002970 }
2971
2972 // Traverse the superclass.
2973 if (IFace->getSuperClass()) {
2974 ShadowContextRAII Shadow(Visited);
2975 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002976 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002977 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002978
Douglas Gregor0b59e802010-04-19 18:02:19 +00002979 // If there is an implementation, traverse it. We do this to find
2980 // synthesized ivars.
2981 if (IFace->getImplementation()) {
2982 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002983 LookupVisibleDecls(IFace->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00002984 QualifiedNameLookup, true, Consumer, Visited);
2985 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002986 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2987 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2988 E = Protocol->protocol_end(); I != E; ++I) {
2989 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002990 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002991 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002992 }
2993 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2994 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2995 E = Category->protocol_end(); I != E; ++I) {
2996 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002997 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002998 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002999 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003000
Douglas Gregor0b59e802010-04-19 18:02:19 +00003001 // If there is an implementation, traverse it.
3002 if (Category->getImplementation()) {
3003 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003004 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00003005 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003006 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003007 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003008}
3009
3010static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3011 UnqualUsingDirectiveSet &UDirs,
3012 VisibleDeclConsumer &Consumer,
3013 VisibleDeclsRecord &Visited) {
3014 if (!S)
3015 return;
3016
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003017 if (!S->getEntity() ||
3018 (!S->getParent() &&
Douglas Gregor39982192010-08-15 06:18:01 +00003019 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003020 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
3021 // Walk through the declarations in this Scope.
3022 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
3023 D != DEnd; ++D) {
John McCall48871652010-08-21 09:40:31 +00003024 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor4a814562011-12-14 16:03:29 +00003025 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003026 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003027 Visited.add(ND);
3028 }
3029 }
3030 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003031
Douglas Gregor66230062010-03-15 14:33:29 +00003032 // FIXME: C++ [temp.local]p8
Douglas Gregor2d435302009-12-30 17:04:44 +00003033 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00003034 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003035 // Look into this scope's declaration context, along with any of its
3036 // parent lookup contexts (e.g., enclosing classes), up to the point
3037 // where we hit the context stored in the next outer scope.
3038 Entity = (DeclContext *)S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00003039 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003040
Douglas Gregorea166062010-03-15 15:26:48 +00003041 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00003042 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003043 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3044 if (Method->isInstanceMethod()) {
3045 // For instance methods, look for ivars in the method's interface.
3046 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3047 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003048 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003049 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Fariborz Jahanian97d744b2011-08-31 22:24:06 +00003050 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003051 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003052 }
3053
3054 // We've already performed all of the name lookup that we need
3055 // to for Objective-C methods; the next context will be the
3056 // outer scope.
3057 break;
3058 }
3059
Douglas Gregor2d435302009-12-30 17:04:44 +00003060 if (Ctx->isFunctionOrMethod())
3061 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003062
3063 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003064 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003065 }
3066 } else if (!S->getParent()) {
3067 // Look into the translation unit scope. We walk through the translation
3068 // unit's declaration context, because the Scope itself won't have all of
3069 // the declarations if we loaded a precompiled header.
3070 // FIXME: We would like the translation unit's Scope object to point to the
3071 // translation unit, so we don't need this special "if" branch. However,
3072 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003073 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00003074 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003075 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00003076 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003077 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003078 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003079 }
3080
Douglas Gregor2d435302009-12-30 17:04:44 +00003081 if (Entity) {
3082 // Lookup visible declarations in any namespaces found by using
3083 // directives.
3084 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
3085 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
3086 for (; UI != UEnd; ++UI)
3087 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003088 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003089 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003090 }
3091
3092 // Lookup names in the parent scope.
3093 ShadowContextRAII Shadow(Visited);
3094 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3095}
3096
3097void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003098 VisibleDeclConsumer &Consumer,
3099 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003100 // Determine the set of using directives available during
3101 // unqualified name lookup.
3102 Scope *Initial = S;
3103 UnqualUsingDirectiveSet UDirs;
3104 if (getLangOptions().CPlusPlus) {
3105 // Find the first namespace or translation-unit scope.
3106 while (S && !isNamespaceOrTranslationUnitScope(S))
3107 S = S->getParent();
3108
3109 UDirs.visitScopeChain(Initial, S);
3110 }
3111 UDirs.done();
3112
3113 // Look for visible declarations.
3114 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3115 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003116 if (!IncludeGlobalScope)
3117 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003118 ShadowContextRAII Shadow(Visited);
3119 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3120}
3121
3122void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003123 VisibleDeclConsumer &Consumer,
3124 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003125 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3126 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003127 if (!IncludeGlobalScope)
3128 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003129 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003130 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003131 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003132}
3133
Chris Lattner43e7f312011-02-18 02:08:43 +00003134/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003135/// If GnuLabelLoc is a valid source location, then this is a definition
3136/// of an __label__ label name, otherwise it is a normal label definition
3137/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003138LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003139 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003140 // Do a lookup to see if we have a label with this name already.
Chris Lattner43e7f312011-02-18 02:08:43 +00003141 NamedDecl *Res = 0;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003142
3143 if (GnuLabelLoc.isValid()) {
3144 // Local label definitions always shadow existing labels.
3145 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3146 Scope *S = CurScope;
3147 PushOnScopeChains(Res, S, true);
3148 return cast<LabelDecl>(Res);
3149 }
3150
3151 // Not a GNU local label.
3152 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3153 // If we found a label, check to see if it is in the same context as us.
3154 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003155 if (Res && Res->getDeclContext() != CurContext)
3156 Res = 0;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003157 if (Res == 0) {
3158 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003159 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3160 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003161 assert(S && "Not in a function?");
3162 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003163 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003164 return cast<LabelDecl>(Res);
3165}
3166
3167//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003168// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003169//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003170
3171namespace {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003172
3173typedef llvm::StringMap<TypoCorrection, llvm::BumpPtrAllocator> TypoResultsMap;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003174typedef std::map<unsigned, TypoResultsMap *> TypoEditDistanceMap;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003175
3176static const unsigned MaxTypoDistanceResultSets = 5;
3177
Douglas Gregor2d435302009-12-30 17:04:44 +00003178class TypoCorrectionConsumer : public VisibleDeclConsumer {
3179 /// \brief The name written that is a typo in the source.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003180 StringRef Typo;
Douglas Gregor2d435302009-12-30 17:04:44 +00003181
3182 /// \brief The results found that have the smallest edit distance
3183 /// found (so far) with the typo name.
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003184 ///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003185 /// The pointer value being set to the current DeclContext indicates
3186 /// whether there is a keyword with this name.
3187 TypoEditDistanceMap BestResults;
Douglas Gregor2d435302009-12-30 17:04:44 +00003188
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003189 Sema &SemaRef;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003190
Douglas Gregor2d435302009-12-30 17:04:44 +00003191public:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003192 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003193 : Typo(Typo->getName()),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003194 SemaRef(SemaRef) { }
Douglas Gregor2d435302009-12-30 17:04:44 +00003195
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003196 ~TypoCorrectionConsumer() {
3197 for (TypoEditDistanceMap::iterator I = BestResults.begin(),
3198 IEnd = BestResults.end();
3199 I != IEnd;
3200 ++I)
3201 delete I->second;
3202 }
3203
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003204 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3205 bool InBaseClass);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003206 void FoundName(StringRef Name);
3207 void addKeywordResult(StringRef Keyword);
3208 void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003209 NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003210 void addCorrection(TypoCorrection Correction);
Douglas Gregor2d435302009-12-30 17:04:44 +00003211
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003212 typedef TypoResultsMap::iterator result_iterator;
3213 typedef TypoEditDistanceMap::iterator distance_iterator;
3214 distance_iterator begin() { return BestResults.begin(); }
3215 distance_iterator end() { return BestResults.end(); }
3216 void erase(distance_iterator I) { BestResults.erase(I); }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003217 unsigned size() const { return BestResults.size(); }
3218 bool empty() const { return BestResults.empty(); }
Douglas Gregor2d435302009-12-30 17:04:44 +00003219
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003220 TypoCorrection &operator[](StringRef Name) {
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003221 return (*BestResults.begin()->second)[Name];
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003222 }
3223
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003224 unsigned getBestEditDistance(bool Normalized) {
3225 if (BestResults.empty())
3226 return (std::numeric_limits<unsigned>::max)();
3227
3228 unsigned BestED = BestResults.begin()->first;
3229 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003230 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003231};
3232
3233}
3234
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003235void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003236 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003237 // Don't consider hidden names for typo correction.
3238 if (Hiding)
3239 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003240
Douglas Gregor2d435302009-12-30 17:04:44 +00003241 // Only consider entities with identifiers for names, ignoring
3242 // special names (constructors, overloaded operators, selectors,
3243 // etc.).
3244 IdentifierInfo *Name = ND->getIdentifier();
3245 if (!Name)
3246 return;
3247
Douglas Gregor57756ea2010-10-14 22:11:03 +00003248 FoundName(Name->getName());
3249}
3250
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003251void TypoCorrectionConsumer::FoundName(StringRef Name) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003252 // Use a simple length-based heuristic to determine the minimum possible
3253 // edit distance. If the minimum isn't good enough, bail out early.
3254 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003255 if (MinED && Typo.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00003256 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003257
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003258 // Compute an upper bound on the allowable edit distance, so that the
3259 // edit-distance algorithm can short-circuit.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003260 unsigned UpperBound = (Typo.size() + 2) / 3;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003261
Douglas Gregor2d435302009-12-30 17:04:44 +00003262 // Compute the edit distance between the typo and the name of this
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003263 // entity, and add the identifier to the list of results.
3264 addName(Name, NULL, Typo.edit_distance(Name, true, UpperBound));
Douglas Gregor2d435302009-12-30 17:04:44 +00003265}
3266
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003267void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003268 // Compute the edit distance between the typo and this keyword,
3269 // and add the keyword to the list of results.
3270 addName(Keyword, NULL, Typo.edit_distance(Keyword), NULL, true);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003271}
3272
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003273void TypoCorrectionConsumer::addName(StringRef Name,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003274 NamedDecl *ND,
3275 unsigned Distance,
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003276 NestedNameSpecifier *NNS,
3277 bool isKeyword) {
3278 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
3279 if (isKeyword) TC.makeKeyword();
3280 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003281}
3282
3283void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003284 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003285 TypoResultsMap *& Map = BestResults[Correction.getEditDistance(false)];
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003286 if (!Map)
3287 Map = new TypoResultsMap;
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003288
3289 TypoCorrection &CurrentCorrection = (*Map)[Name];
3290 if (!CurrentCorrection ||
3291 // FIXME: The following should be rolled up into an operator< on
3292 // TypoCorrection with a more principled definition.
3293 CurrentCorrection.isKeyword() < Correction.isKeyword() ||
3294 Correction.getAsString(SemaRef.getLangOptions()) <
3295 CurrentCorrection.getAsString(SemaRef.getLangOptions()))
3296 CurrentCorrection = Correction;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003297
3298 while (BestResults.size() > MaxTypoDistanceResultSets) {
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003299 TypoEditDistanceMap::iterator Last = BestResults.end();
3300 --Last;
3301 delete Last->second;
3302 BestResults.erase(Last);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003303 }
3304}
3305
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003306// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3307// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3308// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3309static void getNestedNameSpecifierIdentifiers(
3310 NestedNameSpecifier *NNS,
3311 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3312 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3313 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3314 else
3315 Identifiers.clear();
3316
3317 const IdentifierInfo *II = NULL;
3318
3319 switch (NNS->getKind()) {
3320 case NestedNameSpecifier::Identifier:
3321 II = NNS->getAsIdentifier();
3322 break;
3323
3324 case NestedNameSpecifier::Namespace:
3325 if (NNS->getAsNamespace()->isAnonymousNamespace())
3326 return;
3327 II = NNS->getAsNamespace()->getIdentifier();
3328 break;
3329
3330 case NestedNameSpecifier::NamespaceAlias:
3331 II = NNS->getAsNamespaceAlias()->getIdentifier();
3332 break;
3333
3334 case NestedNameSpecifier::TypeSpecWithTemplate:
3335 case NestedNameSpecifier::TypeSpec:
3336 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3337 break;
3338
3339 case NestedNameSpecifier::Global:
3340 return;
3341 }
3342
3343 if (II)
3344 Identifiers.push_back(II);
3345}
3346
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003347namespace {
3348
3349class SpecifierInfo {
3350 public:
3351 DeclContext* DeclCtx;
3352 NestedNameSpecifier* NameSpecifier;
3353 unsigned EditDistance;
3354
3355 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3356 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3357};
3358
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003359typedef SmallVector<DeclContext*, 4> DeclContextList;
3360typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003361
3362class NamespaceSpecifierSet {
3363 ASTContext &Context;
3364 DeclContextList CurContextChain;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003365 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3366 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003367 bool isSorted;
3368
3369 SpecifierInfoList Specifiers;
3370 llvm::SmallSetVector<unsigned, 4> Distances;
3371 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3372
3373 /// \brief Helper for building the list of DeclContexts between the current
3374 /// context and the top of the translation unit
3375 static DeclContextList BuildContextChain(DeclContext *Start);
3376
3377 void SortNamespaces();
3378
3379 public:
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003380 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3381 CXXScopeSpec *CurScopeSpec)
Benjamin Kramerde1d6232011-07-05 09:46:31 +00003382 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003383 isSorted(true) {
3384 if (CurScopeSpec && CurScopeSpec->getScopeRep())
3385 getNestedNameSpecifierIdentifiers(CurScopeSpec->getScopeRep(),
3386 CurNameSpecifierIdentifiers);
3387 // Build the list of identifiers that would be used for an absolute
3388 // (from the global context) NestedNameSpecifier refering to the current
3389 // context.
3390 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3391 CEnd = CurContextChain.rend();
3392 C != CEnd; ++C) {
3393 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3394 CurContextIdentifiers.push_back(ND->getIdentifier());
3395 }
3396 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003397
3398 /// \brief Add the namespace to the set, computing the corresponding
3399 /// NestedNameSpecifier and its distance in the process.
3400 void AddNamespace(NamespaceDecl *ND);
3401
3402 typedef SpecifierInfoList::iterator iterator;
3403 iterator begin() {
3404 if (!isSorted) SortNamespaces();
3405 return Specifiers.begin();
3406 }
3407 iterator end() { return Specifiers.end(); }
3408};
3409
3410}
3411
3412DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003413 assert(Start && "Bulding a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003414 DeclContextList Chain;
3415 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3416 DC = DC->getLookupParent()) {
3417 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3418 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3419 !(ND && ND->isAnonymousNamespace()))
3420 Chain.push_back(DC->getPrimaryContext());
3421 }
3422 return Chain;
3423}
3424
3425void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003426 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003427 sortedDistances.append(Distances.begin(), Distances.end());
3428
3429 if (sortedDistances.size() > 1)
3430 std::sort(sortedDistances.begin(), sortedDistances.end());
3431
3432 Specifiers.clear();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003433 for (SmallVector<unsigned, 4>::iterator DI = sortedDistances.begin(),
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003434 DIEnd = sortedDistances.end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003435 DI != DIEnd; ++DI) {
3436 SpecifierInfoList &SpecList = DistanceMap[*DI];
3437 Specifiers.append(SpecList.begin(), SpecList.end());
3438 }
3439
3440 isSorted = true;
3441}
3442
3443void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003444 DeclContext *Ctx = cast<DeclContext>(ND);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003445 NestedNameSpecifier *NNS = NULL;
3446 unsigned NumSpecifiers = 0;
3447 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003448 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003449
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003450 // Eliminate common elements from the two DeclContext chains.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003451 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3452 CEnd = CurContextChain.rend();
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003453 C != CEnd && !NamespaceDeclChain.empty() &&
3454 NamespaceDeclChain.back() == *C; ++C) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003455 NamespaceDeclChain.pop_back();
3456 }
3457
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003458 // Add an explicit leading '::' specifier if needed.
3459 if (NamespaceDecl *ND =
Kaelyn Uhrain618f97c2012-02-15 22:59:03 +00003460 NamespaceDeclChain.empty() ? NULL :
3461 dyn_cast_or_null<NamespaceDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003462 IdentifierInfo *Name = ND->getIdentifier();
3463 if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3464 Name) != CurContextIdentifiers.end() ||
3465 std::find(CurNameSpecifierIdentifiers.begin(),
3466 CurNameSpecifierIdentifiers.end(),
3467 Name) != CurNameSpecifierIdentifiers.end()) {
3468 NamespaceDeclChain = FullNamespaceDeclChain;
3469 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3470 }
3471 }
3472
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003473 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3474 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3475 CEnd = NamespaceDeclChain.rend();
3476 C != CEnd; ++C) {
3477 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3478 if (ND) {
3479 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3480 ++NumSpecifiers;
3481 }
3482 }
3483
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003484 // If the built NestedNameSpecifier would be replacing an existing
3485 // NestedNameSpecifier, use the number of component identifiers that
3486 // would need to be changed as the edit distance instead of the number
3487 // of components in the built NestedNameSpecifier.
3488 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3489 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3490 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3491 NumSpecifiers = llvm::ComputeEditDistance(
3492 llvm::ArrayRef<const IdentifierInfo*>(CurNameSpecifierIdentifiers),
3493 llvm::ArrayRef<const IdentifierInfo*>(NewNameSpecifierIdentifiers));
3494 }
3495
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003496 isSorted = false;
3497 Distances.insert(NumSpecifiers);
3498 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003499}
3500
Douglas Gregord507d772010-10-20 03:06:34 +00003501/// \brief Perform name lookup for a possible result for typo correction.
3502static void LookupPotentialTypoResult(Sema &SemaRef,
3503 LookupResult &Res,
3504 IdentifierInfo *Name,
3505 Scope *S, CXXScopeSpec *SS,
3506 DeclContext *MemberContext,
3507 bool EnteringContext,
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003508 bool isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00003509 Res.suppressDiagnostics();
3510 Res.clear();
3511 Res.setLookupName(Name);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003512 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00003513 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003514 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00003515 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3516 Res.addDecl(Ivar);
3517 Res.resolveKind();
3518 return;
3519 }
3520 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003521
Douglas Gregord507d772010-10-20 03:06:34 +00003522 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3523 Res.addDecl(Prop);
3524 Res.resolveKind();
3525 return;
3526 }
3527 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003528
Douglas Gregord507d772010-10-20 03:06:34 +00003529 SemaRef.LookupQualifiedName(Res, MemberContext);
3530 return;
3531 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003532
3533 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00003534 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003535
Douglas Gregord507d772010-10-20 03:06:34 +00003536 // Fake ivar lookup; this should really be part of
3537 // LookupParsedName.
3538 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3539 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003540 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00003541 (Res.isSingleResult() &&
3542 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003543 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00003544 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3545 Res.addDecl(IV);
3546 Res.resolveKind();
3547 }
3548 }
3549 }
3550}
3551
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003552/// \brief Add keywords to the consumer as possible typo corrections.
3553static void AddKeywordsToConsumer(Sema &SemaRef,
3554 TypoCorrectionConsumer &Consumer,
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003555 Scope *S, CorrectionCandidateCallback &CCC) {
3556 if (CCC.WantObjCSuper)
3557 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003558
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003559 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003560 // Add type-specifier keywords to the set of results.
3561 const char *CTypeSpecs[] = {
3562 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00003563 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003564 "_Complex", "_Imaginary",
3565 // storage-specifiers as well
3566 "extern", "inline", "static", "typedef"
3567 };
3568
3569 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3570 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3571 Consumer.addKeywordResult(CTypeSpecs[I]);
3572
3573 if (SemaRef.getLangOptions().C99)
3574 Consumer.addKeywordResult("restrict");
3575 if (SemaRef.getLangOptions().Bool || SemaRef.getLangOptions().CPlusPlus)
3576 Consumer.addKeywordResult("bool");
Douglas Gregor3b22a882011-07-01 21:27:45 +00003577 else if (SemaRef.getLangOptions().C99)
3578 Consumer.addKeywordResult("_Bool");
3579
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003580 if (SemaRef.getLangOptions().CPlusPlus) {
3581 Consumer.addKeywordResult("class");
3582 Consumer.addKeywordResult("typename");
3583 Consumer.addKeywordResult("wchar_t");
3584
3585 if (SemaRef.getLangOptions().CPlusPlus0x) {
3586 Consumer.addKeywordResult("char16_t");
3587 Consumer.addKeywordResult("char32_t");
3588 Consumer.addKeywordResult("constexpr");
3589 Consumer.addKeywordResult("decltype");
3590 Consumer.addKeywordResult("thread_local");
3591 }
3592 }
3593
3594 if (SemaRef.getLangOptions().GNUMode)
3595 Consumer.addKeywordResult("typeof");
3596 }
3597
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003598 if (CCC.WantCXXNamedCasts && SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003599 Consumer.addKeywordResult("const_cast");
3600 Consumer.addKeywordResult("dynamic_cast");
3601 Consumer.addKeywordResult("reinterpret_cast");
3602 Consumer.addKeywordResult("static_cast");
3603 }
3604
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003605 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003606 Consumer.addKeywordResult("sizeof");
3607 if (SemaRef.getLangOptions().Bool || SemaRef.getLangOptions().CPlusPlus) {
3608 Consumer.addKeywordResult("false");
3609 Consumer.addKeywordResult("true");
3610 }
3611
3612 if (SemaRef.getLangOptions().CPlusPlus) {
3613 const char *CXXExprs[] = {
3614 "delete", "new", "operator", "throw", "typeid"
3615 };
3616 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3617 for (unsigned I = 0; I != NumCXXExprs; ++I)
3618 Consumer.addKeywordResult(CXXExprs[I]);
3619
3620 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3621 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3622 Consumer.addKeywordResult("this");
3623
3624 if (SemaRef.getLangOptions().CPlusPlus0x) {
3625 Consumer.addKeywordResult("alignof");
3626 Consumer.addKeywordResult("nullptr");
3627 }
3628 }
3629 }
3630
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003631 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003632 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3633 // Statements.
3634 const char *CStmts[] = {
3635 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3636 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3637 for (unsigned I = 0; I != NumCStmts; ++I)
3638 Consumer.addKeywordResult(CStmts[I]);
3639
3640 if (SemaRef.getLangOptions().CPlusPlus) {
3641 Consumer.addKeywordResult("catch");
3642 Consumer.addKeywordResult("try");
3643 }
3644
3645 if (S && S->getBreakParent())
3646 Consumer.addKeywordResult("break");
3647
3648 if (S && S->getContinueParent())
3649 Consumer.addKeywordResult("continue");
3650
3651 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3652 Consumer.addKeywordResult("case");
3653 Consumer.addKeywordResult("default");
3654 }
3655 } else {
3656 if (SemaRef.getLangOptions().CPlusPlus) {
3657 Consumer.addKeywordResult("namespace");
3658 Consumer.addKeywordResult("template");
3659 }
3660
3661 if (S && S->isClassScope()) {
3662 Consumer.addKeywordResult("explicit");
3663 Consumer.addKeywordResult("friend");
3664 Consumer.addKeywordResult("mutable");
3665 Consumer.addKeywordResult("private");
3666 Consumer.addKeywordResult("protected");
3667 Consumer.addKeywordResult("public");
3668 Consumer.addKeywordResult("virtual");
3669 }
3670 }
3671
3672 if (SemaRef.getLangOptions().CPlusPlus) {
3673 Consumer.addKeywordResult("using");
3674
3675 if (SemaRef.getLangOptions().CPlusPlus0x)
3676 Consumer.addKeywordResult("static_assert");
3677 }
3678 }
3679}
3680
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003681static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3682 TypoCorrection &Candidate) {
3683 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3684 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3685}
3686
Douglas Gregor2d435302009-12-30 17:04:44 +00003687/// \brief Try to "correct" a typo in the source code by finding
3688/// visible declarations whose names are similar to the name that was
3689/// present in the source code.
3690///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003691/// \param TypoName the \c DeclarationNameInfo structure that contains
3692/// the name that was present in the source code along with its location.
3693///
3694/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00003695///
3696/// \param S the scope in which name lookup occurs.
3697///
3698/// \param SS the nested-name-specifier that precedes the name we're
3699/// looking for, if present.
3700///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003701/// \param CCC A CorrectionCandidateCallback object that provides further
3702/// validation of typo correction candidates. It also provides flags for
3703/// determining the set of keywords permitted.
3704///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003705/// \param MemberContext if non-NULL, the context in which to look for
3706/// a member access expression.
3707///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003708/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00003709/// the nested-name-specifier SS.
3710///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003711/// \param OPT when non-NULL, the search for visible declarations will
3712/// also walk the protocols in the qualified interfaces of \p OPT.
3713///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003714/// \returns a \c TypoCorrection containing the corrected name if the typo
3715/// along with information such as the \c NamedDecl where the corrected name
3716/// was declared, and any additional \c NestedNameSpecifier needed to access
3717/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3718TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3719 Sema::LookupNameKind LookupKind,
3720 Scope *S, CXXScopeSpec *SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00003721 CorrectionCandidateCallback &CCC,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003722 DeclContext *MemberContext,
3723 bool EnteringContext,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003724 const ObjCObjectPointerType *OPT) {
Douglas Gregor8ed0c0b2010-07-09 17:35:33 +00003725 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003726 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003727
Francois Pichet9c391132011-12-03 15:55:29 +00003728 // In Microsoft mode, don't perform typo correction in a template member
3729 // function dependent context because it interferes with the "lookup into
3730 // dependent bases of class templates" feature.
3731 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
3732 isa<CXXMethodDecl>(CurContext))
3733 return TypoCorrection();
3734
Douglas Gregor2d435302009-12-30 17:04:44 +00003735 // We only attempt to correct typos for identifiers.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003736 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor2d435302009-12-30 17:04:44 +00003737 if (!Typo)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003738 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00003739
3740 // If the scope specifier itself was invalid, don't try to correct
3741 // typos.
3742 if (SS && SS->isInvalid())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003743 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00003744
3745 // Never try to correct typos during template deduction or
3746 // instantiation.
3747 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003748 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003749
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003750 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003751
3752 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003753
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003754 // If a callback object considers an empty typo correction candidate to be
3755 // viable, assume it does not do any actual validation of the candidates.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003756 TypoCorrection EmptyCorrection;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003757 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003758
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003759 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor87074f12010-10-20 01:32:02 +00003760 bool IsUnqualifiedLookup = false;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003761 DeclContext *QualifiedDC = MemberContext;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003762 if (MemberContext) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003763 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003764
3765 // Look in qualified interfaces.
3766 if (OPT) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003767 for (ObjCObjectPointerType::qual_iterator
3768 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003769 I != E; ++I)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003770 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003771 }
3772 } else if (SS && SS->isSet()) {
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003773 QualifiedDC = computeDeclContext(*SS, EnteringContext);
3774 if (!QualifiedDC)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003775 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003776
Douglas Gregor87074f12010-10-20 01:32:02 +00003777 // Provide a stop gap for files that are just seriously broken. Trying
3778 // to correct all typos can turn into a HUGE performance penalty, causing
3779 // some files to take minutes to get rejected by the parser.
3780 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003781 return TypoCorrection();
Douglas Gregor87074f12010-10-20 01:32:02 +00003782 ++TyposCorrected;
3783
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003784 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
Douglas Gregor2d435302009-12-30 17:04:44 +00003785 } else {
Douglas Gregor87074f12010-10-20 01:32:02 +00003786 IsUnqualifiedLookup = true;
3787 UnqualifiedTyposCorrectedMap::iterator Cached
3788 = UnqualifiedTyposCorrected.find(Typo);
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003789 if (Cached != UnqualifiedTyposCorrected.end()) {
3790 // Add the cached value, unless it's a keyword or fails validation. In the
3791 // keyword case, we'll end up adding the keyword below.
3792 if (Cached->second) {
3793 if (!Cached->second.isKeyword() &&
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003794 isCandidateViable(CCC, Cached->second))
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003795 Consumer.addCorrection(Cached->second);
3796 } else {
3797 // Only honor no-correction cache hits when a callback that will validate
3798 // correction candidates is not being used.
3799 if (!ValidatingCallback)
3800 return TypoCorrection();
3801 }
3802 }
3803 if (Cached == UnqualifiedTyposCorrected.end()) {
Douglas Gregor87074f12010-10-20 01:32:02 +00003804 // Provide a stop gap for files that are just seriously broken. Trying
3805 // to correct all typos can turn into a HUGE performance penalty, causing
3806 // some files to take minutes to get rejected by the parser.
3807 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003808 return TypoCorrection();
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003809 }
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003810 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003811
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003812 if (IsUnqualifiedLookup || (QualifiedDC && QualifiedDC->isNamespace())) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003813 // For unqualified lookup, look through all of the names that we have
3814 // seen in this translation unit.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003815 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003816 for (IdentifierTable::iterator I = Context.Idents.begin(),
3817 IEnd = Context.Idents.end();
3818 I != IEnd; ++I)
3819 Consumer.FoundName(I->getKey());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003820
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003821 // Walk through identifiers in external identifier sources.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003822 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003823 if (IdentifierInfoLookup *External
3824 = Context.Idents.getExternalIdentifierLookup()) {
Dylan Noblesmithe2778992012-02-05 02:12:40 +00003825 OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003826 do {
3827 StringRef Name = Iter->Next();
3828 if (Name.empty())
3829 break;
Douglas Gregor57756ea2010-10-14 22:11:03 +00003830
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003831 Consumer.FoundName(Name);
3832 } while (true);
Douglas Gregor57756ea2010-10-14 22:11:03 +00003833 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003834 }
3835
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00003836 AddKeywordsToConsumer(*this, Consumer, S, CCC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003837
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003838 // If we haven't found anything, we're done.
Douglas Gregor87074f12010-10-20 01:32:02 +00003839 if (Consumer.empty()) {
3840 // If this was an unqualified lookup, note that no correction was found.
3841 if (IsUnqualifiedLookup)
3842 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003843
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003844 return TypoCorrection();
Douglas Gregor87074f12010-10-20 01:32:02 +00003845 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003846
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003847 // Make sure that the user typed at least 3 characters for each correction
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003848 // made. Otherwise, we don't even both looking at the results.
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003849 unsigned ED = Consumer.getBestEditDistance(true);
Douglas Gregor87074f12010-10-20 01:32:02 +00003850 if (ED > 0 && Typo->getName().size() / ED < 3) {
3851 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregoraf1daa92010-10-27 14:20:34 +00003852 if (IsUnqualifiedLookup)
Douglas Gregor87074f12010-10-20 01:32:02 +00003853 (void)UnqualifiedTyposCorrected[Typo];
3854
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003855 return TypoCorrection();
3856 }
3857
3858 // Build the NestedNameSpecifiers for the KnownNamespaces
3859 if (getLangOptions().CPlusPlus) {
3860 // Load any externally-known namespaces.
3861 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003862 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003863 LoadedExternalKnownNamespaces = true;
3864 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
3865 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
3866 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
3867 }
3868
3869 for (llvm::DenseMap<NamespaceDecl*, bool>::iterator
3870 KNI = KnownNamespaces.begin(),
3871 KNIEnd = KnownNamespaces.end();
3872 KNI != KNIEnd; ++KNI)
3873 Namespaces.AddNamespace(KNI->first);
Douglas Gregor87074f12010-10-20 01:32:02 +00003874 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003875
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003876 // Weed out any names that could not be found by name lookup or, if a
3877 // CorrectionCandidateCallback object was provided, failed validation.
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003878 llvm::SmallVector<TypoCorrection, 16> QualifiedResults;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003879 LookupResult TmpRes(*this, TypoName, LookupKind);
3880 TmpRes.suppressDiagnostics();
3881 while (!Consumer.empty()) {
3882 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3883 unsigned ED = DI->first;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003884 for (TypoCorrectionConsumer::result_iterator I = DI->second->begin(),
3885 IEnd = DI->second->end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003886 I != IEnd; /* Increment in loop. */) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003887 // If the item already has been looked up or is a keyword, keep it.
3888 // If a validator callback object was given, drop the correction
3889 // unless it passes validation.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003890 if (I->second.isResolved()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003891 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003892 ++I;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003893 if (!isCandidateViable(CCC, Prev->second))
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003894 DI->second->erase(Prev);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003895 continue;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003896 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003897
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003898 // Perform name lookup on this name.
3899 IdentifierInfo *Name = I->second.getCorrectionAsIdentifierInfo();
3900 LookupPotentialTypoResult(*this, TmpRes, Name, S, SS, MemberContext,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00003901 EnteringContext, CCC.IsObjCIvarLookup);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003902
3903 switch (TmpRes.getResultKind()) {
3904 case LookupResult::NotFound:
3905 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain5a43b462011-09-07 20:25:59 +00003906 case LookupResult::FoundUnresolvedValue:
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003907 QualifiedResults.push_back(I->second);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003908 // We didn't find this name in our scope, or didn't like what we found;
3909 // ignore it.
3910 {
3911 TypoCorrectionConsumer::result_iterator Next = I;
3912 ++Next;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003913 DI->second->erase(I);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003914 I = Next;
3915 }
3916 break;
3917
3918 case LookupResult::Ambiguous:
3919 // We don't deal with ambiguities.
3920 return TypoCorrection();
3921
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003922 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003923 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003924 // Store all of the Decls for overloaded symbols
3925 for (LookupResult::iterator TRD = TmpRes.begin(),
3926 TRDEnd = TmpRes.end();
3927 TRD != TRDEnd; ++TRD)
3928 I->second.addCorrectionDecl(*TRD);
3929 ++I;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003930 if (!isCandidateViable(CCC, Prev->second))
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003931 DI->second->erase(Prev);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003932 break;
3933 }
3934
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003935 case LookupResult::Found: {
3936 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003937 I->second.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
3938 ++I;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003939 if (!isCandidateViable(CCC, Prev->second))
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003940 DI->second->erase(Prev);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003941 break;
3942 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003943
3944 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003945 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003946
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003947 if (DI->second->empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003948 Consumer.erase(DI);
3949 else if (!getLangOptions().CPlusPlus || QualifiedResults.empty() || !ED)
3950 // If there are results in the closest possible bucket, stop
3951 break;
3952
3953 // Only perform the qualified lookups for C++
3954 if (getLangOptions().CPlusPlus) {
3955 TmpRes.suppressDiagnostics();
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003956 for (llvm::SmallVector<TypoCorrection,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003957 16>::iterator QRI = QualifiedResults.begin(),
3958 QRIEnd = QualifiedResults.end();
3959 QRI != QRIEnd; ++QRI) {
3960 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
3961 NIEnd = Namespaces.end();
3962 NI != NIEnd; ++NI) {
3963 DeclContext *Ctx = NI->DeclCtx;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003964
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003965 // FIXME: Stop searching once the namespaces are too far away to create
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003966 // acceptable corrections for this identifier (since the namespaces
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003967 // are sorted in ascending order by edit distance).
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003968
3969 TmpRes.clear();
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003970 TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003971 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
3972
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003973 // Any corrections added below will be validated in subsequent
3974 // iterations of the main while() loop over the Consumer's contents.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003975 switch (TmpRes.getResultKind()) {
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003976 case LookupResult::Found: {
3977 TypoCorrection TC(*QRI);
3978 TC.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
3979 TC.setCorrectionSpecifier(NI->NameSpecifier);
3980 TC.setQualifierDistance(NI->EditDistance);
3981 Consumer.addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003982 break;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003983 }
3984 case LookupResult::FoundOverloaded: {
3985 TypoCorrection TC(*QRI);
3986 TC.setCorrectionSpecifier(NI->NameSpecifier);
3987 TC.setQualifierDistance(NI->EditDistance);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003988 for (LookupResult::iterator TRD = TmpRes.begin(),
3989 TRDEnd = TmpRes.end();
3990 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003991 TC.addCorrectionDecl(*TRD);
3992 Consumer.addCorrection(TC);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003993 break;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003994 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003995 case LookupResult::NotFound:
3996 case LookupResult::NotFoundInCurrentInstantiation:
3997 case LookupResult::Ambiguous:
Kaelyn Uhrain5a43b462011-09-07 20:25:59 +00003998 case LookupResult::FoundUnresolvedValue:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003999 break;
4000 }
4001 }
4002 }
4003 }
4004
4005 QualifiedResults.clear();
4006 }
4007
4008 // No corrections remain...
4009 if (Consumer.empty()) return TypoCorrection();
4010
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00004011 TypoResultsMap &BestResults = *Consumer.begin()->second;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00004012 ED = TypoCorrection::NormalizeEditDistance(Consumer.begin()->first);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004013
4014 if (ED > 0 && Typo->getName().size() / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004015 // If this was an unqualified lookup and we believe the callback
4016 // object wouldn't have filtered out possible corrections, note
4017 // that no correction was found.
4018 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004019 (void)UnqualifiedTyposCorrected[Typo];
4020
4021 return TypoCorrection();
4022 }
4023
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004024 // If only a single name remains, return that result.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004025 if (BestResults.size() == 1) {
4026 const llvm::StringMapEntry<TypoCorrection> &Correction = *(BestResults.begin());
4027 const TypoCorrection &Result = Correction.second;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004028
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00004029 // Don't correct to a keyword that's the same as the typo; the keyword
4030 // wasn't actually in scope.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004031 if (ED == 0 && Result.isKeyword()) return TypoCorrection();
4032
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004033 // Record the correction for unqualified lookup.
4034 if (IsUnqualifiedLookup)
4035 UnqualifiedTyposCorrected[Typo] = Result;
4036
4037 return Result;
4038 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004039 else if (BestResults.size() > 1
4040 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4041 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4042 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4043 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00004044 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004045 && BestResults["super"].isKeyword()) {
4046 // Prefer 'super' when we're completing in a message-receiver
4047 // context.
4048
4049 // Don't correct to a keyword that's the same as the typo; the keyword
4050 // wasn't actually in scope.
4051 if (ED == 0) return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004052
Douglas Gregor87074f12010-10-20 01:32:02 +00004053 // Record the correction for unqualified lookup.
4054 if (IsUnqualifiedLookup)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004055 UnqualifiedTyposCorrected[Typo] = BestResults["super"];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004056
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004057 return BestResults["super"];
Douglas Gregoraf9eb592010-10-15 13:35:25 +00004058 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004059
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004060 // If this was an unqualified lookup and we believe the callback object did
4061 // not filter out possible corrections, note that no correction was found.
4062 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregor87074f12010-10-20 01:32:02 +00004063 (void)UnqualifiedTyposCorrected[Typo];
4064
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004065 return TypoCorrection();
4066}
4067
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004068void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4069 if (!CDecl) return;
4070
4071 if (isKeyword())
4072 CorrectionDecls.clear();
4073
4074 CorrectionDecls.push_back(CDecl);
4075
4076 if (!CorrectionName)
4077 CorrectionName = CDecl->getDeclName();
4078}
4079
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004080std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4081 if (CorrectionNameSpec) {
4082 std::string tmpBuffer;
4083 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4084 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
4085 return PrefixOStream.str() + CorrectionName.getAsString();
4086 }
4087
4088 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00004089}