blob: fbb0dc6b0f9009f9af65d099b54d0dceed943913 [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()) {
Richard Smith05afe5e2012-03-13 03:12:56 +0000109 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
110 if (Ctx && !Ctx->isFunctionOrMethod()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000111 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
112 visit(Ctx, EffectiveDC);
113 } else {
114 Scope::udir_iterator I = S->using_directives_begin(),
115 End = S->using_directives_end();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000116
John McCallf6c8a4e2009-11-10 07:01:13 +0000117 for (; I != End; ++I)
John McCall48871652010-08-21 09:40:31 +0000118 visit(*I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000119 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000120 }
121 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000122
123 // Visits a context and collect all of its using directives
124 // recursively. Treats all using directives as if they were
125 // declared in the context.
126 //
127 // A given context is only every visited once, so it is important
128 // that contexts be visited from the inside out in order to get
129 // the effective DCs right.
130 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
131 if (!visited.insert(DC))
132 return;
133
134 addUsingDirectives(DC, EffectiveDC);
135 }
136
137 // Visits a using directive and collects all of its using
138 // directives recursively. Treats all using directives as if they
139 // were declared in the effective DC.
140 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
141 DeclContext *NS = UD->getNominatedNamespace();
142 if (!visited.insert(NS))
143 return;
144
145 addUsingDirective(UD, EffectiveDC);
146 addUsingDirectives(NS, EffectiveDC);
147 }
148
149 // Adds all the using directives in a context (and those nominated
150 // by its using directives, transitively) as if they appeared in
151 // the given effective context.
152 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000153 SmallVector<DeclContext*,4> queue;
John McCallf6c8a4e2009-11-10 07:01:13 +0000154 while (true) {
155 DeclContext::udir_iterator I, End;
156 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
157 UsingDirectiveDecl *UD = *I;
158 DeclContext *NS = UD->getNominatedNamespace();
159 if (visited.insert(NS)) {
160 addUsingDirective(UD, EffectiveDC);
161 queue.push_back(NS);
162 }
163 }
164
165 if (queue.empty())
166 return;
167
168 DC = queue.back();
169 queue.pop_back();
170 }
171 }
172
173 // Add a using directive as if it had been declared in the given
174 // context. This helps implement C++ [namespace.udir]p3:
175 // The using-directive is transitive: if a scope contains a
176 // using-directive that nominates a second namespace that itself
177 // contains using-directives, the effect is as if the
178 // using-directives from the second namespace also appeared in
179 // the first.
180 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
181 // Find the common ancestor between the effective context and
182 // the nominated namespace.
183 DeclContext *Common = UD->getNominatedNamespace();
184 while (!Common->Encloses(EffectiveDC))
185 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000186 Common = Common->getPrimaryContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000187
John McCallf6c8a4e2009-11-10 07:01:13 +0000188 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
189 }
190
191 void done() {
192 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
193 }
194
John McCallf6c8a4e2009-11-10 07:01:13 +0000195 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000196
John McCallf6c8a4e2009-11-10 07:01:13 +0000197 const_iterator begin() const { return list.begin(); }
198 const_iterator end() const { return list.end(); }
199
200 std::pair<const_iterator,const_iterator>
201 getNamespacesFor(DeclContext *DC) const {
John McCall9757d032009-11-10 09:20:04 +0000202 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCallf6c8a4e2009-11-10 07:01:13 +0000203 UnqualUsingEntry::Comparator());
204 }
205 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000206}
207
Douglas Gregor889ceb72009-02-03 19:21:40 +0000208// Retrieve the set of identifier namespaces that correspond to a
209// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000210static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
211 bool CPlusPlus,
212 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000213 unsigned IDNS = 0;
214 switch (NameKind) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +0000215 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000216 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000217 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000218 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000219 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000220 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000221 if (Redeclaration)
222 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCallea305ed2009-12-18 10:40:03 +0000223 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000224 break;
225
John McCallb9467b62010-04-24 01:30:58 +0000226 case Sema::LookupOperatorName:
227 // Operator lookup is its own crazy thing; it is not the same
228 // as (e.g.) looking up an operator name for redeclaration.
229 assert(!Redeclaration && "cannot do redeclaration operator lookup");
230 IDNS = Decl::IDNS_NonMemberOperator;
231 break;
232
Douglas Gregor889ceb72009-02-03 19:21:40 +0000233 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000234 if (CPlusPlus) {
235 IDNS = Decl::IDNS_Type;
236
237 // When looking for a redeclaration of a tag name, we add:
238 // 1) TagFriend to find undeclared friend decls
239 // 2) Namespace because they can't "overload" with tag decls.
240 // 3) Tag because it includes class templates, which can't
241 // "overload" with tag decls.
242 if (Redeclaration)
243 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
244 } else {
245 IDNS = Decl::IDNS_Tag;
246 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000247 break;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000248 case Sema::LookupLabel:
249 IDNS = Decl::IDNS_Label;
250 break;
251
Douglas Gregor889ceb72009-02-03 19:21:40 +0000252 case Sema::LookupMemberName:
253 IDNS = Decl::IDNS_Member;
254 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000255 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000256 break;
257
258 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000259 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
260 break;
261
Douglas Gregor889ceb72009-02-03 19:21:40 +0000262 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000263 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000264 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000265
John McCall84d87672009-12-10 09:41:52 +0000266 case Sema::LookupUsingDeclName:
267 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
268 | Decl::IDNS_Member | Decl::IDNS_Using;
269 break;
270
Douglas Gregor79947a22009-04-24 00:11:27 +0000271 case Sema::LookupObjCProtocolName:
272 IDNS = Decl::IDNS_ObjCProtocol;
273 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000274
Douglas Gregor39982192010-08-15 06:18:01 +0000275 case Sema::LookupAnyName:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000276 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor39982192010-08-15 06:18:01 +0000277 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
278 | Decl::IDNS_Type;
279 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000280 }
281 return IDNS;
282}
283
John McCallea305ed2009-12-18 10:40:03 +0000284void LookupResult::configure() {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000285 IDNS = getIDNS(LookupKind, SemaRef.getLangOpts().CPlusPlus,
John McCallea305ed2009-12-18 10:40:03 +0000286 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000287
288 // If we're looking for one of the allocation or deallocation
289 // operators, make sure that the implicitly-declared new and delete
290 // operators can be found.
291 if (!isForRedeclaration()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000292 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000293 case OO_New:
294 case OO_Delete:
295 case OO_Array_New:
296 case OO_Array_Delete:
297 SemaRef.DeclareGlobalNewDelete();
298 break;
299
300 default:
301 break;
302 }
303 }
John McCallea305ed2009-12-18 10:40:03 +0000304}
305
Daniel Dunbar9e19f132012-03-08 01:43:06 +0000306void LookupResult::sanityImpl() const {
307 // Note that this function is never called by NDEBUG builds. See
308 // LookupResult::sanity().
John McCall19c1bfd2010-08-25 05:32:35 +0000309 assert(ResultKind != NotFound || Decls.size() == 0);
310 assert(ResultKind != Found || Decls.size() == 1);
311 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
312 (Decls.size() == 1 &&
313 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
314 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
315 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000316 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
317 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall19c1bfd2010-08-25 05:32:35 +0000318 assert((Paths != NULL) == (ResultKind == Ambiguous &&
319 (Ambiguity == AmbiguousBaseSubobjectTypes ||
320 Ambiguity == AmbiguousBaseSubobjects)));
321}
John McCall19c1bfd2010-08-25 05:32:35 +0000322
John McCall9f3059a2009-10-09 21:13:30 +0000323// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000324void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000325 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000326}
327
Douglas Gregor4a814562011-12-14 16:03:29 +0000328static NamedDecl *getVisibleDecl(NamedDecl *D);
329
330NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
331 return getVisibleDecl(D);
332}
333
John McCall283b9012009-11-22 00:44:51 +0000334/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000335void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000336 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000337
John McCall9f3059a2009-10-09 21:13:30 +0000338 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000339 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000340 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000341 return;
342 }
343
John McCall283b9012009-11-22 00:44:51 +0000344 // If there's a single decl, we need to examine it to decide what
345 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000346 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000347 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
348 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000349 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000350 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000351 ResultKind = FoundUnresolvedValue;
352 return;
353 }
John McCall9f3059a2009-10-09 21:13:30 +0000354
John McCall6538c932009-10-10 05:48:19 +0000355 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000356 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000357
John McCall9f3059a2009-10-09 21:13:30 +0000358 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor13e65872010-08-11 14:45:53 +0000359 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000360
John McCall9f3059a2009-10-09 21:13:30 +0000361 bool Ambiguous = false;
362 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000363 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000364
365 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000366
John McCall9f3059a2009-10-09 21:13:30 +0000367 unsigned I = 0;
368 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000369 NamedDecl *D = Decls[I]->getUnderlyingDecl();
370 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000371
Douglas Gregor13e65872010-08-11 14:45:53 +0000372 // Redeclarations of types via typedef can occur both within a scope
373 // and, through using declarations and directives, across scopes. There is
374 // no ambiguity if they all refer to the same type, so unique based on the
375 // canonical type.
376 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
377 if (!TD->getDeclContext()->isRecord()) {
378 QualType T = SemaRef.Context.getTypeDeclType(TD);
379 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
380 // The type is not unique; pull something off the back and continue
381 // at this index.
382 Decls[I] = Decls[--N];
383 continue;
384 }
385 }
386 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000387
John McCallf0f1cf02009-11-17 07:50:12 +0000388 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000389 // If it's not unique, pull something off the back (and
390 // continue at this index).
391 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000392 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000393 }
394
Douglas Gregor13e65872010-08-11 14:45:53 +0000395 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000396
Douglas Gregor13e65872010-08-11 14:45:53 +0000397 if (isa<UnresolvedUsingValueDecl>(D)) {
398 HasUnresolved = true;
399 } else if (isa<TagDecl>(D)) {
400 if (HasTag)
401 Ambiguous = true;
402 UniqueTagIndex = I;
403 HasTag = true;
404 } else if (isa<FunctionTemplateDecl>(D)) {
405 HasFunction = true;
406 HasFunctionTemplate = true;
407 } else if (isa<FunctionDecl>(D)) {
408 HasFunction = true;
409 } else {
410 if (HasNonFunction)
411 Ambiguous = true;
412 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000413 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000414 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000415 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000416
John McCall9f3059a2009-10-09 21:13:30 +0000417 // C++ [basic.scope.hiding]p2:
418 // A class name or enumeration name can be hidden by the name of
419 // an object, function, or enumerator declared in the same
420 // scope. If a class or enumeration name and an object, function,
421 // or enumerator are declared in the same scope (in any order)
422 // with the same name, the class or enumeration name is hidden
423 // wherever the object, function, or enumerator name is visible.
424 // But it's still an error if there are distinct tag types found,
425 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000426 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000427 (HasFunction || HasNonFunction || HasUnresolved)) {
428 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
429 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
430 Decls[UniqueTagIndex] = Decls[--N];
431 else
432 Ambiguous = true;
433 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000434
John McCall9f3059a2009-10-09 21:13:30 +0000435 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000436
John McCall80053822009-12-03 00:58:24 +0000437 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000438 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000439
John McCall9f3059a2009-10-09 21:13:30 +0000440 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000441 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000442 else if (HasUnresolved)
443 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000444 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000445 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000446 else
John McCall27b18f82009-11-17 02:14:36 +0000447 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000448}
449
John McCall5cebab12009-11-18 07:57:50 +0000450void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000451 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000452 DeclContext::lookup_iterator DI, DE;
453 for (I = P.begin(), E = P.end(); I != E; ++I)
454 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
455 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000456}
457
John McCall5cebab12009-11-18 07:57:50 +0000458void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000459 Paths = new CXXBasePaths;
460 Paths->swap(P);
461 addDeclsFromBasePaths(*Paths);
462 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000463 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000464}
465
John McCall5cebab12009-11-18 07:57:50 +0000466void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000467 Paths = new CXXBasePaths;
468 Paths->swap(P);
469 addDeclsFromBasePaths(*Paths);
470 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000471 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000472}
473
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000474void LookupResult::print(raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000475 Out << Decls.size() << " result(s)";
476 if (isAmbiguous()) Out << ", ambiguous";
477 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000478
John McCall9f3059a2009-10-09 21:13:30 +0000479 for (iterator I = begin(), E = end(); I != E; ++I) {
480 Out << "\n";
481 (*I)->print(Out, 2);
482 }
483}
484
Douglas Gregord3a59182010-02-12 05:48:04 +0000485/// \brief Lookup a builtin function, when name lookup would otherwise
486/// fail.
487static bool LookupBuiltin(Sema &S, LookupResult &R) {
488 Sema::LookupNameKind NameKind = R.getLookupKind();
489
490 // If we didn't find a use of this identifier, and if the identifier
491 // corresponds to a compiler builtin, create the decl object for the builtin
492 // now, injecting it into translation unit scope, and return it.
493 if (NameKind == Sema::LookupOrdinaryName ||
494 NameKind == Sema::LookupRedeclarationWithLinkage) {
495 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
496 if (II) {
497 // If this is a builtin on this (or all) targets, create the decl.
498 if (unsigned BuiltinID = II->getBuiltinID()) {
499 // In C++, we don't have any predefined library functions like
500 // 'malloc'. Instead, we'll just error.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000501 if (S.getLangOpts().CPlusPlus &&
Douglas Gregord3a59182010-02-12 05:48:04 +0000502 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
503 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000504
505 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
506 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000507 R.isForRedeclaration(),
508 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000509 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000510 return true;
511 }
512
513 if (R.isForRedeclaration()) {
514 // If we're redeclaring this function anyway, forget that
515 // this was a builtin at all.
516 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
517 }
518
519 return false;
Douglas Gregord3a59182010-02-12 05:48:04 +0000520 }
521 }
522 }
523
524 return false;
525}
526
Douglas Gregor7454c562010-07-02 20:37:36 +0000527/// \brief Determine whether we can declare a special member function within
528/// the class at this point.
529static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
530 const CXXRecordDecl *Class) {
531 // We need to have a definition for the class.
532 if (!Class->getDefinition() || Class->isDependentContext())
533 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000534
Douglas Gregor7454c562010-07-02 20:37:36 +0000535 // We can't be in the middle of defining the class.
536 if (const RecordType *RecordTy
537 = Context.getTypeDeclType(Class)->getAs<RecordType>())
538 return !RecordTy->isBeingDefined();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000539
Douglas Gregor7454c562010-07-02 20:37:36 +0000540 return false;
541}
542
543void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000544 if (!CanDeclareSpecialMemberFunction(Context, Class))
545 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000546
547 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000548 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000549 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000550
Douglas Gregora6d69502010-07-02 23:41:54 +0000551 // If the copy constructor has not yet been declared, do so now.
552 if (!Class->hasDeclaredCopyConstructor())
553 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000554
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000555 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000556 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000557 DeclareImplicitCopyAssignment(Class);
558
David Blaikiebbafb8a2012-03-11 07:00:24 +0000559 if (getLangOpts().CPlusPlus0x) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000560 // If the move constructor has not yet been declared, do so now.
561 if (Class->needsImplicitMoveConstructor())
562 DeclareImplicitMoveConstructor(Class); // might not actually do it
563
564 // If the move assignment operator has not yet been declared, do so now.
565 if (Class->needsImplicitMoveAssignment())
566 DeclareImplicitMoveAssignment(Class); // might not actually do it
567 }
568
Douglas Gregor7454c562010-07-02 20:37:36 +0000569 // If the destructor has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000570 if (!Class->hasDeclaredDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000571 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000572}
573
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000574/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000575/// special member function.
576static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
577 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000578 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000579 case DeclarationName::CXXDestructorName:
580 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000581
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000582 case DeclarationName::CXXOperatorName:
583 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000584
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000585 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000586 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000587 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000588
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000589 return false;
590}
591
592/// \brief If there are any implicit member functions with the given name
593/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000594static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000595 DeclarationName Name,
596 const DeclContext *DC) {
597 if (!DC)
598 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000599
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000600 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000601 case DeclarationName::CXXConstructorName:
602 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor9672f922010-07-03 00:47:00 +0000603 if (Record->getDefinition() &&
604 CanDeclareSpecialMemberFunction(S.Context, Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000605 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000606 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000607 S.DeclareImplicitDefaultConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000608 if (!Record->hasDeclaredCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000609 S.DeclareImplicitCopyConstructor(Class);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000610 if (S.getLangOpts().CPlusPlus0x &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000611 Record->needsImplicitMoveConstructor())
612 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000613 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000614 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000615
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000616 case DeclarationName::CXXDestructorName:
617 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
618 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
619 CanDeclareSpecialMemberFunction(S.Context, Record))
620 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000621 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000622
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000623 case DeclarationName::CXXOperatorName:
624 if (Name.getCXXOverloadedOperator() != OO_Equal)
625 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000626
Sebastian Redl22653ba2011-08-30 19:58:05 +0000627 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
628 if (Record->getDefinition() &&
629 CanDeclareSpecialMemberFunction(S.Context, Record)) {
630 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
631 if (!Record->hasDeclaredCopyAssignment())
632 S.DeclareImplicitCopyAssignment(Class);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000633 if (S.getLangOpts().CPlusPlus0x &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000634 Record->needsImplicitMoveAssignment())
635 S.DeclareImplicitMoveAssignment(Class);
636 }
637 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000638 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000639
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000640 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000641 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000642 }
643}
Douglas Gregor7454c562010-07-02 20:37:36 +0000644
John McCall9f3059a2009-10-09 21:13:30 +0000645// Adds all qualifying matches for a name within a decl context to the
646// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000647static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000648 bool Found = false;
649
Douglas Gregor7454c562010-07-02 20:37:36 +0000650 // Lazily declare C++ special member functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000651 if (S.getLangOpts().CPlusPlus)
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000652 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000653
Douglas Gregor7454c562010-07-02 20:37:36 +0000654 // Perform lookup into this declaration context.
John McCallf6c8a4e2009-11-10 07:01:13 +0000655 DeclContext::lookup_const_iterator I, E;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000656 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall401982f2010-01-20 21:53:11 +0000657 NamedDecl *D = *I;
Douglas Gregor4a814562011-12-14 16:03:29 +0000658 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000659 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000660 Found = true;
661 }
662 }
John McCall9f3059a2009-10-09 21:13:30 +0000663
Douglas Gregord3a59182010-02-12 05:48:04 +0000664 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
665 return true;
666
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000667 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000668 != DeclarationName::CXXConversionFunctionName ||
669 R.getLookupName().getCXXNameType()->isDependentType() ||
670 !isa<CXXRecordDecl>(DC))
671 return Found;
672
673 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000674 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000675 // name lookup. Instead, any conversion function templates visible in the
676 // context of the use are considered. [...]
677 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000678 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000679 return Found;
680
681 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000682 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
Chandler Carruth3a693b72010-01-31 11:44:02 +0000683 UEnd = Unresolved->end(); U != UEnd; ++U) {
684 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
685 if (!ConvTemplate)
686 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000687
Chandler Carruth3a693b72010-01-31 11:44:02 +0000688 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000689 // add the conversion function template. When we deduce template
690 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000691 // type of the new declaration with the type of the function template.
692 if (R.isForRedeclaration()) {
693 R.addDecl(ConvTemplate);
694 Found = true;
695 continue;
696 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000697
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000698 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000699 // [...] For each such operator, if argument deduction succeeds
700 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000701 // name lookup.
702 //
703 // When referencing a conversion function for any purpose other than
704 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000705 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000706 // specialization into the result set. We do this to avoid forcing all
707 // callers to perform special deduction for conversion functions.
John McCall19c1bfd2010-08-25 05:32:35 +0000708 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruth3a693b72010-01-31 11:44:02 +0000709 FunctionDecl *Specialization = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000710
711 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000712 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
713 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000714
Chandler Carruth3a693b72010-01-31 11:44:02 +0000715 // Compute the type of the function that we would expect the conversion
716 // function to have, if it were to match the name given.
717 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000718 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
719 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
Sebastian Redl7c6c9e92011-03-06 10:52:04 +0000720 EPI.ExceptionSpecType = EST_None;
John McCalldb40c7f2010-12-14 08:05:40 +0000721 EPI.NumExceptions = 0;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000722 QualType ExpectedType
723 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
John McCalldb40c7f2010-12-14 08:05:40 +0000724 0, 0, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000725
Chandler Carruth3a693b72010-01-31 11:44:02 +0000726 // Perform template argument deduction against the type that we would
727 // expect the function to have.
728 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
729 Specialization, Info)
730 == Sema::TDK_Success) {
731 R.addDecl(Specialization);
732 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000733 }
734 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000735
John McCall9f3059a2009-10-09 21:13:30 +0000736 return Found;
737}
738
John McCallf6c8a4e2009-11-10 07:01:13 +0000739// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000740static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000741CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000742 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000743
744 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
745
John McCallf6c8a4e2009-11-10 07:01:13 +0000746 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000747 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000748
John McCallf6c8a4e2009-11-10 07:01:13 +0000749 // Perform direct name lookup into the namespaces nominated by the
750 // using directives whose common ancestor is this namespace.
751 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
752 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000753
John McCallf6c8a4e2009-11-10 07:01:13 +0000754 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000755 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000756 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000757
758 R.resolveKind();
759
760 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000761}
762
763static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000764 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000765 return Ctx->isFileContext();
766 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000767}
Douglas Gregored8f2882009-01-30 01:04:22 +0000768
Douglas Gregor66230062010-03-15 14:33:29 +0000769// Find the next outer declaration context from this scope. This
770// routine actually returns the semantic outer context, which may
771// differ from the lexical context (encoded directly in the Scope
772// stack) when we are parsing a member of a class template. In this
773// case, the second element of the pair will be true, to indicate that
774// name lookup should continue searching in this semantic context when
775// it leaves the current template parameter scope.
776static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
777 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
778 DeclContext *Lexical = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000779 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000780 OuterS = OuterS->getParent()) {
781 if (OuterS->getEntity()) {
Douglas Gregorea166062010-03-15 15:26:48 +0000782 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor66230062010-03-15 14:33:29 +0000783 break;
784 }
785 }
786
787 // C++ [temp.local]p8:
788 // In the definition of a member of a class template that appears
789 // outside of the namespace containing the class template
790 // definition, the name of a template-parameter hides the name of
791 // a member of this namespace.
792 //
793 // Example:
794 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000795 // namespace N {
796 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000797 //
798 // template<class T> class B {
799 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000800 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000801 // }
802 //
803 // template<class C> void N::B<C>::f(C) {
804 // C b; // C is the template parameter, not N::C
805 // }
806 //
807 // In this example, the lexical context we return is the
808 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000809 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000810 !S->getParent()->isTemplateParamScope())
811 return std::make_pair(Lexical, false);
812
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000813 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000814 // For the example, this is the scope for the template parameters of
815 // template<class C>.
816 Scope *OutermostTemplateScope = S->getParent();
817 while (OutermostTemplateScope->getParent() &&
818 OutermostTemplateScope->getParent()->isTemplateParamScope())
819 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000820
Douglas Gregor66230062010-03-15 14:33:29 +0000821 // Find the namespace context in which the original scope occurs. In
822 // the example, this is namespace N.
823 DeclContext *Semantic = DC;
824 while (!Semantic->isFileContext())
825 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000826
Douglas Gregor66230062010-03-15 14:33:29 +0000827 // Find the declaration context just outside of the template
828 // parameter scope. This is the context in which the template is
829 // being lexically declaration (a namespace context). In the
830 // example, this is the global scope.
831 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
832 Lexical->Encloses(Semantic))
833 return std::make_pair(Semantic, true);
834
835 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000836}
837
John McCall27b18f82009-11-17 02:14:36 +0000838bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000839 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000840
841 DeclarationName Name = R.getLookupName();
842
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000843 // If this is the name of an implicitly-declared special member function,
844 // go through the scope stack to implicitly declare
845 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
846 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
847 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
848 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
849 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000850
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000851 // Implicitly declare member functions with the name we're looking for, if in
852 // fact we are in a scope where it matters.
853
Douglas Gregor889ceb72009-02-03 19:21:40 +0000854 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000855 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000856 I = IdResolver.begin(Name),
857 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000858
Douglas Gregor889ceb72009-02-03 19:21:40 +0000859 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000860 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000861 // ...During unqualified name lookup (3.4.1), the names appear as if
862 // they were declared in the nearest enclosing namespace which contains
863 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000864 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000865 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000866 //
867 // For example:
868 // namespace A { int i; }
869 // void foo() {
870 // int i;
871 // {
872 // using namespace A;
873 // ++i; // finds local 'i', A::i appears at global scope
874 // }
875 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000876 //
Douglas Gregor66230062010-03-15 14:33:29 +0000877 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor700792c2009-02-05 19:25:20 +0000878 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor3e51e172010-05-20 20:58:56 +0000879 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
880
Douglas Gregor889ceb72009-02-03 19:21:40 +0000881 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000882 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000883 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000884 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
John McCall9f3059a2009-10-09 21:13:30 +0000885 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +0000886 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000887 }
888 }
John McCall9f3059a2009-10-09 21:13:30 +0000889 if (Found) {
890 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000891 if (S->isClassScope())
892 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
893 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000894 return true;
895 }
896
Douglas Gregor66230062010-03-15 14:33:29 +0000897 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
898 S->getParent() && !S->getParent()->isTemplateParamScope()) {
899 // We've just searched the last template parameter scope and
900 // found nothing, so look into the the contexts between the
901 // lexical and semantic declaration contexts returned by
902 // findOuterContext(). This implements the name lookup behavior
903 // of C++ [temp.local]p8.
904 Ctx = OutsideOfTemplateParamDC;
905 OutsideOfTemplateParamDC = 0;
906 }
907
908 if (Ctx) {
909 DeclContext *OuterCtx;
910 bool SearchAfterTemplateScope;
911 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
912 if (SearchAfterTemplateScope)
913 OutsideOfTemplateParamDC = OuterCtx;
914
Douglas Gregorea166062010-03-15 15:26:48 +0000915 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000916 // We do not directly look into transparent contexts, since
917 // those entities will be found in the nearest enclosing
918 // non-transparent context.
919 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000920 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000921
922 // We do not look directly into function or method contexts,
923 // since all of the local variables and parameters of the
924 // function/method are present within the Scope.
925 if (Ctx->isFunctionOrMethod()) {
926 // If we have an Objective-C instance method, look for ivars
927 // in the corresponding interface.
928 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
929 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
930 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
931 ObjCInterfaceDecl *ClassDeclared;
932 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000933 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +0000934 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000935 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
936 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +0000937 R.resolveKind();
938 return true;
939 }
940 }
941 }
942 }
943
944 continue;
945 }
946
Douglas Gregor7f737c02009-09-10 16:57:35 +0000947 // Perform qualified name lookup into this context.
948 // FIXME: In some cases, we know that every name that could be found by
949 // this qualified name lookup will also be on the identifier chain. For
950 // example, inside a class without any base classes, we never need to
951 // perform qualified lookup because all of the members are on top of the
952 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000953 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +0000954 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000955 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000956 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000957 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000958
John McCallf6c8a4e2009-11-10 07:01:13 +0000959 // Stop if we ran out of scopes.
960 // FIXME: This really, really shouldn't be happening.
961 if (!S) return false;
962
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +0000963 // If we are looking for members, no need to look into global/namespace scope.
964 if (R.getLookupKind() == LookupMemberName)
965 return false;
966
Douglas Gregor700792c2009-02-05 19:25:20 +0000967 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000968 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000969 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000970 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
971 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000972
John McCallf6c8a4e2009-11-10 07:01:13 +0000973 UnqualUsingDirectiveSet UDirs;
974 UDirs.visitScopeChain(Initial, S);
975 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000976
Douglas Gregor700792c2009-02-05 19:25:20 +0000977 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000978 // Unqualified name lookup in C++ requires looking into scopes
979 // that aren't strictly lexical, and therefore we walk through the
980 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000981
Douglas Gregor889ceb72009-02-03 19:21:40 +0000982 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000983 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000984 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000985 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000986 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000987 // We found something. Look for anything else in our scope
988 // with this same name and in an acceptable identifier
989 // namespace, so that we can construct an overload set if we
990 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000991 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +0000992 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000993 }
994 }
995
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000996 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +0000997 R.resolveKind();
998 return true;
999 }
1000
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001001 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1002 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1003 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1004 // We've just searched the last template parameter scope and
1005 // found nothing, so look into the the contexts between the
1006 // lexical and semantic declaration contexts returned by
1007 // findOuterContext(). This implements the name lookup behavior
1008 // of C++ [temp.local]p8.
1009 Ctx = OutsideOfTemplateParamDC;
1010 OutsideOfTemplateParamDC = 0;
1011 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001012
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001013 if (Ctx) {
1014 DeclContext *OuterCtx;
1015 bool SearchAfterTemplateScope;
1016 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1017 if (SearchAfterTemplateScope)
1018 OutsideOfTemplateParamDC = OuterCtx;
1019
1020 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1021 // We do not directly look into transparent contexts, since
1022 // those entities will be found in the nearest enclosing
1023 // non-transparent context.
1024 if (Ctx->isTransparentContext())
1025 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001026
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001027 // If we have a context, and it's not a context stashed in the
1028 // template parameter scope for an out-of-line definition, also
1029 // look into that context.
1030 if (!(Found && S && S->isTemplateParamScope())) {
1031 assert(Ctx->isFileContext() &&
1032 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001033
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001034 // Look into context considering using-directives.
1035 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1036 Found = true;
1037 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001038
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001039 if (Found) {
1040 R.resolveKind();
1041 return true;
1042 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001043
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001044 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1045 return false;
1046 }
1047 }
1048
Douglas Gregor3ce74932010-02-05 07:07:10 +00001049 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001050 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001051 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001052
John McCall9f3059a2009-10-09 21:13:30 +00001053 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001054}
1055
Douglas Gregor4a814562011-12-14 16:03:29 +00001056/// \brief Retrieve the visible declaration corresponding to D, if any.
1057///
1058/// This routine determines whether the declaration D is visible in the current
1059/// module, with the current imports. If not, it checks whether any
1060/// redeclaration of D is visible, and if so, returns that declaration.
1061///
1062/// \returns D, or a visible previous declaration of D, whichever is more recent
1063/// and visible. If no declaration of D is visible, returns null.
1064static NamedDecl *getVisibleDecl(NamedDecl *D) {
1065 if (LookupResult::isVisible(D))
1066 return D;
1067
Douglas Gregor54079202012-01-06 22:05:37 +00001068 for (Decl::redecl_iterator RD = D->redecls_begin(), RDEnd = D->redecls_end();
1069 RD != RDEnd; ++RD) {
1070 if (NamedDecl *ND = dyn_cast<NamedDecl>(*RD)) {
1071 if (LookupResult::isVisible(ND))
1072 return ND;
1073 }
Douglas Gregor4a814562011-12-14 16:03:29 +00001074 }
1075
1076 return 0;
1077}
1078
Douglas Gregor34074322009-01-14 22:20:51 +00001079/// @brief Perform unqualified name lookup starting from a given
1080/// scope.
1081///
1082/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1083/// used to find names within the current scope. For example, 'x' in
1084/// @code
1085/// int x;
1086/// int f() {
1087/// return x; // unqualified name look finds 'x' in the global scope
1088/// }
1089/// @endcode
1090///
1091/// Different lookup criteria can find different names. For example, a
1092/// particular scope can have both a struct and a function of the same
1093/// name, and each can be found by certain lookup criteria. For more
1094/// information about lookup criteria, see the documentation for the
1095/// class LookupCriteria.
1096///
1097/// @param S The scope from which unqualified name lookup will
1098/// begin. If the lookup criteria permits, name lookup may also search
1099/// in the parent scopes.
1100///
1101/// @param Name The name of the entity that we are searching for.
1102///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001103/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001104/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001105/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +00001106///
1107/// @returns The result of name lookup, which includes zero or more
1108/// declarations and possibly additional information used to diagnose
1109/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +00001110bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1111 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001112 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001113
John McCall27b18f82009-11-17 02:14:36 +00001114 LookupNameKind NameKind = R.getLookupKind();
1115
David Blaikiebbafb8a2012-03-11 07:00:24 +00001116 if (!getLangOpts().CPlusPlus) {
Douglas Gregor34074322009-01-14 22:20:51 +00001117 // Unqualified name lookup in C/Objective-C is purely lexical, so
1118 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001119 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001120 // Find the nearest non-transparent declaration scope.
1121 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +00001122 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +00001123 static_cast<DeclContext *>(S->getEntity())
1124 ->isTransparentContext()))
1125 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001126 }
1127
John McCallea305ed2009-12-18 10:40:03 +00001128 unsigned IDNS = R.getIdentifierNamespace();
1129
Douglas Gregor34074322009-01-14 22:20:51 +00001130 // Scan up the scope chain looking for a decl that matches this
1131 // identifier that is in the appropriate namespace. This search
1132 // should not take long, as shadowing of names is uncommon, and
1133 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001134 bool LeftStartingScope = false;
1135
Douglas Gregored8f2882009-01-30 01:04:22 +00001136 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001137 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001138 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001139 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001140 if (NameKind == LookupRedeclarationWithLinkage) {
1141 // Determine whether this (or a previous) declaration is
1142 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001143 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001144 LeftStartingScope = true;
1145
1146 // If we found something outside of our starting scope that
1147 // does not have linkage, skip it.
1148 if (LeftStartingScope && !((*I)->hasLinkage()))
1149 continue;
1150 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001151 else if (NameKind == LookupObjCImplicitSelfParam &&
1152 !isa<ImplicitParamDecl>(*I))
1153 continue;
1154
Douglas Gregor2a5d1482011-12-02 20:08:44 +00001155 // If this declaration is module-private and it came from an AST
1156 // file, we can't see it.
Douglas Gregor5c193c72012-01-05 01:11:47 +00001157 NamedDecl *D = R.isHiddenDeclarationVisible()? *I : getVisibleDecl(*I);
Douglas Gregor4a814562011-12-14 16:03:29 +00001158 if (!D)
Douglas Gregor2a5d1482011-12-02 20:08:44 +00001159 continue;
Douglas Gregor4a814562011-12-14 16:03:29 +00001160
1161 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001162
Douglas Gregorb59643b2012-01-03 23:26:26 +00001163 // Check whether there are any other declarations with the same name
1164 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001165 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001166 // Find the scope in which this declaration was declared (if it
1167 // actually exists in a Scope).
1168 while (S && !S->isDeclScope(D))
1169 S = S->getParent();
1170
1171 // If the scope containing the declaration is the translation unit,
1172 // then we'll need to perform our checks based on the matching
1173 // DeclContexts rather than matching scopes.
1174 if (S && isNamespaceOrTranslationUnitScope(S))
1175 S = 0;
1176
1177 // Compute the DeclContext, if we need it.
1178 DeclContext *DC = 0;
1179 if (!S)
1180 DC = (*I)->getDeclContext()->getRedeclContext();
1181
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001182 IdentifierResolver::iterator LastI = I;
1183 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001184 if (S) {
1185 // Match based on scope.
1186 if (!S->isDeclScope(*LastI))
1187 break;
1188 } else {
1189 // Match based on DeclContext.
1190 DeclContext *LastDC
1191 = (*LastI)->getDeclContext()->getRedeclContext();
1192 if (!LastDC->Equals(DC))
1193 break;
1194 }
1195
1196 // If the declaration isn't in the right namespace, skip it.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001197 if (!(*LastI)->isInIdentifierNamespace(IDNS))
1198 continue;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001199
Douglas Gregor5c193c72012-01-05 01:11:47 +00001200 D = R.isHiddenDeclarationVisible()? *LastI : getVisibleDecl(*LastI);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001201 if (D)
1202 R.addDecl(D);
1203 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001204
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001205 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001206 }
John McCall9f3059a2009-10-09 21:13:30 +00001207 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001208 }
Douglas Gregor34074322009-01-14 22:20:51 +00001209 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001210 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001211 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001212 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001213 }
1214
1215 // If we didn't find a use of this identifier, and if the identifier
1216 // corresponds to a compiler builtin, create the decl object for the builtin
1217 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001218 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1219 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001220
Axel Naumann016538a2011-02-24 16:47:47 +00001221 // If we didn't find a use of this identifier, the ExternalSource
1222 // may be able to handle the situation.
1223 // Note: some lookup failures are expected!
1224 // See e.g. R.isForRedeclaration().
1225 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001226}
1227
John McCall6538c932009-10-10 05:48:19 +00001228/// @brief Perform qualified name lookup in the namespaces nominated by
1229/// using directives by the given context.
1230///
1231/// C++98 [namespace.qual]p2:
1232/// Given X::m (where X is a user-declared namespace), or given ::m
1233/// (where X is the global namespace), let S be the set of all
1234/// declarations of m in X and in the transitive closure of all
1235/// namespaces nominated by using-directives in X and its used
1236/// namespaces, except that using-directives are ignored in any
1237/// namespace, including X, directly containing one or more
1238/// declarations of m. No namespace is searched more than once in
1239/// the lookup of a name. If S is the empty set, the program is
1240/// ill-formed. Otherwise, if S has exactly one member, or if the
1241/// context of the reference is a using-declaration
1242/// (namespace.udecl), S is the required set of declarations of
1243/// m. Otherwise if the use of m is not one that allows a unique
1244/// declaration to be chosen from S, the program is ill-formed.
1245/// C++98 [namespace.qual]p5:
1246/// During the lookup of a qualified namespace member name, if the
1247/// lookup finds more than one declaration of the member, and if one
1248/// declaration introduces a class name or enumeration name and the
1249/// other declarations either introduce the same object, the same
1250/// enumerator or a set of functions, the non-type name hides the
1251/// class or enumeration name if and only if the declarations are
1252/// from the same namespace; otherwise (the declarations are from
1253/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001254static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001255 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001256 assert(StartDC->isFileContext() && "start context is not a file context");
1257
1258 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1259 DeclContext::udir_iterator E = StartDC->using_directives_end();
1260
1261 if (I == E) return false;
1262
1263 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001264 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001265 Visited.insert(StartDC);
1266
1267 // We have not yet looked into these namespaces, much less added
1268 // their "using-children" to the queue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001269 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001270
1271 // We have already looked into the initial namespace; seed the queue
1272 // with its using-children.
1273 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +00001274 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001275 if (Visited.insert(ND))
John McCall6538c932009-10-10 05:48:19 +00001276 Queue.push_back(ND);
1277 }
1278
1279 // The easiest way to implement the restriction in [namespace.qual]p5
1280 // is to check whether any of the individual results found a tag
1281 // and, if so, to declare an ambiguity if the final result is not
1282 // a tag.
1283 bool FoundTag = false;
1284 bool FoundNonTag = false;
1285
John McCall5cebab12009-11-18 07:57:50 +00001286 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001287
1288 bool Found = false;
1289 while (!Queue.empty()) {
1290 NamespaceDecl *ND = Queue.back();
1291 Queue.pop_back();
1292
1293 // We go through some convolutions here to avoid copying results
1294 // between LookupResults.
1295 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001296 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001297 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001298
1299 if (FoundDirect) {
1300 // First do any local hiding.
1301 DirectR.resolveKind();
1302
1303 // If the local result is a tag, remember that.
1304 if (DirectR.isSingleTagDecl())
1305 FoundTag = true;
1306 else
1307 FoundNonTag = true;
1308
1309 // Append the local results to the total results if necessary.
1310 if (UseLocal) {
1311 R.addAllDecls(LocalR);
1312 LocalR.clear();
1313 }
1314 }
1315
1316 // If we find names in this namespace, ignore its using directives.
1317 if (FoundDirect) {
1318 Found = true;
1319 continue;
1320 }
1321
1322 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1323 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001324 if (Visited.insert(Nom))
John McCall6538c932009-10-10 05:48:19 +00001325 Queue.push_back(Nom);
1326 }
1327 }
1328
1329 if (Found) {
1330 if (FoundTag && FoundNonTag)
1331 R.setAmbiguousQualifiedTagHiding();
1332 else
1333 R.resolveKind();
1334 }
1335
1336 return Found;
1337}
1338
Douglas Gregor39982192010-08-15 06:18:01 +00001339/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001340static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor39982192010-08-15 06:18:01 +00001341 CXXBasePath &Path,
1342 void *Name) {
1343 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001344
Douglas Gregor39982192010-08-15 06:18:01 +00001345 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1346 Path.Decls = BaseRecord->lookup(N);
1347 return Path.Decls.first != Path.Decls.second;
1348}
1349
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001350/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001351/// static members, nested types, and enumerators.
1352template<typename InputIterator>
1353static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1354 Decl *D = (*First)->getUnderlyingDecl();
1355 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1356 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001357
Douglas Gregorc0d24902010-10-22 22:08:47 +00001358 if (isa<CXXMethodDecl>(D)) {
1359 // Determine whether all of the methods are static.
1360 bool AllMethodsAreStatic = true;
1361 for(; First != Last; ++First) {
1362 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001363
Douglas Gregorc0d24902010-10-22 22:08:47 +00001364 if (!isa<CXXMethodDecl>(D)) {
1365 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1366 break;
1367 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001368
Douglas Gregorc0d24902010-10-22 22:08:47 +00001369 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1370 AllMethodsAreStatic = false;
1371 break;
1372 }
1373 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001374
Douglas Gregorc0d24902010-10-22 22:08:47 +00001375 if (AllMethodsAreStatic)
1376 return true;
1377 }
1378
1379 return false;
1380}
1381
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001382/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001383///
1384/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1385/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001386/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001387///
1388/// Different lookup criteria can find different names. For example, a
1389/// particular scope can have both a struct and a function of the same
1390/// name, and each can be found by certain lookup criteria. For more
1391/// information about lookup criteria, see the documentation for the
1392/// class LookupCriteria.
1393///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001394/// \param R captures both the lookup criteria and any lookup results found.
1395///
1396/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001397/// search. If the lookup criteria permits, name lookup may also search
1398/// in the parent contexts or (for C++ classes) base classes.
1399///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001400/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001401/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001402///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001403/// \returns true if lookup succeeded, false if it failed.
1404bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1405 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001406 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001407
John McCall27b18f82009-11-17 02:14:36 +00001408 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001409 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001410
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001411 // Make sure that the declaration context is complete.
1412 assert((!isa<TagDecl>(LookupCtx) ||
1413 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00001414 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001415 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1416 ->isBeingDefined()) &&
1417 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001418
Douglas Gregor34074322009-01-14 22:20:51 +00001419 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001420 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001421 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001422 if (isa<CXXRecordDecl>(LookupCtx))
1423 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001424 return true;
1425 }
Douglas Gregor34074322009-01-14 22:20:51 +00001426
John McCall6538c932009-10-10 05:48:19 +00001427 // Don't descend into implied contexts for redeclarations.
1428 // C++98 [namespace.qual]p6:
1429 // In a declaration for a namespace member in which the
1430 // declarator-id is a qualified-id, given that the qualified-id
1431 // for the namespace member has the form
1432 // nested-name-specifier unqualified-id
1433 // the unqualified-id shall name a member of the namespace
1434 // designated by the nested-name-specifier.
1435 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001436 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001437 return false;
1438
John McCall27b18f82009-11-17 02:14:36 +00001439 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001440 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001441 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001442
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001443 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001444 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001445 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001446 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001447 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001448
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001449 // If we're performing qualified name lookup into a dependent class,
1450 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001451 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001452 // template instantiation time (at which point all bases will be available)
1453 // or we have to fail.
1454 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1455 LookupRec->hasAnyDependentBases()) {
1456 R.setNotFoundInCurrentInstantiation();
1457 return false;
1458 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001459
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001460 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001461 CXXBasePaths Paths;
1462 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001463
1464 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001465 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001466 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001467 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001468 case LookupOrdinaryName:
1469 case LookupMemberName:
1470 case LookupRedeclarationWithLinkage:
1471 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1472 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001473
Douglas Gregor36d1b142009-10-06 17:59:45 +00001474 case LookupTagName:
1475 BaseCallback = &CXXRecordDecl::FindTagMember;
1476 break;
John McCall84d87672009-12-10 09:41:52 +00001477
Douglas Gregor39982192010-08-15 06:18:01 +00001478 case LookupAnyName:
1479 BaseCallback = &LookupAnyMember;
1480 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001481
John McCall84d87672009-12-10 09:41:52 +00001482 case LookupUsingDeclName:
1483 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001484
Douglas Gregor36d1b142009-10-06 17:59:45 +00001485 case LookupOperatorName:
1486 case LookupNamespaceName:
1487 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001488 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001489 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001490 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001491
Douglas Gregor36d1b142009-10-06 17:59:45 +00001492 case LookupNestedNameSpecifierName:
1493 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1494 break;
1495 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001496
John McCall27b18f82009-11-17 02:14:36 +00001497 if (!LookupRec->lookupInBases(BaseCallback,
1498 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001499 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001500
John McCall553c0792010-01-23 00:46:32 +00001501 R.setNamingClass(LookupRec);
1502
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001503 // C++ [class.member.lookup]p2:
1504 // [...] If the resulting set of declarations are not all from
1505 // sub-objects of the same type, or the set has a nonstatic member
1506 // and includes members from distinct sub-objects, there is an
1507 // ambiguity and the program is ill-formed. Otherwise that set is
1508 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001509 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001510 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001511 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001512
Douglas Gregor36d1b142009-10-06 17:59:45 +00001513 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001514 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001515 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001516
John McCall401982f2010-01-20 21:53:11 +00001517 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1518 // across all paths.
1519 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001520
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001521 // Determine whether we're looking at a distinct sub-object or not.
1522 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001523 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001524 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1525 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001526 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001527 }
1528
Douglas Gregorc0d24902010-10-22 22:08:47 +00001529 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001530 != Context.getCanonicalType(PathElement.Base->getType())) {
1531 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001532 // different types. If the declaration sets aren't the same, this
1533 // this lookup is ambiguous.
1534 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1535 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1536 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1537 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001538
Douglas Gregorc0d24902010-10-22 22:08:47 +00001539 while (FirstD != FirstPath->Decls.second &&
1540 CurrentD != Path->Decls.second) {
1541 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1542 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1543 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001544
Douglas Gregorc0d24902010-10-22 22:08:47 +00001545 ++FirstD;
1546 ++CurrentD;
1547 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001548
Douglas Gregorc0d24902010-10-22 22:08:47 +00001549 if (FirstD == FirstPath->Decls.second &&
1550 CurrentD == Path->Decls.second)
1551 continue;
1552 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001553
John McCall9f3059a2009-10-09 21:13:30 +00001554 R.setAmbiguousBaseSubobjectTypes(Paths);
1555 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001556 }
1557
Douglas Gregorc0d24902010-10-22 22:08:47 +00001558 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001559 // We have a different subobject of the same type.
1560
1561 // C++ [class.member.lookup]p5:
1562 // A static member, a nested type or an enumerator defined in
1563 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001564 // has more than one base class subobject of type T.
Douglas Gregorc0d24902010-10-22 22:08:47 +00001565 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001566 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001567
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001568 // We have found a nonstatic member name in multiple, distinct
1569 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001570 R.setAmbiguousBaseSubobjects(Paths);
1571 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001572 }
1573 }
1574
1575 // Lookup in a base class succeeded; return these results.
1576
John McCall9f3059a2009-10-09 21:13:30 +00001577 DeclContext::lookup_iterator I, E;
John McCall553c0792010-01-23 00:46:32 +00001578 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1579 NamedDecl *D = *I;
1580 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1581 D->getAccess());
1582 R.addDecl(D, AS);
1583 }
John McCall9f3059a2009-10-09 21:13:30 +00001584 R.resolveKind();
1585 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001586}
1587
1588/// @brief Performs name lookup for a name that was parsed in the
1589/// source code, and may contain a C++ scope specifier.
1590///
1591/// This routine is a convenience routine meant to be called from
1592/// contexts that receive a name and an optional C++ scope specifier
1593/// (e.g., "N::M::x"). It will then perform either qualified or
1594/// unqualified name lookup (with LookupQualifiedName or LookupName,
1595/// respectively) on the given name and return those results.
1596///
1597/// @param S The scope from which unqualified name lookup will
1598/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001599///
Douglas Gregore861bac2009-08-25 22:51:20 +00001600/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001601///
Douglas Gregore861bac2009-08-25 22:51:20 +00001602/// @param EnteringContext Indicates whether we are going to enter the
1603/// context of the scope-specifier SS (if present).
1604///
John McCall9f3059a2009-10-09 21:13:30 +00001605/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001606bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001607 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001608 if (SS && SS->isInvalid()) {
1609 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001610 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001611 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001612 }
Mike Stump11289f42009-09-09 15:08:12 +00001613
Douglas Gregore861bac2009-08-25 22:51:20 +00001614 if (SS && SS->isSet()) {
1615 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001616 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001617 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001618 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001619 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001620
John McCall27b18f82009-11-17 02:14:36 +00001621 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00001622 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001623 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001624
Douglas Gregore861bac2009-08-25 22:51:20 +00001625 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001626 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001627 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00001628 R.setNotFoundInCurrentInstantiation();
1629 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00001630 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001631 }
1632
Mike Stump11289f42009-09-09 15:08:12 +00001633 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001634 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001635}
1636
Douglas Gregor889ceb72009-02-03 19:21:40 +00001637
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001638/// @brief Produce a diagnostic describing the ambiguity that resulted
1639/// from name lookup.
1640///
1641/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001642///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001643/// @param Name The name of the entity that name lookup was
1644/// searching for.
1645///
1646/// @param NameLoc The location of the name within the source code.
1647///
1648/// @param LookupRange A source range that provides more
1649/// source-location information concerning the lookup itself. For
1650/// example, this range might highlight a nested-name-specifier that
1651/// precedes the name.
1652///
1653/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001654bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001655 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1656
John McCall27b18f82009-11-17 02:14:36 +00001657 DeclarationName Name = Result.getLookupName();
1658 SourceLocation NameLoc = Result.getNameLoc();
1659 SourceRange LookupRange = Result.getContextRange();
1660
John McCall6538c932009-10-10 05:48:19 +00001661 switch (Result.getAmbiguityKind()) {
1662 case LookupResult::AmbiguousBaseSubobjects: {
1663 CXXBasePaths *Paths = Result.getBasePaths();
1664 QualType SubobjectType = Paths->front().back().Base->getType();
1665 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1666 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1667 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001668
John McCall6538c932009-10-10 05:48:19 +00001669 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1670 while (isa<CXXMethodDecl>(*Found) &&
1671 cast<CXXMethodDecl>(*Found)->isStatic())
1672 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001673
John McCall6538c932009-10-10 05:48:19 +00001674 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001675
John McCall6538c932009-10-10 05:48:19 +00001676 return true;
1677 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001678
John McCall6538c932009-10-10 05:48:19 +00001679 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001680 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1681 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001682
John McCall6538c932009-10-10 05:48:19 +00001683 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001684 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001685 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1686 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001687 Path != PathEnd; ++Path) {
1688 Decl *D = *Path->Decls.first;
1689 if (DeclsPrinted.insert(D).second)
1690 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1691 }
1692
Douglas Gregor1c846b02009-01-16 00:38:09 +00001693 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001694 }
1695
John McCall6538c932009-10-10 05:48:19 +00001696 case LookupResult::AmbiguousTagHiding: {
1697 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001698
John McCall6538c932009-10-10 05:48:19 +00001699 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1700
1701 LookupResult::iterator DI, DE = Result.end();
1702 for (DI = Result.begin(); DI != DE; ++DI)
1703 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1704 TagDecls.insert(TD);
1705 Diag(TD->getLocation(), diag::note_hidden_tag);
1706 }
1707
1708 for (DI = Result.begin(); DI != DE; ++DI)
1709 if (!isa<TagDecl>(*DI))
1710 Diag((*DI)->getLocation(), diag::note_hiding_object);
1711
1712 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001713 LookupResult::Filter F = Result.makeFilter();
1714 while (F.hasNext()) {
1715 if (TagDecls.count(F.next()))
1716 F.erase();
1717 }
1718 F.done();
John McCall6538c932009-10-10 05:48:19 +00001719
1720 return true;
1721 }
1722
1723 case LookupResult::AmbiguousReference: {
1724 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001725
John McCall6538c932009-10-10 05:48:19 +00001726 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1727 for (; DI != DE; ++DI)
1728 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001729
John McCall6538c932009-10-10 05:48:19 +00001730 return true;
1731 }
1732 }
1733
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001734 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001735}
Douglas Gregore254f902009-02-04 00:32:51 +00001736
John McCallf24d7bb2010-05-28 18:45:08 +00001737namespace {
1738 struct AssociatedLookup {
1739 AssociatedLookup(Sema &S,
1740 Sema::AssociatedNamespaceSet &Namespaces,
1741 Sema::AssociatedClassSet &Classes)
1742 : S(S), Namespaces(Namespaces), Classes(Classes) {
1743 }
1744
1745 Sema &S;
1746 Sema::AssociatedNamespaceSet &Namespaces;
1747 Sema::AssociatedClassSet &Classes;
1748 };
1749}
1750
Mike Stump11289f42009-09-09 15:08:12 +00001751static void
John McCallf24d7bb2010-05-28 18:45:08 +00001752addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001753
Douglas Gregor8b895222010-04-30 07:08:38 +00001754static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1755 DeclContext *Ctx) {
1756 // Add the associated namespace for this class.
1757
1758 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1759 // be a locally scoped record.
1760
Sebastian Redlbd595762010-08-31 20:53:31 +00001761 // We skip out of inline namespaces. The innermost non-inline namespace
1762 // contains all names of all its nested inline namespaces anyway, so we can
1763 // replace the entire inline namespace tree with its root.
1764 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1765 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00001766 Ctx = Ctx->getParent();
1767
John McCallc7e8e792009-08-07 22:18:02 +00001768 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001769 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001770}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001771
Mike Stump11289f42009-09-09 15:08:12 +00001772// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001773// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001774static void
John McCallf24d7bb2010-05-28 18:45:08 +00001775addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1776 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001777 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001778 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001779 switch (Arg.getKind()) {
1780 case TemplateArgument::Null:
1781 break;
Mike Stump11289f42009-09-09 15:08:12 +00001782
Douglas Gregor197e5f72009-07-08 07:51:57 +00001783 case TemplateArgument::Type:
1784 // [...] the namespaces and classes associated with the types of the
1785 // template arguments provided for template type parameters (excluding
1786 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001787 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001788 break;
Mike Stump11289f42009-09-09 15:08:12 +00001789
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001790 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001791 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00001792 // [...] the namespaces in which any template template arguments are
1793 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001794 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001795 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00001796 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001797 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001798 DeclContext *Ctx = ClassTemplate->getDeclContext();
1799 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001800 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001801 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001802 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001803 }
1804 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001805 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001806
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001807 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001808 case TemplateArgument::Integral:
1809 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001810 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001811 // associated namespaces. ]
1812 break;
Mike Stump11289f42009-09-09 15:08:12 +00001813
Douglas Gregor197e5f72009-07-08 07:51:57 +00001814 case TemplateArgument::Pack:
1815 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1816 PEnd = Arg.pack_end();
1817 P != PEnd; ++P)
John McCallf24d7bb2010-05-28 18:45:08 +00001818 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001819 break;
1820 }
1821}
1822
Douglas Gregore254f902009-02-04 00:32:51 +00001823// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001824// argument-dependent lookup with an argument of class type
1825// (C++ [basic.lookup.koenig]p2).
1826static void
John McCallf24d7bb2010-05-28 18:45:08 +00001827addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1828 CXXRecordDecl *Class) {
1829
1830 // Just silently ignore anything whose name is __va_list_tag.
1831 if (Class->getDeclName() == Result.S.VAListTagName)
1832 return;
1833
Douglas Gregore254f902009-02-04 00:32:51 +00001834 // C++ [basic.lookup.koenig]p2:
1835 // [...]
1836 // -- If T is a class type (including unions), its associated
1837 // classes are: the class itself; the class of which it is a
1838 // member, if any; and its direct and indirect base
1839 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001840 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001841
1842 // Add the class of which it is a member, if any.
1843 DeclContext *Ctx = Class->getDeclContext();
1844 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001845 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001846 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001847 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001848
Douglas Gregore254f902009-02-04 00:32:51 +00001849 // Add the class itself. If we've already seen this class, we don't
1850 // need to visit base classes.
John McCallf24d7bb2010-05-28 18:45:08 +00001851 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00001852 return;
1853
Mike Stump11289f42009-09-09 15:08:12 +00001854 // -- If T is a template-id, its associated namespaces and classes are
1855 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001856 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001857 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001858 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001859 // namespaces in which any template template arguments are defined; and
1860 // the classes in which any member templates used as template template
1861 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001862 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001863 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001864 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1865 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1866 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001867 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001868 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001869 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001870
Douglas Gregor197e5f72009-07-08 07:51:57 +00001871 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1872 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00001873 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001874 }
Mike Stump11289f42009-09-09 15:08:12 +00001875
John McCall67da35c2010-02-04 22:26:26 +00001876 // Only recurse into base classes for complete types.
1877 if (!Class->hasDefinition()) {
1878 // FIXME: we might need to instantiate templates here
1879 return;
1880 }
1881
Douglas Gregore254f902009-02-04 00:32:51 +00001882 // Add direct and indirect base classes along with their associated
1883 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001884 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00001885 Bases.push_back(Class);
1886 while (!Bases.empty()) {
1887 // Pop this class off the stack.
1888 Class = Bases.back();
1889 Bases.pop_back();
1890
1891 // Visit the base classes.
1892 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1893 BaseEnd = Class->bases_end();
1894 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001895 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001896 // In dependent contexts, we do ADL twice, and the first time around,
1897 // the base type might be a dependent TemplateSpecializationType, or a
1898 // TemplateTypeParmType. If that happens, simply ignore it.
1899 // FIXME: If we want to support export, we probably need to add the
1900 // namespace of the template in a TemplateSpecializationType, or even
1901 // the classes and namespaces of known non-dependent arguments.
1902 if (!BaseType)
1903 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001904 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001905 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00001906 // Find the associated namespace for this base class.
1907 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00001908 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001909
1910 // Make sure we visit the bases of this base class.
1911 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1912 Bases.push_back(BaseDecl);
1913 }
1914 }
1915 }
1916}
1917
1918// \brief Add the associated classes and namespaces for
1919// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001920// (C++ [basic.lookup.koenig]p2).
1921static void
John McCallf24d7bb2010-05-28 18:45:08 +00001922addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00001923 // C++ [basic.lookup.koenig]p2:
1924 //
1925 // For each argument type T in the function call, there is a set
1926 // of zero or more associated namespaces and a set of zero or more
1927 // associated classes to be considered. The sets of namespaces and
1928 // classes is determined entirely by the types of the function
1929 // arguments (and the namespace of any template template
1930 // argument). Typedef names and using-declarations used to specify
1931 // the types do not contribute to this set. The sets of namespaces
1932 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00001933
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001934 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00001935 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1936
Douglas Gregore254f902009-02-04 00:32:51 +00001937 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00001938 switch (T->getTypeClass()) {
1939
1940#define TYPE(Class, Base)
1941#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1942#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1943#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1944#define ABSTRACT_TYPE(Class, Base)
1945#include "clang/AST/TypeNodes.def"
1946 // T is canonical. We can also ignore dependent types because
1947 // we don't need to do ADL at the definition point, but if we
1948 // wanted to implement template export (or if we find some other
1949 // use for associated classes and namespaces...) this would be
1950 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00001951 break;
Douglas Gregore254f902009-02-04 00:32:51 +00001952
John McCall0af3d3b2010-05-28 06:08:54 +00001953 // -- If T is a pointer to U or an array of U, its associated
1954 // namespaces and classes are those associated with U.
1955 case Type::Pointer:
1956 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1957 continue;
1958 case Type::ConstantArray:
1959 case Type::IncompleteArray:
1960 case Type::VariableArray:
1961 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1962 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001963
John McCall0af3d3b2010-05-28 06:08:54 +00001964 // -- If T is a fundamental type, its associated sets of
1965 // namespaces and classes are both empty.
1966 case Type::Builtin:
1967 break;
1968
1969 // -- If T is a class type (including unions), its associated
1970 // classes are: the class itself; the class of which it is a
1971 // member, if any; and its direct and indirect base
1972 // classes. Its associated namespaces are the namespaces in
1973 // which its associated classes are defined.
1974 case Type::Record: {
1975 CXXRecordDecl *Class
1976 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001977 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00001978 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00001979 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00001980
John McCall0af3d3b2010-05-28 06:08:54 +00001981 // -- If T is an enumeration type, its associated namespace is
1982 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001983 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00001984 // it has no associated class.
1985 case Type::Enum: {
1986 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001987
John McCall0af3d3b2010-05-28 06:08:54 +00001988 DeclContext *Ctx = Enum->getDeclContext();
1989 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001990 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001991
John McCall0af3d3b2010-05-28 06:08:54 +00001992 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001993 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001994
John McCall0af3d3b2010-05-28 06:08:54 +00001995 break;
1996 }
1997
1998 // -- If T is a function type, its associated namespaces and
1999 // classes are those associated with the function parameter
2000 // types and those associated with the return type.
2001 case Type::FunctionProto: {
2002 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2003 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
2004 ArgEnd = Proto->arg_type_end();
2005 Arg != ArgEnd; ++Arg)
2006 Queue.push_back(Arg->getTypePtr());
2007 // fallthrough
2008 }
2009 case Type::FunctionNoProto: {
2010 const FunctionType *FnType = cast<FunctionType>(T);
2011 T = FnType->getResultType().getTypePtr();
2012 continue;
2013 }
2014
2015 // -- If T is a pointer to a member function of a class X, its
2016 // associated namespaces and classes are those associated
2017 // with the function parameter types and return type,
2018 // together with those associated with X.
2019 //
2020 // -- If T is a pointer to a data member of class X, its
2021 // associated namespaces and classes are those associated
2022 // with the member type together with those associated with
2023 // X.
2024 case Type::MemberPointer: {
2025 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2026
2027 // Queue up the class type into which this points.
2028 Queue.push_back(MemberPtr->getClass());
2029
2030 // And directly continue with the pointee type.
2031 T = MemberPtr->getPointeeType().getTypePtr();
2032 continue;
2033 }
2034
2035 // As an extension, treat this like a normal pointer.
2036 case Type::BlockPointer:
2037 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2038 continue;
2039
2040 // References aren't covered by the standard, but that's such an
2041 // obvious defect that we cover them anyway.
2042 case Type::LValueReference:
2043 case Type::RValueReference:
2044 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2045 continue;
2046
2047 // These are fundamental types.
2048 case Type::Vector:
2049 case Type::ExtVector:
2050 case Type::Complex:
2051 break;
2052
Douglas Gregor8e936662011-04-12 01:02:45 +00002053 // If T is an Objective-C object or interface type, or a pointer to an
2054 // object or interface type, the associated namespace is the global
2055 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002056 case Type::ObjCObject:
2057 case Type::ObjCInterface:
2058 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002059 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002060 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002061
2062 // Atomic types are just wrappers; use the associations of the
2063 // contained type.
2064 case Type::Atomic:
2065 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2066 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002067 }
2068
2069 if (Queue.empty()) break;
2070 T = Queue.back();
2071 Queue.pop_back();
Douglas Gregore254f902009-02-04 00:32:51 +00002072 }
Douglas Gregore254f902009-02-04 00:32:51 +00002073}
2074
2075/// \brief Find the associated classes and namespaces for
2076/// argument-dependent lookup for a call with the given set of
2077/// arguments.
2078///
2079/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002080/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002081/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002082void
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002083Sema::FindAssociatedClassesAndNamespaces(llvm::ArrayRef<Expr *> Args,
Douglas Gregore254f902009-02-04 00:32:51 +00002084 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00002085 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002086 AssociatedNamespaces.clear();
2087 AssociatedClasses.clear();
2088
John McCallf24d7bb2010-05-28 18:45:08 +00002089 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
2090
Douglas Gregore254f902009-02-04 00:32:51 +00002091 // C++ [basic.lookup.koenig]p2:
2092 // For each argument type T in the function call, there is a set
2093 // of zero or more associated namespaces and a set of zero or more
2094 // associated classes to be considered. The sets of namespaces and
2095 // classes is determined entirely by the types of the function
2096 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002097 // argument).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002098 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregore254f902009-02-04 00:32:51 +00002099 Expr *Arg = Args[ArgIdx];
2100
2101 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002102 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002103 continue;
2104 }
2105
2106 // [...] In addition, if the argument is the name or address of a
2107 // set of overloaded functions and/or function templates, its
2108 // associated classes and namespaces are the union of those
2109 // associated with each of the members of the set: the namespace
2110 // in which the function or function template is defined and the
2111 // classes and namespaces associated with its (non-dependent)
2112 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002113 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002114 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002115 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002116 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002117
John McCallf24d7bb2010-05-28 18:45:08 +00002118 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2119 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002120
John McCallf24d7bb2010-05-28 18:45:08 +00002121 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2122 I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002123 // Look through any using declarations to find the underlying function.
2124 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002125
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002126 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2127 if (!FDecl)
2128 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002129
2130 // Add the classes and namespaces associated with the parameter
2131 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002132 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002133 }
2134 }
2135}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002136
2137/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2138/// an acceptable non-member overloaded operator for a call whose
2139/// arguments have types T1 (and, if non-empty, T2). This routine
2140/// implements the check in C++ [over.match.oper]p3b2 concerning
2141/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00002142static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002143IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2144 QualType T1, QualType T2,
2145 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00002146 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2147 return true;
2148
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002149 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2150 return true;
2151
John McCall9dd450b2009-09-21 23:43:11 +00002152 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002153 if (Proto->getNumArgs() < 1)
2154 return false;
2155
2156 if (T1->isEnumeralType()) {
2157 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002158 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002159 return true;
2160 }
2161
2162 if (Proto->getNumArgs() < 2)
2163 return false;
2164
2165 if (!T2.isNull() && T2->isEnumeralType()) {
2166 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002167 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002168 return true;
2169 }
2170
2171 return false;
2172}
2173
John McCall5cebab12009-11-18 07:57:50 +00002174NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002175 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002176 LookupNameKind NameKind,
2177 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002178 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002179 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002180 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002181}
2182
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002183/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002184ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002185 SourceLocation IdLoc,
2186 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002187 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002188 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002189 return cast_or_null<ObjCProtocolDecl>(D);
2190}
2191
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002192void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002193 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002194 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002195 // C++ [over.match.oper]p3:
2196 // -- The set of non-member candidates is the result of the
2197 // unqualified lookup of operator@ in the context of the
2198 // expression according to the usual rules for name lookup in
2199 // unqualified function calls (3.4.2) except that all member
2200 // functions are ignored. However, if no operand has a class
2201 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00002202 // that have a first parameter of type T1 or "reference to
2203 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002204 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00002205 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002206 // when T2 is an enumeration type, are candidate functions.
2207 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002208 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2209 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002210
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002211 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2212
John McCall9f3059a2009-10-09 21:13:30 +00002213 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002214 return;
2215
2216 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2217 Op != OpEnd; ++Op) {
Douglas Gregor645d76f2010-04-25 20:25:43 +00002218 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2219 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002220 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor645d76f2010-04-25 20:25:43 +00002221 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00002222 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor645d76f2010-04-25 20:25:43 +00002223 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor15448f82009-06-27 21:05:07 +00002224 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00002225 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00002226 // later?
2227 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor645d76f2010-04-25 20:25:43 +00002228 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor15448f82009-06-27 21:05:07 +00002229 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002230 }
2231}
2232
Alexis Hunt1da39282011-06-24 02:11:39 +00002233Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002234 CXXSpecialMember SM,
2235 bool ConstArg,
2236 bool VolatileArg,
2237 bool RValueThis,
2238 bool ConstThis,
2239 bool VolatileThis) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002240 RD = RD->getDefinition();
2241 assert((RD && !RD->isBeingDefined()) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002242 "doing special member lookup into record that isn't fully complete");
2243 if (RValueThis || ConstThis || VolatileThis)
2244 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2245 "constructors and destructors always have unqualified lvalue this");
2246 if (ConstArg || VolatileArg)
2247 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2248 "parameter-less special members can't have qualified arguments");
2249
2250 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002251 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002252 ID.AddInteger(SM);
2253 ID.AddInteger(ConstArg);
2254 ID.AddInteger(VolatileArg);
2255 ID.AddInteger(RValueThis);
2256 ID.AddInteger(ConstThis);
2257 ID.AddInteger(VolatileThis);
2258
2259 void *InsertPoint;
2260 SpecialMemberOverloadResult *Result =
2261 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2262
2263 // This was already cached
2264 if (Result)
2265 return Result;
2266
Alexis Huntba8e18d2011-06-07 00:11:58 +00002267 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2268 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002269 SpecialMemberCache.InsertNode(Result, InsertPoint);
2270
2271 if (SM == CXXDestructor) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002272 if (!RD->hasDeclaredDestructor())
2273 DeclareImplicitDestructor(RD);
2274 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002275 assert(DD && "record without a destructor");
2276 Result->setMethod(DD);
Richard Smithd951a1d2012-02-18 02:02:13 +00002277 Result->setSuccess(!DD->isDeleted());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002278 Result->setConstParamMatch(false);
2279 return Result;
2280 }
2281
Alexis Hunteef8ee02011-06-10 03:50:41 +00002282 // Prepare for overload resolution. Here we construct a synthetic argument
2283 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002284 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002285 DeclarationName Name;
2286 Expr *Arg = 0;
2287 unsigned NumArgs;
2288
2289 if (SM == CXXDefaultConstructor) {
2290 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2291 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002292 if (RD->needsImplicitDefaultConstructor())
2293 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002294 } else {
2295 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2296 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Alexis Hunt1da39282011-06-24 02:11:39 +00002297 if (!RD->hasDeclaredCopyConstructor())
2298 DeclareImplicitCopyConstructor(RD);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002299 if (getLangOpts().CPlusPlus0x && RD->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002300 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002301 } else {
2302 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Alexis Hunt1da39282011-06-24 02:11:39 +00002303 if (!RD->hasDeclaredCopyAssignment())
2304 DeclareImplicitCopyAssignment(RD);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002305 if (getLangOpts().CPlusPlus0x && RD->needsImplicitMoveAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002306 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002307 }
2308
2309 QualType ArgType = CanTy;
2310 if (ConstArg)
2311 ArgType.addConst();
2312 if (VolatileArg)
2313 ArgType.addVolatile();
2314
2315 // This isn't /really/ specified by the standard, but it's implied
2316 // we should be working from an RValue in the case of move to ensure
2317 // that we prefer to bind to rvalue references, and an LValue in the
2318 // case of copy to ensure we don't bind to rvalue references.
2319 // Possibly an XValue is actually correct in the case of move, but
2320 // there is no semantic difference for class types in this restricted
2321 // case.
2322 ExprValueKind VK;
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002323 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002324 VK = VK_LValue;
2325 else
2326 VK = VK_RValue;
2327
2328 NumArgs = 1;
2329 Arg = new (Context) OpaqueValueExpr(SourceLocation(), ArgType, VK);
2330 }
2331
2332 // Create the object argument
2333 QualType ThisTy = CanTy;
2334 if (ConstThis)
2335 ThisTy.addConst();
2336 if (VolatileThis)
2337 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002338 Expr::Classification Classification =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002339 (new (Context) OpaqueValueExpr(SourceLocation(), ThisTy,
2340 RValueThis ? VK_RValue : VK_LValue))->
2341 Classify(Context);
2342
2343 // Now we perform lookup on the name we computed earlier and do overload
2344 // resolution. Lookup is only performed directly into the class since there
2345 // will always be a (possibly implicit) declaration to shadow any others.
2346 OverloadCandidateSet OCS((SourceLocation()));
2347 DeclContext::lookup_iterator I, E;
2348 Result->setConstParamMatch(false);
2349
Alexis Hunt1da39282011-06-24 02:11:39 +00002350 llvm::tie(I, E) = RD->lookup(Name);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002351 assert((I != E) &&
2352 "lookup for a constructor or assignment operator was empty");
2353 for ( ; I != E; ++I) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002354 Decl *Cand = *I;
Alexis Hunt080709f2011-06-23 00:26:20 +00002355
Alexis Hunt1da39282011-06-24 02:11:39 +00002356 if (Cand->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002357 continue;
2358
Alexis Hunt1da39282011-06-24 02:11:39 +00002359 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2360 // FIXME: [namespace.udecl]p15 says that we should only consider a
2361 // using declaration here if it does not match a declaration in the
2362 // derived class. We do not implement this correctly in other cases
2363 // either.
2364 Cand = U->getTargetDecl();
2365
2366 if (Cand->isInvalidDecl())
2367 continue;
2368 }
2369
2370 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002371 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Alexis Hunt1da39282011-06-24 02:11:39 +00002372 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002373 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2374 OCS, true);
Alexis Hunt080709f2011-06-23 00:26:20 +00002375 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002376 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2377 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002378
2379 // Here we're looking for a const parameter to speed up creation of
2380 // implicit copy methods.
2381 if ((SM == CXXCopyAssignment && M->isCopyAssignmentOperator()) ||
2382 (SM == CXXCopyConstructor &&
2383 cast<CXXConstructorDecl>(M)->isCopyConstructor())) {
2384 QualType ArgType = M->getType()->getAs<FunctionProtoType>()->getArgType(0);
Alexis Hunt491ec602011-06-21 23:42:56 +00002385 if (!ArgType->isReferenceType() ||
2386 ArgType->getPointeeType().isConstQualified())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002387 Result->setConstParamMatch(true);
2388 }
Alexis Hunt2949f022011-06-22 02:58:46 +00002389 } else if (FunctionTemplateDecl *Tmpl =
Alexis Hunt1da39282011-06-24 02:11:39 +00002390 dyn_cast<FunctionTemplateDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002391 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2392 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002393 RD, 0, ThisTy, Classification,
2394 llvm::makeArrayRef(&Arg, NumArgs),
Alexis Hunt080709f2011-06-23 00:26:20 +00002395 OCS, true);
2396 else
2397 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002398 0, llvm::makeArrayRef(&Arg, NumArgs),
2399 OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002400 } else {
2401 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002402 }
2403 }
2404
2405 OverloadCandidateSet::iterator Best;
2406 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2407 case OR_Success:
2408 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2409 Result->setSuccess(true);
2410 break;
2411
2412 case OR_Deleted:
2413 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2414 Result->setSuccess(false);
2415 break;
2416
2417 case OR_Ambiguous:
2418 case OR_No_Viable_Function:
2419 Result->setMethod(0);
2420 Result->setSuccess(false);
2421 break;
2422 }
2423
2424 return Result;
2425}
2426
2427/// \brief Look up the default constructor for the given class.
2428CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002429 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002430 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2431 false, false);
2432
2433 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002434}
2435
Alexis Hunt491ec602011-06-21 23:42:56 +00002436/// \brief Look up the copying constructor for the given class.
2437CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
2438 unsigned Quals,
2439 bool *ConstParamMatch) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002440 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2441 "non-const, non-volatile qualifiers for copy ctor arg");
2442 SpecialMemberOverloadResult *Result =
2443 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2444 Quals & Qualifiers::Volatile, false, false, false);
2445
2446 if (ConstParamMatch)
2447 *ConstParamMatch = Result->hasConstParamMatch();
2448
2449 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2450}
2451
Sebastian Redl22653ba2011-08-30 19:58:05 +00002452/// \brief Look up the moving constructor for the given class.
2453CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class) {
2454 SpecialMemberOverloadResult *Result =
2455 LookupSpecialMember(Class, CXXMoveConstructor, false,
2456 false, false, false, false);
2457
2458 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2459}
2460
Douglas Gregor52b72822010-07-02 23:12:18 +00002461/// \brief Look up the constructors for the given class.
2462DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002463 // If the implicit constructors have not yet been declared, do so now.
Douglas Gregor9672f922010-07-03 00:47:00 +00002464 if (CanDeclareSpecialMemberFunction(Context, Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00002465 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002466 DeclareImplicitDefaultConstructor(Class);
2467 if (!Class->hasDeclaredCopyConstructor())
2468 DeclareImplicitCopyConstructor(Class);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002469 if (getLangOpts().CPlusPlus0x && Class->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002470 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00002471 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002472
Douglas Gregor52b72822010-07-02 23:12:18 +00002473 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2474 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2475 return Class->lookup(Name);
2476}
2477
Alexis Hunt491ec602011-06-21 23:42:56 +00002478/// \brief Look up the copying assignment operator for the given class.
2479CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2480 unsigned Quals, bool RValueThis,
2481 unsigned ThisQuals,
2482 bool *ConstParamMatch) {
2483 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2484 "non-const, non-volatile qualifiers for copy assignment arg");
2485 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2486 "non-const, non-volatile qualifiers for copy assignment this");
2487 SpecialMemberOverloadResult *Result =
2488 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2489 Quals & Qualifiers::Volatile, RValueThis,
2490 ThisQuals & Qualifiers::Const,
2491 ThisQuals & Qualifiers::Volatile);
2492
2493 if (ConstParamMatch)
2494 *ConstParamMatch = Result->hasConstParamMatch();
2495
2496 return Result->getMethod();
2497}
2498
Sebastian Redl22653ba2011-08-30 19:58:05 +00002499/// \brief Look up the moving assignment operator for the given class.
2500CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
2501 bool RValueThis,
2502 unsigned ThisQuals) {
2503 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2504 "non-const, non-volatile qualifiers for copy assignment this");
2505 SpecialMemberOverloadResult *Result =
2506 LookupSpecialMember(Class, CXXMoveAssignment, false, false, RValueThis,
2507 ThisQuals & Qualifiers::Const,
2508 ThisQuals & Qualifiers::Volatile);
2509
2510 return Result->getMethod();
2511}
2512
Douglas Gregore71edda2010-07-01 22:47:18 +00002513/// \brief Look for the destructor of the given class.
2514///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00002515/// During semantic analysis, this routine should be used in lieu of
2516/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00002517///
2518/// \returns The destructor for this class.
2519CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002520 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2521 false, false, false,
2522 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00002523}
2524
Richard Smithbcc22fc2012-03-09 08:00:36 +00002525/// LookupLiteralOperator - Determine which literal operator should be used for
2526/// a user-defined literal, per C++11 [lex.ext].
2527///
2528/// Normal overload resolution is not used to select which literal operator to
2529/// call for a user-defined literal. Look up the provided literal operator name,
2530/// and filter the results to the appropriate set for the given argument types.
2531Sema::LiteralOperatorLookupResult
2532Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2533 ArrayRef<QualType> ArgTys,
2534 bool AllowRawAndTemplate) {
2535 LookupName(R, S);
2536 assert(R.getResultKind() != LookupResult::Ambiguous &&
2537 "literal operator lookup can't be ambiguous");
2538
2539 // Filter the lookup results appropriately.
2540 LookupResult::Filter F = R.makeFilter();
2541
2542 bool FoundTemplate = false;
2543 bool FoundRaw = false;
2544 bool FoundExactMatch = false;
2545
2546 while (F.hasNext()) {
2547 Decl *D = F.next();
2548 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2549 D = USD->getTargetDecl();
2550
2551 bool IsTemplate = isa<FunctionTemplateDecl>(D);
2552 bool IsRaw = false;
2553 bool IsExactMatch = false;
2554
2555 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2556 if (FD->getNumParams() == 1 &&
2557 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2558 IsRaw = true;
2559 else {
2560 IsExactMatch = true;
2561 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2562 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2563 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2564 IsExactMatch = false;
2565 break;
2566 }
2567 }
2568 }
2569 }
2570
2571 if (IsExactMatch) {
2572 FoundExactMatch = true;
2573 AllowRawAndTemplate = false;
2574 if (FoundRaw || FoundTemplate) {
2575 // Go through again and remove the raw and template decls we've
2576 // already found.
2577 F.restart();
2578 FoundRaw = FoundTemplate = false;
2579 }
2580 } else if (AllowRawAndTemplate && (IsTemplate || IsRaw)) {
2581 FoundTemplate |= IsTemplate;
2582 FoundRaw |= IsRaw;
2583 } else {
2584 F.erase();
2585 }
2586 }
2587
2588 F.done();
2589
2590 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2591 // parameter type, that is used in preference to a raw literal operator
2592 // or literal operator template.
2593 if (FoundExactMatch)
2594 return LOLR_Cooked;
2595
2596 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2597 // operator template, but not both.
2598 if (FoundRaw && FoundTemplate) {
2599 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
2600 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2601 Decl *D = *I;
2602 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2603 D = USD->getTargetDecl();
2604 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2605 D = FunTmpl->getTemplatedDecl();
2606 NoteOverloadCandidate(cast<FunctionDecl>(D));
2607 }
2608 return LOLR_Error;
2609 }
2610
2611 if (FoundRaw)
2612 return LOLR_Raw;
2613
2614 if (FoundTemplate)
2615 return LOLR_Template;
2616
2617 // Didn't find anything we could use.
2618 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2619 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
2620 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRawAndTemplate;
2621 return LOLR_Error;
2622}
2623
John McCall8fe68082010-01-26 07:16:45 +00002624void ADLResult::insert(NamedDecl *New) {
2625 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2626
2627 // If we haven't yet seen a decl for this key, or the last decl
2628 // was exactly this one, we're done.
2629 if (Old == 0 || Old == New) {
2630 Old = New;
2631 return;
2632 }
2633
2634 // Otherwise, decide which is a more recent redeclaration.
2635 FunctionDecl *OldFD, *NewFD;
2636 if (isa<FunctionTemplateDecl>(New)) {
2637 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2638 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2639 } else {
2640 OldFD = cast<FunctionDecl>(Old);
2641 NewFD = cast<FunctionDecl>(New);
2642 }
2643
2644 FunctionDecl *Cursor = NewFD;
2645 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002646 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00002647
2648 // If we got to the end without finding OldFD, OldFD is the newer
2649 // declaration; leave things as they are.
2650 if (!Cursor) return;
2651
2652 // If we do find OldFD, then NewFD is newer.
2653 if (Cursor == OldFD) break;
2654
2655 // Otherwise, keep looking.
2656 }
2657
2658 Old = New;
2659}
2660
Sebastian Redlc057f422009-10-23 19:23:15 +00002661void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Richard Smithe06a2c12012-02-25 06:24:24 +00002662 SourceLocation Loc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002663 llvm::ArrayRef<Expr *> Args,
Richard Smith02e85f32011-04-14 22:09:26 +00002664 ADLResult &Result,
2665 bool StdNamespaceIsAssociated) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002666 // Find all of the associated namespaces and classes based on the
2667 // arguments we have.
2668 AssociatedNamespaceSet AssociatedNamespaces;
2669 AssociatedClassSet AssociatedClasses;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002670 FindAssociatedClassesAndNamespaces(Args,
John McCallc7e8e792009-08-07 22:18:02 +00002671 AssociatedNamespaces,
2672 AssociatedClasses);
Richard Smith02e85f32011-04-14 22:09:26 +00002673 if (StdNamespaceIsAssociated && StdNamespace)
2674 AssociatedNamespaces.insert(getStdNamespace());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002675
Sebastian Redlc057f422009-10-23 19:23:15 +00002676 QualType T1, T2;
2677 if (Operator) {
2678 T1 = Args[0]->getType();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002679 if (Args.size() >= 2)
Sebastian Redlc057f422009-10-23 19:23:15 +00002680 T2 = Args[1]->getType();
2681 }
2682
Richard Smithe06a2c12012-02-25 06:24:24 +00002683 // Try to complete all associated classes, in case they contain a
2684 // declaration of a friend function.
2685 for (AssociatedClassSet::iterator C = AssociatedClasses.begin(),
2686 CEnd = AssociatedClasses.end();
2687 C != CEnd; ++C)
2688 RequireCompleteType(Loc, Context.getRecordType(*C), 0);
2689
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002690 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002691 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2692 // and let Y be the lookup set produced by argument dependent
2693 // lookup (defined as follows). If X contains [...] then Y is
2694 // empty. Otherwise Y is the set of declarations found in the
2695 // namespaces associated with the argument types as described
2696 // below. The set of declarations found by the lookup of the name
2697 // is the union of X and Y.
2698 //
2699 // Here, we compute Y and add its members to the overloaded
2700 // candidate set.
2701 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00002702 NSEnd = AssociatedNamespaces.end();
2703 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002704 // When considering an associated namespace, the lookup is the
2705 // same as the lookup performed when the associated namespace is
2706 // used as a qualifier (3.4.3.2) except that:
2707 //
2708 // -- Any using-directives in the associated namespace are
2709 // ignored.
2710 //
John McCallc7e8e792009-08-07 22:18:02 +00002711 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002712 // associated classes are visible within their respective
2713 // namespaces even if they are not visible during an ordinary
2714 // lookup (11.4).
2715 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00002716 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00002717 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00002718 // If the only declaration here is an ordinary friend, consider
2719 // it only if it was declared in an associated classes.
2720 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00002721 DeclContext *LexDC = D->getLexicalDeclContext();
2722 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2723 continue;
2724 }
Mike Stump11289f42009-09-09 15:08:12 +00002725
John McCall91f61fc2010-01-26 06:04:06 +00002726 if (isa<UsingShadowDecl>(D))
2727 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002728
John McCall91f61fc2010-01-26 06:04:06 +00002729 if (isa<FunctionDecl>(D)) {
2730 if (Operator &&
2731 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2732 T1, T2, Context))
2733 continue;
John McCall8fe68082010-01-26 07:16:45 +00002734 } else if (!isa<FunctionTemplateDecl>(D))
2735 continue;
2736
2737 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002738 }
2739 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002740}
Douglas Gregor2d435302009-12-30 17:04:44 +00002741
2742//----------------------------------------------------------------------------
2743// Search for all visible declarations.
2744//----------------------------------------------------------------------------
2745VisibleDeclConsumer::~VisibleDeclConsumer() { }
2746
2747namespace {
2748
2749class ShadowContextRAII;
2750
2751class VisibleDeclsRecord {
2752public:
2753 /// \brief An entry in the shadow map, which is optimized to store a
2754 /// single declaration (the common case) but can also store a list
2755 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002756 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00002757
2758private:
2759 /// \brief A mapping from declaration names to the declarations that have
2760 /// this name within a particular scope.
2761 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2762
2763 /// \brief A list of shadow maps, which is used to model name hiding.
2764 std::list<ShadowMap> ShadowMaps;
2765
2766 /// \brief The declaration contexts we have already visited.
2767 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2768
2769 friend class ShadowContextRAII;
2770
2771public:
2772 /// \brief Determine whether we have already visited this context
2773 /// (and, if not, note that we are going to visit that context now).
2774 bool visitedContext(DeclContext *Ctx) {
2775 return !VisitedContexts.insert(Ctx);
2776 }
2777
Douglas Gregor39982192010-08-15 06:18:01 +00002778 bool alreadyVisitedContext(DeclContext *Ctx) {
2779 return VisitedContexts.count(Ctx);
2780 }
2781
Douglas Gregor2d435302009-12-30 17:04:44 +00002782 /// \brief Determine whether the given declaration is hidden in the
2783 /// current scope.
2784 ///
2785 /// \returns the declaration that hides the given declaration, or
2786 /// NULL if no such declaration exists.
2787 NamedDecl *checkHidden(NamedDecl *ND);
2788
2789 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002790 void add(NamedDecl *ND) {
2791 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2792 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002793};
2794
2795/// \brief RAII object that records when we've entered a shadow context.
2796class ShadowContextRAII {
2797 VisibleDeclsRecord &Visible;
2798
2799 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2800
2801public:
2802 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2803 Visible.ShadowMaps.push_back(ShadowMap());
2804 }
2805
2806 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00002807 Visible.ShadowMaps.pop_back();
2808 }
2809};
2810
2811} // end anonymous namespace
2812
Douglas Gregor2d435302009-12-30 17:04:44 +00002813NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002814 // Look through using declarations.
2815 ND = ND->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002816
Douglas Gregor2d435302009-12-30 17:04:44 +00002817 unsigned IDNS = ND->getIdentifierNamespace();
2818 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2819 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2820 SM != SMEnd; ++SM) {
2821 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2822 if (Pos == SM->end())
2823 continue;
2824
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002825 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor2d435302009-12-30 17:04:44 +00002826 IEnd = Pos->second.end();
2827 I != IEnd; ++I) {
2828 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +00002829 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002830 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00002831 Decl::IDNS_ObjCProtocol)))
2832 continue;
2833
2834 // Protocols are in distinct namespaces from everything else.
2835 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2836 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2837 (*I)->getIdentifierNamespace() != IDNS)
2838 continue;
2839
Douglas Gregor09bbc652010-01-14 15:47:35 +00002840 // Functions and function templates in the same scope overload
2841 // rather than hide. FIXME: Look for hiding based on function
2842 // signatures!
Douglas Gregor200c99d2010-01-14 03:35:48 +00002843 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002844 ND->isFunctionOrFunctionTemplate() &&
2845 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002846 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002847
Douglas Gregor2d435302009-12-30 17:04:44 +00002848 // We've found a declaration that hides this one.
2849 return *I;
2850 }
2851 }
2852
2853 return 0;
2854}
2855
2856static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2857 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002858 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002859 VisibleDeclConsumer &Consumer,
2860 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002861 if (!Ctx)
2862 return;
2863
Douglas Gregor2d435302009-12-30 17:04:44 +00002864 // Make sure we don't visit the same context twice.
2865 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2866 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002867
Douglas Gregor7454c562010-07-02 20:37:36 +00002868 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2869 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2870
Douglas Gregor2d435302009-12-30 17:04:44 +00002871 // Enumerate all of the results in this context.
Douglas Gregore57e7522012-01-07 09:11:48 +00002872 llvm::SmallVector<DeclContext *, 2> Contexts;
2873 Ctx->collectAllContexts(Contexts);
2874 for (unsigned I = 0, N = Contexts.size(); I != N; ++I) {
2875 DeclContext *CurCtx = Contexts[I];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002876 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
Douglas Gregor2d435302009-12-30 17:04:44 +00002877 DEnd = CurCtx->decls_end();
2878 D != DEnd; ++D) {
Douglas Gregora3b23b02010-12-09 21:44:02 +00002879 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00002880 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00002881 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002882 Visited.add(ND);
2883 }
Douglas Gregora3b23b02010-12-09 21:44:02 +00002884 }
Douglas Gregor04246572011-02-16 01:39:26 +00002885
Sebastian Redlbd595762010-08-31 20:53:31 +00002886 // Visit transparent contexts and inline namespaces inside this context.
Douglas Gregor2d435302009-12-30 17:04:44 +00002887 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
Sebastian Redlbd595762010-08-31 20:53:31 +00002888 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Douglas Gregor09bbc652010-01-14 15:47:35 +00002889 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002890 Consumer, Visited);
2891 }
2892 }
2893 }
2894
2895 // Traverse using directives for qualified name lookup.
2896 if (QualifiedNameLookup) {
2897 ShadowContextRAII Shadow(Visited);
2898 DeclContext::udir_iterator I, E;
2899 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002900 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002901 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002902 }
2903 }
2904
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002905 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00002906 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00002907 if (!Record->hasDefinition())
2908 return;
2909
Douglas Gregor2d435302009-12-30 17:04:44 +00002910 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2911 BEnd = Record->bases_end();
2912 B != BEnd; ++B) {
2913 QualType BaseType = B->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002914
Douglas Gregor2d435302009-12-30 17:04:44 +00002915 // Don't look into dependent bases, because name lookup can't look
2916 // there anyway.
2917 if (BaseType->isDependentType())
2918 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002919
Douglas Gregor2d435302009-12-30 17:04:44 +00002920 const RecordType *Record = BaseType->getAs<RecordType>();
2921 if (!Record)
2922 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002923
Douglas Gregor2d435302009-12-30 17:04:44 +00002924 // FIXME: It would be nice to be able to determine whether referencing
2925 // a particular member would be ambiguous. For example, given
2926 //
2927 // struct A { int member; };
2928 // struct B { int member; };
2929 // struct C : A, B { };
2930 //
2931 // void f(C *c) { c->### }
2932 //
2933 // accessing 'member' would result in an ambiguity. However, we
2934 // could be smart enough to qualify the member with the base
2935 // class, e.g.,
2936 //
2937 // c->B::member
2938 //
2939 // or
2940 //
2941 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002942
Douglas Gregor2d435302009-12-30 17:04:44 +00002943 // Find results in this base class (and its bases).
2944 ShadowContextRAII Shadow(Visited);
2945 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002946 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002947 }
2948 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002949
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002950 // Traverse the contexts of Objective-C classes.
2951 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2952 // Traverse categories.
2953 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2954 Category; Category = Category->getNextClassCategory()) {
2955 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002956 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002957 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002958 }
2959
2960 // Traverse protocols.
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002961 for (ObjCInterfaceDecl::all_protocol_iterator
2962 I = IFace->all_referenced_protocol_begin(),
2963 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002964 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002965 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002966 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002967 }
2968
2969 // Traverse the superclass.
2970 if (IFace->getSuperClass()) {
2971 ShadowContextRAII Shadow(Visited);
2972 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002973 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002974 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002975
Douglas Gregor0b59e802010-04-19 18:02:19 +00002976 // If there is an implementation, traverse it. We do this to find
2977 // synthesized ivars.
2978 if (IFace->getImplementation()) {
2979 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002980 LookupVisibleDecls(IFace->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00002981 QualifiedNameLookup, true, Consumer, Visited);
2982 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002983 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2984 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2985 E = Protocol->protocol_end(); I != E; ++I) {
2986 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002987 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002988 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002989 }
2990 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2991 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2992 E = Category->protocol_end(); I != E; ++I) {
2993 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002994 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002995 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002996 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002997
Douglas Gregor0b59e802010-04-19 18:02:19 +00002998 // If there is an implementation, traverse it.
2999 if (Category->getImplementation()) {
3000 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003001 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00003002 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003003 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003004 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003005}
3006
3007static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3008 UnqualUsingDirectiveSet &UDirs,
3009 VisibleDeclConsumer &Consumer,
3010 VisibleDeclsRecord &Visited) {
3011 if (!S)
3012 return;
3013
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003014 if (!S->getEntity() ||
3015 (!S->getParent() &&
Douglas Gregor39982192010-08-15 06:18:01 +00003016 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003017 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
3018 // Walk through the declarations in this Scope.
3019 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
3020 D != DEnd; ++D) {
John McCall48871652010-08-21 09:40:31 +00003021 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor4a814562011-12-14 16:03:29 +00003022 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003023 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003024 Visited.add(ND);
3025 }
3026 }
3027 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003028
Douglas Gregor66230062010-03-15 14:33:29 +00003029 // FIXME: C++ [temp.local]p8
Douglas Gregor2d435302009-12-30 17:04:44 +00003030 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00003031 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003032 // Look into this scope's declaration context, along with any of its
3033 // parent lookup contexts (e.g., enclosing classes), up to the point
3034 // where we hit the context stored in the next outer scope.
3035 Entity = (DeclContext *)S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00003036 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003037
Douglas Gregorea166062010-03-15 15:26:48 +00003038 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00003039 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003040 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3041 if (Method->isInstanceMethod()) {
3042 // For instance methods, look for ivars in the method's interface.
3043 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3044 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003045 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003046 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Fariborz Jahanian97d744b2011-08-31 22:24:06 +00003047 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003048 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003049 }
3050
3051 // We've already performed all of the name lookup that we need
3052 // to for Objective-C methods; the next context will be the
3053 // outer scope.
3054 break;
3055 }
3056
Douglas Gregor2d435302009-12-30 17:04:44 +00003057 if (Ctx->isFunctionOrMethod())
3058 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003059
3060 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003061 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003062 }
3063 } else if (!S->getParent()) {
3064 // Look into the translation unit scope. We walk through the translation
3065 // unit's declaration context, because the Scope itself won't have all of
3066 // the declarations if we loaded a precompiled header.
3067 // FIXME: We would like the translation unit's Scope object to point to the
3068 // translation unit, so we don't need this special "if" branch. However,
3069 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003070 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00003071 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003072 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00003073 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003074 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003075 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003076 }
3077
Douglas Gregor2d435302009-12-30 17:04:44 +00003078 if (Entity) {
3079 // Lookup visible declarations in any namespaces found by using
3080 // directives.
3081 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
3082 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
3083 for (; UI != UEnd; ++UI)
3084 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003085 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003086 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003087 }
3088
3089 // Lookup names in the parent scope.
3090 ShadowContextRAII Shadow(Visited);
3091 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3092}
3093
3094void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003095 VisibleDeclConsumer &Consumer,
3096 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003097 // Determine the set of using directives available during
3098 // unqualified name lookup.
3099 Scope *Initial = S;
3100 UnqualUsingDirectiveSet UDirs;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003101 if (getLangOpts().CPlusPlus) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003102 // Find the first namespace or translation-unit scope.
3103 while (S && !isNamespaceOrTranslationUnitScope(S))
3104 S = S->getParent();
3105
3106 UDirs.visitScopeChain(Initial, S);
3107 }
3108 UDirs.done();
3109
3110 // Look for visible declarations.
3111 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3112 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003113 if (!IncludeGlobalScope)
3114 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003115 ShadowContextRAII Shadow(Visited);
3116 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3117}
3118
3119void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003120 VisibleDeclConsumer &Consumer,
3121 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003122 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3123 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003124 if (!IncludeGlobalScope)
3125 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003126 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003127 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003128 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003129}
3130
Chris Lattner43e7f312011-02-18 02:08:43 +00003131/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003132/// If GnuLabelLoc is a valid source location, then this is a definition
3133/// of an __label__ label name, otherwise it is a normal label definition
3134/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003135LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003136 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003137 // Do a lookup to see if we have a label with this name already.
Chris Lattner43e7f312011-02-18 02:08:43 +00003138 NamedDecl *Res = 0;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003139
3140 if (GnuLabelLoc.isValid()) {
3141 // Local label definitions always shadow existing labels.
3142 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3143 Scope *S = CurScope;
3144 PushOnScopeChains(Res, S, true);
3145 return cast<LabelDecl>(Res);
3146 }
3147
3148 // Not a GNU local label.
3149 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3150 // If we found a label, check to see if it is in the same context as us.
3151 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003152 if (Res && Res->getDeclContext() != CurContext)
3153 Res = 0;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003154 if (Res == 0) {
3155 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003156 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3157 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003158 assert(S && "Not in a function?");
3159 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003160 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003161 return cast<LabelDecl>(Res);
3162}
3163
3164//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003165// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003166//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003167
3168namespace {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003169
3170typedef llvm::StringMap<TypoCorrection, llvm::BumpPtrAllocator> TypoResultsMap;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003171typedef std::map<unsigned, TypoResultsMap *> TypoEditDistanceMap;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003172
3173static const unsigned MaxTypoDistanceResultSets = 5;
3174
Douglas Gregor2d435302009-12-30 17:04:44 +00003175class TypoCorrectionConsumer : public VisibleDeclConsumer {
3176 /// \brief The name written that is a typo in the source.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003177 StringRef Typo;
Douglas Gregor2d435302009-12-30 17:04:44 +00003178
3179 /// \brief The results found that have the smallest edit distance
3180 /// found (so far) with the typo name.
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003181 ///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003182 /// The pointer value being set to the current DeclContext indicates
3183 /// whether there is a keyword with this name.
3184 TypoEditDistanceMap BestResults;
Douglas Gregor2d435302009-12-30 17:04:44 +00003185
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003186 Sema &SemaRef;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003187
Douglas Gregor2d435302009-12-30 17:04:44 +00003188public:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003189 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003190 : Typo(Typo->getName()),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003191 SemaRef(SemaRef) { }
Douglas Gregor2d435302009-12-30 17:04:44 +00003192
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003193 ~TypoCorrectionConsumer() {
3194 for (TypoEditDistanceMap::iterator I = BestResults.begin(),
3195 IEnd = BestResults.end();
3196 I != IEnd;
3197 ++I)
3198 delete I->second;
3199 }
3200
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003201 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3202 bool InBaseClass);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003203 void FoundName(StringRef Name);
3204 void addKeywordResult(StringRef Keyword);
3205 void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003206 NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003207 void addCorrection(TypoCorrection Correction);
Douglas Gregor2d435302009-12-30 17:04:44 +00003208
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003209 typedef TypoResultsMap::iterator result_iterator;
3210 typedef TypoEditDistanceMap::iterator distance_iterator;
3211 distance_iterator begin() { return BestResults.begin(); }
3212 distance_iterator end() { return BestResults.end(); }
3213 void erase(distance_iterator I) { BestResults.erase(I); }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003214 unsigned size() const { return BestResults.size(); }
3215 bool empty() const { return BestResults.empty(); }
Douglas Gregor2d435302009-12-30 17:04:44 +00003216
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003217 TypoCorrection &operator[](StringRef Name) {
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003218 return (*BestResults.begin()->second)[Name];
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003219 }
3220
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003221 unsigned getBestEditDistance(bool Normalized) {
3222 if (BestResults.empty())
3223 return (std::numeric_limits<unsigned>::max)();
3224
3225 unsigned BestED = BestResults.begin()->first;
3226 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003227 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003228};
3229
3230}
3231
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003232void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003233 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003234 // Don't consider hidden names for typo correction.
3235 if (Hiding)
3236 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003237
Douglas Gregor2d435302009-12-30 17:04:44 +00003238 // Only consider entities with identifiers for names, ignoring
3239 // special names (constructors, overloaded operators, selectors,
3240 // etc.).
3241 IdentifierInfo *Name = ND->getIdentifier();
3242 if (!Name)
3243 return;
3244
Douglas Gregor57756ea2010-10-14 22:11:03 +00003245 FoundName(Name->getName());
3246}
3247
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003248void TypoCorrectionConsumer::FoundName(StringRef Name) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003249 // Use a simple length-based heuristic to determine the minimum possible
3250 // edit distance. If the minimum isn't good enough, bail out early.
3251 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003252 if (MinED && Typo.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00003253 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003254
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003255 // Compute an upper bound on the allowable edit distance, so that the
3256 // edit-distance algorithm can short-circuit.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003257 unsigned UpperBound = (Typo.size() + 2) / 3;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003258
Douglas Gregor2d435302009-12-30 17:04:44 +00003259 // Compute the edit distance between the typo and the name of this
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003260 // entity, and add the identifier to the list of results.
3261 addName(Name, NULL, Typo.edit_distance(Name, true, UpperBound));
Douglas Gregor2d435302009-12-30 17:04:44 +00003262}
3263
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003264void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003265 // Compute the edit distance between the typo and this keyword,
3266 // and add the keyword to the list of results.
3267 addName(Keyword, NULL, Typo.edit_distance(Keyword), NULL, true);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003268}
3269
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003270void TypoCorrectionConsumer::addName(StringRef Name,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003271 NamedDecl *ND,
3272 unsigned Distance,
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003273 NestedNameSpecifier *NNS,
3274 bool isKeyword) {
3275 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
3276 if (isKeyword) TC.makeKeyword();
3277 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003278}
3279
3280void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003281 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003282 TypoResultsMap *& Map = BestResults[Correction.getEditDistance(false)];
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003283 if (!Map)
3284 Map = new TypoResultsMap;
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003285
3286 TypoCorrection &CurrentCorrection = (*Map)[Name];
3287 if (!CurrentCorrection ||
3288 // FIXME: The following should be rolled up into an operator< on
3289 // TypoCorrection with a more principled definition.
3290 CurrentCorrection.isKeyword() < Correction.isKeyword() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00003291 Correction.getAsString(SemaRef.getLangOpts()) <
3292 CurrentCorrection.getAsString(SemaRef.getLangOpts()))
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003293 CurrentCorrection = Correction;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003294
3295 while (BestResults.size() > MaxTypoDistanceResultSets) {
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003296 TypoEditDistanceMap::iterator Last = BestResults.end();
3297 --Last;
3298 delete Last->second;
3299 BestResults.erase(Last);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003300 }
3301}
3302
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003303// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3304// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3305// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3306static void getNestedNameSpecifierIdentifiers(
3307 NestedNameSpecifier *NNS,
3308 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3309 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3310 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3311 else
3312 Identifiers.clear();
3313
3314 const IdentifierInfo *II = NULL;
3315
3316 switch (NNS->getKind()) {
3317 case NestedNameSpecifier::Identifier:
3318 II = NNS->getAsIdentifier();
3319 break;
3320
3321 case NestedNameSpecifier::Namespace:
3322 if (NNS->getAsNamespace()->isAnonymousNamespace())
3323 return;
3324 II = NNS->getAsNamespace()->getIdentifier();
3325 break;
3326
3327 case NestedNameSpecifier::NamespaceAlias:
3328 II = NNS->getAsNamespaceAlias()->getIdentifier();
3329 break;
3330
3331 case NestedNameSpecifier::TypeSpecWithTemplate:
3332 case NestedNameSpecifier::TypeSpec:
3333 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3334 break;
3335
3336 case NestedNameSpecifier::Global:
3337 return;
3338 }
3339
3340 if (II)
3341 Identifiers.push_back(II);
3342}
3343
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003344namespace {
3345
3346class SpecifierInfo {
3347 public:
3348 DeclContext* DeclCtx;
3349 NestedNameSpecifier* NameSpecifier;
3350 unsigned EditDistance;
3351
3352 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3353 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3354};
3355
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003356typedef SmallVector<DeclContext*, 4> DeclContextList;
3357typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003358
3359class NamespaceSpecifierSet {
3360 ASTContext &Context;
3361 DeclContextList CurContextChain;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003362 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3363 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003364 bool isSorted;
3365
3366 SpecifierInfoList Specifiers;
3367 llvm::SmallSetVector<unsigned, 4> Distances;
3368 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3369
3370 /// \brief Helper for building the list of DeclContexts between the current
3371 /// context and the top of the translation unit
3372 static DeclContextList BuildContextChain(DeclContext *Start);
3373
3374 void SortNamespaces();
3375
3376 public:
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003377 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3378 CXXScopeSpec *CurScopeSpec)
Benjamin Kramerde1d6232011-07-05 09:46:31 +00003379 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003380 isSorted(true) {
3381 if (CurScopeSpec && CurScopeSpec->getScopeRep())
3382 getNestedNameSpecifierIdentifiers(CurScopeSpec->getScopeRep(),
3383 CurNameSpecifierIdentifiers);
3384 // Build the list of identifiers that would be used for an absolute
3385 // (from the global context) NestedNameSpecifier refering to the current
3386 // context.
3387 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3388 CEnd = CurContextChain.rend();
3389 C != CEnd; ++C) {
3390 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3391 CurContextIdentifiers.push_back(ND->getIdentifier());
3392 }
3393 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003394
3395 /// \brief Add the namespace to the set, computing the corresponding
3396 /// NestedNameSpecifier and its distance in the process.
3397 void AddNamespace(NamespaceDecl *ND);
3398
3399 typedef SpecifierInfoList::iterator iterator;
3400 iterator begin() {
3401 if (!isSorted) SortNamespaces();
3402 return Specifiers.begin();
3403 }
3404 iterator end() { return Specifiers.end(); }
3405};
3406
3407}
3408
3409DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003410 assert(Start && "Bulding a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003411 DeclContextList Chain;
3412 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3413 DC = DC->getLookupParent()) {
3414 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3415 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3416 !(ND && ND->isAnonymousNamespace()))
3417 Chain.push_back(DC->getPrimaryContext());
3418 }
3419 return Chain;
3420}
3421
3422void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003423 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003424 sortedDistances.append(Distances.begin(), Distances.end());
3425
3426 if (sortedDistances.size() > 1)
3427 std::sort(sortedDistances.begin(), sortedDistances.end());
3428
3429 Specifiers.clear();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003430 for (SmallVector<unsigned, 4>::iterator DI = sortedDistances.begin(),
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003431 DIEnd = sortedDistances.end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003432 DI != DIEnd; ++DI) {
3433 SpecifierInfoList &SpecList = DistanceMap[*DI];
3434 Specifiers.append(SpecList.begin(), SpecList.end());
3435 }
3436
3437 isSorted = true;
3438}
3439
3440void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003441 DeclContext *Ctx = cast<DeclContext>(ND);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003442 NestedNameSpecifier *NNS = NULL;
3443 unsigned NumSpecifiers = 0;
3444 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003445 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003446
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003447 // Eliminate common elements from the two DeclContext chains.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003448 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3449 CEnd = CurContextChain.rend();
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003450 C != CEnd && !NamespaceDeclChain.empty() &&
3451 NamespaceDeclChain.back() == *C; ++C) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003452 NamespaceDeclChain.pop_back();
3453 }
3454
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003455 // Add an explicit leading '::' specifier if needed.
3456 if (NamespaceDecl *ND =
Kaelyn Uhrain618f97c2012-02-15 22:59:03 +00003457 NamespaceDeclChain.empty() ? NULL :
3458 dyn_cast_or_null<NamespaceDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003459 IdentifierInfo *Name = ND->getIdentifier();
3460 if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3461 Name) != CurContextIdentifiers.end() ||
3462 std::find(CurNameSpecifierIdentifiers.begin(),
3463 CurNameSpecifierIdentifiers.end(),
3464 Name) != CurNameSpecifierIdentifiers.end()) {
3465 NamespaceDeclChain = FullNamespaceDeclChain;
3466 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3467 }
3468 }
3469
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003470 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3471 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3472 CEnd = NamespaceDeclChain.rend();
3473 C != CEnd; ++C) {
3474 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3475 if (ND) {
3476 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3477 ++NumSpecifiers;
3478 }
3479 }
3480
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003481 // If the built NestedNameSpecifier would be replacing an existing
3482 // NestedNameSpecifier, use the number of component identifiers that
3483 // would need to be changed as the edit distance instead of the number
3484 // of components in the built NestedNameSpecifier.
3485 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3486 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3487 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3488 NumSpecifiers = llvm::ComputeEditDistance(
3489 llvm::ArrayRef<const IdentifierInfo*>(CurNameSpecifierIdentifiers),
3490 llvm::ArrayRef<const IdentifierInfo*>(NewNameSpecifierIdentifiers));
3491 }
3492
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003493 isSorted = false;
3494 Distances.insert(NumSpecifiers);
3495 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003496}
3497
Douglas Gregord507d772010-10-20 03:06:34 +00003498/// \brief Perform name lookup for a possible result for typo correction.
3499static void LookupPotentialTypoResult(Sema &SemaRef,
3500 LookupResult &Res,
3501 IdentifierInfo *Name,
3502 Scope *S, CXXScopeSpec *SS,
3503 DeclContext *MemberContext,
3504 bool EnteringContext,
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003505 bool isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00003506 Res.suppressDiagnostics();
3507 Res.clear();
3508 Res.setLookupName(Name);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003509 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00003510 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003511 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00003512 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3513 Res.addDecl(Ivar);
3514 Res.resolveKind();
3515 return;
3516 }
3517 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003518
Douglas Gregord507d772010-10-20 03:06:34 +00003519 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3520 Res.addDecl(Prop);
3521 Res.resolveKind();
3522 return;
3523 }
3524 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003525
Douglas Gregord507d772010-10-20 03:06:34 +00003526 SemaRef.LookupQualifiedName(Res, MemberContext);
3527 return;
3528 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003529
3530 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00003531 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003532
Douglas Gregord507d772010-10-20 03:06:34 +00003533 // Fake ivar lookup; this should really be part of
3534 // LookupParsedName.
3535 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3536 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003537 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00003538 (Res.isSingleResult() &&
3539 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003540 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00003541 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3542 Res.addDecl(IV);
3543 Res.resolveKind();
3544 }
3545 }
3546 }
3547}
3548
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003549/// \brief Add keywords to the consumer as possible typo corrections.
3550static void AddKeywordsToConsumer(Sema &SemaRef,
3551 TypoCorrectionConsumer &Consumer,
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003552 Scope *S, CorrectionCandidateCallback &CCC) {
3553 if (CCC.WantObjCSuper)
3554 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003555
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003556 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003557 // Add type-specifier keywords to the set of results.
3558 const char *CTypeSpecs[] = {
3559 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00003560 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003561 "_Complex", "_Imaginary",
3562 // storage-specifiers as well
3563 "extern", "inline", "static", "typedef"
3564 };
3565
3566 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3567 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3568 Consumer.addKeywordResult(CTypeSpecs[I]);
3569
David Blaikiebbafb8a2012-03-11 07:00:24 +00003570 if (SemaRef.getLangOpts().C99)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003571 Consumer.addKeywordResult("restrict");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003572 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003573 Consumer.addKeywordResult("bool");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003574 else if (SemaRef.getLangOpts().C99)
Douglas Gregor3b22a882011-07-01 21:27:45 +00003575 Consumer.addKeywordResult("_Bool");
3576
David Blaikiebbafb8a2012-03-11 07:00:24 +00003577 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003578 Consumer.addKeywordResult("class");
3579 Consumer.addKeywordResult("typename");
3580 Consumer.addKeywordResult("wchar_t");
3581
David Blaikiebbafb8a2012-03-11 07:00:24 +00003582 if (SemaRef.getLangOpts().CPlusPlus0x) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003583 Consumer.addKeywordResult("char16_t");
3584 Consumer.addKeywordResult("char32_t");
3585 Consumer.addKeywordResult("constexpr");
3586 Consumer.addKeywordResult("decltype");
3587 Consumer.addKeywordResult("thread_local");
3588 }
3589 }
3590
David Blaikiebbafb8a2012-03-11 07:00:24 +00003591 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003592 Consumer.addKeywordResult("typeof");
3593 }
3594
David Blaikiebbafb8a2012-03-11 07:00:24 +00003595 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003596 Consumer.addKeywordResult("const_cast");
3597 Consumer.addKeywordResult("dynamic_cast");
3598 Consumer.addKeywordResult("reinterpret_cast");
3599 Consumer.addKeywordResult("static_cast");
3600 }
3601
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003602 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003603 Consumer.addKeywordResult("sizeof");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003604 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003605 Consumer.addKeywordResult("false");
3606 Consumer.addKeywordResult("true");
3607 }
3608
David Blaikiebbafb8a2012-03-11 07:00:24 +00003609 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003610 const char *CXXExprs[] = {
3611 "delete", "new", "operator", "throw", "typeid"
3612 };
3613 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3614 for (unsigned I = 0; I != NumCXXExprs; ++I)
3615 Consumer.addKeywordResult(CXXExprs[I]);
3616
3617 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3618 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3619 Consumer.addKeywordResult("this");
3620
David Blaikiebbafb8a2012-03-11 07:00:24 +00003621 if (SemaRef.getLangOpts().CPlusPlus0x) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003622 Consumer.addKeywordResult("alignof");
3623 Consumer.addKeywordResult("nullptr");
3624 }
3625 }
3626 }
3627
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003628 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003629 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3630 // Statements.
3631 const char *CStmts[] = {
3632 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3633 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3634 for (unsigned I = 0; I != NumCStmts; ++I)
3635 Consumer.addKeywordResult(CStmts[I]);
3636
David Blaikiebbafb8a2012-03-11 07:00:24 +00003637 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003638 Consumer.addKeywordResult("catch");
3639 Consumer.addKeywordResult("try");
3640 }
3641
3642 if (S && S->getBreakParent())
3643 Consumer.addKeywordResult("break");
3644
3645 if (S && S->getContinueParent())
3646 Consumer.addKeywordResult("continue");
3647
3648 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3649 Consumer.addKeywordResult("case");
3650 Consumer.addKeywordResult("default");
3651 }
3652 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003653 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003654 Consumer.addKeywordResult("namespace");
3655 Consumer.addKeywordResult("template");
3656 }
3657
3658 if (S && S->isClassScope()) {
3659 Consumer.addKeywordResult("explicit");
3660 Consumer.addKeywordResult("friend");
3661 Consumer.addKeywordResult("mutable");
3662 Consumer.addKeywordResult("private");
3663 Consumer.addKeywordResult("protected");
3664 Consumer.addKeywordResult("public");
3665 Consumer.addKeywordResult("virtual");
3666 }
3667 }
3668
David Blaikiebbafb8a2012-03-11 07:00:24 +00003669 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003670 Consumer.addKeywordResult("using");
3671
David Blaikiebbafb8a2012-03-11 07:00:24 +00003672 if (SemaRef.getLangOpts().CPlusPlus0x)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003673 Consumer.addKeywordResult("static_assert");
3674 }
3675 }
3676}
3677
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003678static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3679 TypoCorrection &Candidate) {
3680 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3681 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3682}
3683
Douglas Gregor2d435302009-12-30 17:04:44 +00003684/// \brief Try to "correct" a typo in the source code by finding
3685/// visible declarations whose names are similar to the name that was
3686/// present in the source code.
3687///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003688/// \param TypoName the \c DeclarationNameInfo structure that contains
3689/// the name that was present in the source code along with its location.
3690///
3691/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00003692///
3693/// \param S the scope in which name lookup occurs.
3694///
3695/// \param SS the nested-name-specifier that precedes the name we're
3696/// looking for, if present.
3697///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003698/// \param CCC A CorrectionCandidateCallback object that provides further
3699/// validation of typo correction candidates. It also provides flags for
3700/// determining the set of keywords permitted.
3701///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003702/// \param MemberContext if non-NULL, the context in which to look for
3703/// a member access expression.
3704///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003705/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00003706/// the nested-name-specifier SS.
3707///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003708/// \param OPT when non-NULL, the search for visible declarations will
3709/// also walk the protocols in the qualified interfaces of \p OPT.
3710///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003711/// \returns a \c TypoCorrection containing the corrected name if the typo
3712/// along with information such as the \c NamedDecl where the corrected name
3713/// was declared, and any additional \c NestedNameSpecifier needed to access
3714/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3715TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3716 Sema::LookupNameKind LookupKind,
3717 Scope *S, CXXScopeSpec *SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00003718 CorrectionCandidateCallback &CCC,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003719 DeclContext *MemberContext,
3720 bool EnteringContext,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003721 const ObjCObjectPointerType *OPT) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003722 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003723 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003724
Francois Pichet9c391132011-12-03 15:55:29 +00003725 // In Microsoft mode, don't perform typo correction in a template member
3726 // function dependent context because it interferes with the "lookup into
3727 // dependent bases of class templates" feature.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003728 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichet9c391132011-12-03 15:55:29 +00003729 isa<CXXMethodDecl>(CurContext))
3730 return TypoCorrection();
3731
Douglas Gregor2d435302009-12-30 17:04:44 +00003732 // We only attempt to correct typos for identifiers.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003733 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor2d435302009-12-30 17:04:44 +00003734 if (!Typo)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003735 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00003736
3737 // If the scope specifier itself was invalid, don't try to correct
3738 // typos.
3739 if (SS && SS->isInvalid())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003740 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00003741
3742 // Never try to correct typos during template deduction or
3743 // instantiation.
3744 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003745 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003746
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003747 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003748
3749 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003750
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003751 // If a callback object considers an empty typo correction candidate to be
3752 // viable, assume it does not do any actual validation of the candidates.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003753 TypoCorrection EmptyCorrection;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003754 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003755
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003756 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor87074f12010-10-20 01:32:02 +00003757 bool IsUnqualifiedLookup = false;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003758 DeclContext *QualifiedDC = MemberContext;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003759 if (MemberContext) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003760 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003761
3762 // Look in qualified interfaces.
3763 if (OPT) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003764 for (ObjCObjectPointerType::qual_iterator
3765 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003766 I != E; ++I)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003767 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003768 }
3769 } else if (SS && SS->isSet()) {
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003770 QualifiedDC = computeDeclContext(*SS, EnteringContext);
3771 if (!QualifiedDC)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003772 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003773
Douglas Gregor87074f12010-10-20 01:32:02 +00003774 // Provide a stop gap for files that are just seriously broken. Trying
3775 // to correct all typos can turn into a HUGE performance penalty, causing
3776 // some files to take minutes to get rejected by the parser.
3777 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003778 return TypoCorrection();
Douglas Gregor87074f12010-10-20 01:32:02 +00003779 ++TyposCorrected;
3780
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003781 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
Douglas Gregor2d435302009-12-30 17:04:44 +00003782 } else {
Douglas Gregor87074f12010-10-20 01:32:02 +00003783 IsUnqualifiedLookup = true;
3784 UnqualifiedTyposCorrectedMap::iterator Cached
3785 = UnqualifiedTyposCorrected.find(Typo);
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003786 if (Cached != UnqualifiedTyposCorrected.end()) {
3787 // Add the cached value, unless it's a keyword or fails validation. In the
3788 // keyword case, we'll end up adding the keyword below.
3789 if (Cached->second) {
3790 if (!Cached->second.isKeyword() &&
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003791 isCandidateViable(CCC, Cached->second))
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003792 Consumer.addCorrection(Cached->second);
3793 } else {
3794 // Only honor no-correction cache hits when a callback that will validate
3795 // correction candidates is not being used.
3796 if (!ValidatingCallback)
3797 return TypoCorrection();
3798 }
3799 }
3800 if (Cached == UnqualifiedTyposCorrected.end()) {
Douglas Gregor87074f12010-10-20 01:32:02 +00003801 // Provide a stop gap for files that are just seriously broken. Trying
3802 // to correct all typos can turn into a HUGE performance penalty, causing
3803 // some files to take minutes to get rejected by the parser.
3804 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003805 return TypoCorrection();
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003806 }
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003807 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003808
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003809 if (IsUnqualifiedLookup || (QualifiedDC && QualifiedDC->isNamespace())) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003810 // For unqualified lookup, look through all of the names that we have
3811 // seen in this translation unit.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003812 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003813 for (IdentifierTable::iterator I = Context.Idents.begin(),
3814 IEnd = Context.Idents.end();
3815 I != IEnd; ++I)
3816 Consumer.FoundName(I->getKey());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003817
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003818 // Walk through identifiers in external identifier sources.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003819 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003820 if (IdentifierInfoLookup *External
3821 = Context.Idents.getExternalIdentifierLookup()) {
Dylan Noblesmithe2778992012-02-05 02:12:40 +00003822 OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003823 do {
3824 StringRef Name = Iter->Next();
3825 if (Name.empty())
3826 break;
Douglas Gregor57756ea2010-10-14 22:11:03 +00003827
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003828 Consumer.FoundName(Name);
3829 } while (true);
Douglas Gregor57756ea2010-10-14 22:11:03 +00003830 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003831 }
3832
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00003833 AddKeywordsToConsumer(*this, Consumer, S, CCC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003834
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003835 // If we haven't found anything, we're done.
Douglas Gregor87074f12010-10-20 01:32:02 +00003836 if (Consumer.empty()) {
3837 // If this was an unqualified lookup, note that no correction was found.
3838 if (IsUnqualifiedLookup)
3839 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003840
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003841 return TypoCorrection();
Douglas Gregor87074f12010-10-20 01:32:02 +00003842 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003843
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003844 // Make sure that the user typed at least 3 characters for each correction
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003845 // made. Otherwise, we don't even both looking at the results.
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003846 unsigned ED = Consumer.getBestEditDistance(true);
Douglas Gregor87074f12010-10-20 01:32:02 +00003847 if (ED > 0 && Typo->getName().size() / ED < 3) {
3848 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregoraf1daa92010-10-27 14:20:34 +00003849 if (IsUnqualifiedLookup)
Douglas Gregor87074f12010-10-20 01:32:02 +00003850 (void)UnqualifiedTyposCorrected[Typo];
3851
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003852 return TypoCorrection();
3853 }
3854
3855 // Build the NestedNameSpecifiers for the KnownNamespaces
David Blaikiebbafb8a2012-03-11 07:00:24 +00003856 if (getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003857 // Load any externally-known namespaces.
3858 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003859 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003860 LoadedExternalKnownNamespaces = true;
3861 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
3862 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
3863 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
3864 }
3865
3866 for (llvm::DenseMap<NamespaceDecl*, bool>::iterator
3867 KNI = KnownNamespaces.begin(),
3868 KNIEnd = KnownNamespaces.end();
3869 KNI != KNIEnd; ++KNI)
3870 Namespaces.AddNamespace(KNI->first);
Douglas Gregor87074f12010-10-20 01:32:02 +00003871 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003872
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003873 // Weed out any names that could not be found by name lookup or, if a
3874 // CorrectionCandidateCallback object was provided, failed validation.
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003875 llvm::SmallVector<TypoCorrection, 16> QualifiedResults;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003876 LookupResult TmpRes(*this, TypoName, LookupKind);
3877 TmpRes.suppressDiagnostics();
3878 while (!Consumer.empty()) {
3879 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3880 unsigned ED = DI->first;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003881 for (TypoCorrectionConsumer::result_iterator I = DI->second->begin(),
3882 IEnd = DI->second->end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003883 I != IEnd; /* Increment in loop. */) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003884 // If the item already has been looked up or is a keyword, keep it.
3885 // If a validator callback object was given, drop the correction
3886 // unless it passes validation.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003887 if (I->second.isResolved()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003888 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003889 ++I;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003890 if (!isCandidateViable(CCC, Prev->second))
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003891 DI->second->erase(Prev);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003892 continue;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003893 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003894
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003895 // Perform name lookup on this name.
3896 IdentifierInfo *Name = I->second.getCorrectionAsIdentifierInfo();
3897 LookupPotentialTypoResult(*this, TmpRes, Name, S, SS, MemberContext,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00003898 EnteringContext, CCC.IsObjCIvarLookup);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003899
3900 switch (TmpRes.getResultKind()) {
3901 case LookupResult::NotFound:
3902 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain5a43b462011-09-07 20:25:59 +00003903 case LookupResult::FoundUnresolvedValue:
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003904 QualifiedResults.push_back(I->second);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003905 // We didn't find this name in our scope, or didn't like what we found;
3906 // ignore it.
3907 {
3908 TypoCorrectionConsumer::result_iterator Next = I;
3909 ++Next;
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003910 DI->second->erase(I);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003911 I = Next;
3912 }
3913 break;
3914
3915 case LookupResult::Ambiguous:
3916 // We don't deal with ambiguities.
3917 return TypoCorrection();
3918
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003919 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003920 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003921 // Store all of the Decls for overloaded symbols
3922 for (LookupResult::iterator TRD = TmpRes.begin(),
3923 TRDEnd = TmpRes.end();
3924 TRD != TRDEnd; ++TRD)
3925 I->second.addCorrectionDecl(*TRD);
3926 ++I;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003927 if (!isCandidateViable(CCC, Prev->second))
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003928 DI->second->erase(Prev);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003929 break;
3930 }
3931
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003932 case LookupResult::Found: {
3933 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003934 I->second.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
3935 ++I;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003936 if (!isCandidateViable(CCC, Prev->second))
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003937 DI->second->erase(Prev);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003938 break;
3939 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003940
3941 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003942 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003943
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00003944 if (DI->second->empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003945 Consumer.erase(DI);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003946 else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !ED)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003947 // If there are results in the closest possible bucket, stop
3948 break;
3949
3950 // Only perform the qualified lookups for C++
David Blaikiebbafb8a2012-03-11 07:00:24 +00003951 if (getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003952 TmpRes.suppressDiagnostics();
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003953 for (llvm::SmallVector<TypoCorrection,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003954 16>::iterator QRI = QualifiedResults.begin(),
3955 QRIEnd = QualifiedResults.end();
3956 QRI != QRIEnd; ++QRI) {
3957 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
3958 NIEnd = Namespaces.end();
3959 NI != NIEnd; ++NI) {
3960 DeclContext *Ctx = NI->DeclCtx;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003961
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003962 // FIXME: Stop searching once the namespaces are too far away to create
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003963 // acceptable corrections for this identifier (since the namespaces
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003964 // are sorted in ascending order by edit distance).
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003965
3966 TmpRes.clear();
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003967 TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003968 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
3969
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003970 // Any corrections added below will be validated in subsequent
3971 // iterations of the main while() loop over the Consumer's contents.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003972 switch (TmpRes.getResultKind()) {
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003973 case LookupResult::Found: {
3974 TypoCorrection TC(*QRI);
3975 TC.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
3976 TC.setCorrectionSpecifier(NI->NameSpecifier);
3977 TC.setQualifierDistance(NI->EditDistance);
3978 Consumer.addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003979 break;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003980 }
3981 case LookupResult::FoundOverloaded: {
3982 TypoCorrection TC(*QRI);
3983 TC.setCorrectionSpecifier(NI->NameSpecifier);
3984 TC.setQualifierDistance(NI->EditDistance);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003985 for (LookupResult::iterator TRD = TmpRes.begin(),
3986 TRDEnd = TmpRes.end();
3987 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003988 TC.addCorrectionDecl(*TRD);
3989 Consumer.addCorrection(TC);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003990 break;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003991 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003992 case LookupResult::NotFound:
3993 case LookupResult::NotFoundInCurrentInstantiation:
3994 case LookupResult::Ambiguous:
Kaelyn Uhrain5a43b462011-09-07 20:25:59 +00003995 case LookupResult::FoundUnresolvedValue:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003996 break;
3997 }
3998 }
3999 }
4000 }
4001
4002 QualifiedResults.clear();
4003 }
4004
4005 // No corrections remain...
4006 if (Consumer.empty()) return TypoCorrection();
4007
Douglas Gregor29cdc6b2011-06-28 16:44:39 +00004008 TypoResultsMap &BestResults = *Consumer.begin()->second;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00004009 ED = TypoCorrection::NormalizeEditDistance(Consumer.begin()->first);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004010
4011 if (ED > 0 && Typo->getName().size() / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004012 // If this was an unqualified lookup and we believe the callback
4013 // object wouldn't have filtered out possible corrections, note
4014 // that no correction was found.
4015 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004016 (void)UnqualifiedTyposCorrected[Typo];
4017
4018 return TypoCorrection();
4019 }
4020
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004021 // If only a single name remains, return that result.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004022 if (BestResults.size() == 1) {
4023 const llvm::StringMapEntry<TypoCorrection> &Correction = *(BestResults.begin());
4024 const TypoCorrection &Result = Correction.second;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004025
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00004026 // Don't correct to a keyword that's the same as the typo; the keyword
4027 // wasn't actually in scope.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004028 if (ED == 0 && Result.isKeyword()) return TypoCorrection();
4029
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004030 // Record the correction for unqualified lookup.
4031 if (IsUnqualifiedLookup)
4032 UnqualifiedTyposCorrected[Typo] = Result;
4033
4034 return Result;
4035 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004036 else if (BestResults.size() > 1
4037 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4038 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4039 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4040 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00004041 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004042 && BestResults["super"].isKeyword()) {
4043 // Prefer 'super' when we're completing in a message-receiver
4044 // context.
4045
4046 // Don't correct to a keyword that's the same as the typo; the keyword
4047 // wasn't actually in scope.
4048 if (ED == 0) return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004049
Douglas Gregor87074f12010-10-20 01:32:02 +00004050 // Record the correction for unqualified lookup.
4051 if (IsUnqualifiedLookup)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004052 UnqualifiedTyposCorrected[Typo] = BestResults["super"];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004053
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004054 return BestResults["super"];
Douglas Gregoraf9eb592010-10-15 13:35:25 +00004055 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004056
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004057 // If this was an unqualified lookup and we believe the callback object did
4058 // not filter out possible corrections, note that no correction was found.
4059 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregor87074f12010-10-20 01:32:02 +00004060 (void)UnqualifiedTyposCorrected[Typo];
4061
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004062 return TypoCorrection();
4063}
4064
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004065void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4066 if (!CDecl) return;
4067
4068 if (isKeyword())
4069 CorrectionDecls.clear();
4070
4071 CorrectionDecls.push_back(CDecl);
4072
4073 if (!CorrectionName)
4074 CorrectionName = CDecl->getDeclName();
4075}
4076
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004077std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4078 if (CorrectionNameSpec) {
4079 std::string tmpBuffer;
4080 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4081 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
4082 return PrefixOStream.str() + CorrectionName.getAsString();
4083 }
4084
4085 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00004086}