blob: 41996b3e42001693fcf10ae346599fddb2710e9e [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/Lookup.h"
Douglas Gregor960b5bc2009-01-15 00:26:24 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000017#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
Nick Lewyckyc3921482012-04-03 21:44:08 +000019#include "clang/AST/DeclLookups.h"
Douglas Gregor34074322009-01-14 22:20:51 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000022#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000023#include "clang/AST/ExprCXX.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Douglas Gregor34074322009-01-14 22:20:51 +000025#include "clang/Basic/LangOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Sema/DeclSpec.h"
27#include "clang/Sema/ExternalSemaSource.h"
28#include "clang/Sema/Overload.h"
29#include "clang/Sema/Scope.h"
30#include "clang/Sema/ScopeInfo.h"
31#include "clang/Sema/Sema.h"
32#include "clang/Sema/SemaInternal.h"
33#include "clang/Sema/TemplateDeduction.h"
34#include "clang/Sema/TypoCorrection.h"
Douglas Gregor34074322009-01-14 22:20:51 +000035#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000036#include "llvm/ADT/SetVector.h"
Douglas Gregore254f902009-02-04 00:32:51 +000037#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0afa7f62010-10-14 20:34:08 +000038#include "llvm/ADT/StringMap.h"
Chris Lattner83cfc7c2011-07-18 01:54:02 +000039#include "llvm/ADT/TinyPtrVector.h"
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +000040#include "llvm/ADT/edit_distance.h"
John McCall6538c932009-10-10 05:48:19 +000041#include "llvm/Support/ErrorHandling.h"
Nick Lewycky13668f22012-04-03 20:26:45 +000042#include <algorithm>
43#include <iterator>
Douglas Gregor0afa7f62010-10-14 20:34:08 +000044#include <limits>
Douglas Gregor2d435302009-12-30 17:04:44 +000045#include <list>
Douglas Gregorc2fa1692011-06-28 16:20:02 +000046#include <map>
Nick Lewycky13668f22012-04-03 20:26:45 +000047#include <set>
48#include <utility>
49#include <vector>
Douglas Gregor34074322009-01-14 22:20:51 +000050
51using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000052using namespace sema;
Douglas Gregor34074322009-01-14 22:20:51 +000053
John McCallf6c8a4e2009-11-10 07:01:13 +000054namespace {
55 class UnqualUsingEntry {
56 const DeclContext *Nominated;
57 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000058
John McCallf6c8a4e2009-11-10 07:01:13 +000059 public:
60 UnqualUsingEntry(const DeclContext *Nominated,
61 const DeclContext *CommonAncestor)
62 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
63 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000064
John McCallf6c8a4e2009-11-10 07:01:13 +000065 const DeclContext *getCommonAncestor() const {
66 return CommonAncestor;
67 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000068
John McCallf6c8a4e2009-11-10 07:01:13 +000069 const DeclContext *getNominatedNamespace() const {
70 return Nominated;
71 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000072
John McCallf6c8a4e2009-11-10 07:01:13 +000073 // Sort by the pointer value of the common ancestor.
74 struct Comparator {
75 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
76 return L.getCommonAncestor() < R.getCommonAncestor();
77 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000078
John McCallf6c8a4e2009-11-10 07:01:13 +000079 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
80 return E.getCommonAncestor() < DC;
81 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000082
John McCallf6c8a4e2009-11-10 07:01:13 +000083 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
84 return DC < E.getCommonAncestor();
85 }
86 };
87 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000088
John McCallf6c8a4e2009-11-10 07:01:13 +000089 /// A collection of using directives, as used by C++ unqualified
90 /// lookup.
91 class UnqualUsingDirectiveSet {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000092 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000093
John McCallf6c8a4e2009-11-10 07:01:13 +000094 ListTy list;
95 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000096
John McCallf6c8a4e2009-11-10 07:01:13 +000097 public:
98 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +000099
John McCallf6c8a4e2009-11-10 07:01:13 +0000100 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000101 // C++ [namespace.udir]p1:
John McCallf6c8a4e2009-11-10 07:01:13 +0000102 // During unqualified name lookup, the names appear as if they
103 // were declared in the nearest enclosing namespace which contains
104 // both the using-directive and the nominated namespace.
105 DeclContext *InnermostFileDC
106 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
107 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +0000108
John McCallf6c8a4e2009-11-10 07:01:13 +0000109 for (; S; S = S->getParent()) {
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000110 // C++ [namespace.udir]p1:
111 // A using-directive shall not appear in class scope, but may
112 // appear in namespace scope or in block scope.
Richard Smith05afe5e2012-03-13 03:12:56 +0000113 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000114 if (Ctx && Ctx->isFileContext()) {
115 visit(Ctx, Ctx);
116 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000117 Scope::udir_iterator I = S->using_directives_begin(),
118 End = S->using_directives_end();
John McCallf6c8a4e2009-11-10 07:01:13 +0000119 for (; I != End; ++I)
John McCall48871652010-08-21 09:40:31 +0000120 visit(*I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000121 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000122 }
123 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000124
125 // Visits a context and collect all of its using directives
126 // recursively. Treats all using directives as if they were
127 // declared in the context.
128 //
129 // A given context is only every visited once, so it is important
130 // that contexts be visited from the inside out in order to get
131 // the effective DCs right.
132 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
133 if (!visited.insert(DC))
134 return;
135
136 addUsingDirectives(DC, EffectiveDC);
137 }
138
139 // Visits a using directive and collects all of its using
140 // directives recursively. Treats all using directives as if they
141 // were declared in the effective DC.
142 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
143 DeclContext *NS = UD->getNominatedNamespace();
144 if (!visited.insert(NS))
145 return;
146
147 addUsingDirective(UD, EffectiveDC);
148 addUsingDirectives(NS, EffectiveDC);
149 }
150
151 // Adds all the using directives in a context (and those nominated
152 // by its using directives, transitively) as if they appeared in
153 // the given effective context.
154 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000155 SmallVector<DeclContext*,4> queue;
John McCallf6c8a4e2009-11-10 07:01:13 +0000156 while (true) {
157 DeclContext::udir_iterator I, End;
158 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
159 UsingDirectiveDecl *UD = *I;
160 DeclContext *NS = UD->getNominatedNamespace();
161 if (visited.insert(NS)) {
162 addUsingDirective(UD, EffectiveDC);
163 queue.push_back(NS);
164 }
165 }
166
167 if (queue.empty())
168 return;
169
170 DC = queue.back();
171 queue.pop_back();
172 }
173 }
174
175 // Add a using directive as if it had been declared in the given
176 // context. This helps implement C++ [namespace.udir]p3:
177 // The using-directive is transitive: if a scope contains a
178 // using-directive that nominates a second namespace that itself
179 // contains using-directives, the effect is as if the
180 // using-directives from the second namespace also appeared in
181 // the first.
182 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
183 // Find the common ancestor between the effective context and
184 // the nominated namespace.
185 DeclContext *Common = UD->getNominatedNamespace();
186 while (!Common->Encloses(EffectiveDC))
187 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000188 Common = Common->getPrimaryContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000189
John McCallf6c8a4e2009-11-10 07:01:13 +0000190 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
191 }
192
193 void done() {
194 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
195 }
196
John McCallf6c8a4e2009-11-10 07:01:13 +0000197 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000198
John McCallf6c8a4e2009-11-10 07:01:13 +0000199 const_iterator begin() const { return list.begin(); }
200 const_iterator end() const { return list.end(); }
201
202 std::pair<const_iterator,const_iterator>
203 getNamespacesFor(DeclContext *DC) const {
John McCall9757d032009-11-10 09:20:04 +0000204 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCallf6c8a4e2009-11-10 07:01:13 +0000205 UnqualUsingEntry::Comparator());
206 }
207 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000208}
209
Douglas Gregor889ceb72009-02-03 19:21:40 +0000210// Retrieve the set of identifier namespaces that correspond to a
211// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000212static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
213 bool CPlusPlus,
214 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000215 unsigned IDNS = 0;
216 switch (NameKind) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +0000217 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000218 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000219 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000220 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000221 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000222 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000223 if (Redeclaration)
224 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCallea305ed2009-12-18 10:40:03 +0000225 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000226 break;
227
John McCallb9467b62010-04-24 01:30:58 +0000228 case Sema::LookupOperatorName:
229 // Operator lookup is its own crazy thing; it is not the same
230 // as (e.g.) looking up an operator name for redeclaration.
231 assert(!Redeclaration && "cannot do redeclaration operator lookup");
232 IDNS = Decl::IDNS_NonMemberOperator;
233 break;
234
Douglas Gregor889ceb72009-02-03 19:21:40 +0000235 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000236 if (CPlusPlus) {
237 IDNS = Decl::IDNS_Type;
238
239 // When looking for a redeclaration of a tag name, we add:
240 // 1) TagFriend to find undeclared friend decls
241 // 2) Namespace because they can't "overload" with tag decls.
242 // 3) Tag because it includes class templates, which can't
243 // "overload" with tag decls.
244 if (Redeclaration)
245 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
246 } else {
247 IDNS = Decl::IDNS_Tag;
248 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000249 break;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000250 case Sema::LookupLabel:
251 IDNS = Decl::IDNS_Label;
252 break;
253
Douglas Gregor889ceb72009-02-03 19:21:40 +0000254 case Sema::LookupMemberName:
255 IDNS = Decl::IDNS_Member;
256 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000257 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000258 break;
259
260 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000261 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
262 break;
263
Douglas Gregor889ceb72009-02-03 19:21:40 +0000264 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000265 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000266 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000267
John McCall84d87672009-12-10 09:41:52 +0000268 case Sema::LookupUsingDeclName:
269 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
270 | Decl::IDNS_Member | Decl::IDNS_Using;
271 break;
272
Douglas Gregor79947a22009-04-24 00:11:27 +0000273 case Sema::LookupObjCProtocolName:
274 IDNS = Decl::IDNS_ObjCProtocol;
275 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000276
Douglas Gregor39982192010-08-15 06:18:01 +0000277 case Sema::LookupAnyName:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000278 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor39982192010-08-15 06:18:01 +0000279 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
280 | Decl::IDNS_Type;
281 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000282 }
283 return IDNS;
284}
285
John McCallea305ed2009-12-18 10:40:03 +0000286void LookupResult::configure() {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000287 IDNS = getIDNS(LookupKind, SemaRef.getLangOpts().CPlusPlus,
John McCallea305ed2009-12-18 10:40:03 +0000288 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000289
290 // If we're looking for one of the allocation or deallocation
291 // operators, make sure that the implicitly-declared new and delete
292 // operators can be found.
293 if (!isForRedeclaration()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000294 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000295 case OO_New:
296 case OO_Delete:
297 case OO_Array_New:
298 case OO_Array_Delete:
299 SemaRef.DeclareGlobalNewDelete();
300 break;
301
302 default:
303 break;
304 }
305 }
John McCallea305ed2009-12-18 10:40:03 +0000306}
307
Daniel Dunbar9e19f132012-03-08 01:43:06 +0000308void LookupResult::sanityImpl() const {
309 // Note that this function is never called by NDEBUG builds. See
310 // LookupResult::sanity().
John McCall19c1bfd2010-08-25 05:32:35 +0000311 assert(ResultKind != NotFound || Decls.size() == 0);
312 assert(ResultKind != Found || Decls.size() == 1);
313 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
314 (Decls.size() == 1 &&
315 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
316 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
317 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000318 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
319 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall19c1bfd2010-08-25 05:32:35 +0000320 assert((Paths != NULL) == (ResultKind == Ambiguous &&
321 (Ambiguity == AmbiguousBaseSubobjectTypes ||
322 Ambiguity == AmbiguousBaseSubobjects)));
323}
John McCall19c1bfd2010-08-25 05:32:35 +0000324
John McCall9f3059a2009-10-09 21:13:30 +0000325// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000326void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000327 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000328}
329
Douglas Gregor4a814562011-12-14 16:03:29 +0000330static NamedDecl *getVisibleDecl(NamedDecl *D);
331
332NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
333 return getVisibleDecl(D);
334}
335
John McCall283b9012009-11-22 00:44:51 +0000336/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000337void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000338 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000339
John McCall9f3059a2009-10-09 21:13:30 +0000340 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000341 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000342 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000343 return;
344 }
345
John McCall283b9012009-11-22 00:44:51 +0000346 // If there's a single decl, we need to examine it to decide what
347 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000348 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000349 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
350 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000351 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000352 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000353 ResultKind = FoundUnresolvedValue;
354 return;
355 }
John McCall9f3059a2009-10-09 21:13:30 +0000356
John McCall6538c932009-10-10 05:48:19 +0000357 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000358 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000359
John McCall9f3059a2009-10-09 21:13:30 +0000360 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor13e65872010-08-11 14:45:53 +0000361 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000362
John McCall9f3059a2009-10-09 21:13:30 +0000363 bool Ambiguous = false;
364 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000365 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000366
367 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000368
John McCall9f3059a2009-10-09 21:13:30 +0000369 unsigned I = 0;
370 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000371 NamedDecl *D = Decls[I]->getUnderlyingDecl();
372 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000373
Douglas Gregor13e65872010-08-11 14:45:53 +0000374 // Redeclarations of types via typedef can occur both within a scope
375 // and, through using declarations and directives, across scopes. There is
376 // no ambiguity if they all refer to the same type, so unique based on the
377 // canonical type.
378 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
379 if (!TD->getDeclContext()->isRecord()) {
380 QualType T = SemaRef.Context.getTypeDeclType(TD);
381 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
382 // The type is not unique; pull something off the back and continue
383 // at this index.
384 Decls[I] = Decls[--N];
385 continue;
386 }
387 }
388 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000389
John McCallf0f1cf02009-11-17 07:50:12 +0000390 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000391 // If it's not unique, pull something off the back (and
392 // continue at this index).
393 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000394 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000395 }
396
Douglas Gregor13e65872010-08-11 14:45:53 +0000397 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000398
Douglas Gregor13e65872010-08-11 14:45:53 +0000399 if (isa<UnresolvedUsingValueDecl>(D)) {
400 HasUnresolved = true;
401 } else if (isa<TagDecl>(D)) {
402 if (HasTag)
403 Ambiguous = true;
404 UniqueTagIndex = I;
405 HasTag = true;
406 } else if (isa<FunctionTemplateDecl>(D)) {
407 HasFunction = true;
408 HasFunctionTemplate = true;
409 } else if (isa<FunctionDecl>(D)) {
410 HasFunction = true;
411 } else {
412 if (HasNonFunction)
413 Ambiguous = true;
414 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000415 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000416 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000417 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000418
John McCall9f3059a2009-10-09 21:13:30 +0000419 // C++ [basic.scope.hiding]p2:
420 // A class name or enumeration name can be hidden by the name of
421 // an object, function, or enumerator declared in the same
422 // scope. If a class or enumeration name and an object, function,
423 // or enumerator are declared in the same scope (in any order)
424 // with the same name, the class or enumeration name is hidden
425 // wherever the object, function, or enumerator name is visible.
426 // But it's still an error if there are distinct tag types found,
427 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000428 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000429 (HasFunction || HasNonFunction || HasUnresolved)) {
430 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
431 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
432 Decls[UniqueTagIndex] = Decls[--N];
433 else
434 Ambiguous = true;
435 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000436
John McCall9f3059a2009-10-09 21:13:30 +0000437 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000438
John McCall80053822009-12-03 00:58:24 +0000439 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000440 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000441
John McCall9f3059a2009-10-09 21:13:30 +0000442 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000443 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000444 else if (HasUnresolved)
445 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000446 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000447 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000448 else
John McCall27b18f82009-11-17 02:14:36 +0000449 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000450}
451
John McCall5cebab12009-11-18 07:57:50 +0000452void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000453 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000454 DeclContext::lookup_iterator DI, DE;
455 for (I = P.begin(), E = P.end(); I != E; ++I)
456 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
457 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000458}
459
John McCall5cebab12009-11-18 07:57:50 +0000460void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000461 Paths = new CXXBasePaths;
462 Paths->swap(P);
463 addDeclsFromBasePaths(*Paths);
464 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000465 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000466}
467
John McCall5cebab12009-11-18 07:57:50 +0000468void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000469 Paths = new CXXBasePaths;
470 Paths->swap(P);
471 addDeclsFromBasePaths(*Paths);
472 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000473 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000474}
475
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000476void LookupResult::print(raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000477 Out << Decls.size() << " result(s)";
478 if (isAmbiguous()) Out << ", ambiguous";
479 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000480
John McCall9f3059a2009-10-09 21:13:30 +0000481 for (iterator I = begin(), E = end(); I != E; ++I) {
482 Out << "\n";
483 (*I)->print(Out, 2);
484 }
485}
486
Douglas Gregord3a59182010-02-12 05:48:04 +0000487/// \brief Lookup a builtin function, when name lookup would otherwise
488/// fail.
489static bool LookupBuiltin(Sema &S, LookupResult &R) {
490 Sema::LookupNameKind NameKind = R.getLookupKind();
491
492 // If we didn't find a use of this identifier, and if the identifier
493 // corresponds to a compiler builtin, create the decl object for the builtin
494 // now, injecting it into translation unit scope, and return it.
495 if (NameKind == Sema::LookupOrdinaryName ||
496 NameKind == Sema::LookupRedeclarationWithLinkage) {
497 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
498 if (II) {
499 // If this is a builtin on this (or all) targets, create the decl.
500 if (unsigned BuiltinID = II->getBuiltinID()) {
501 // In C++, we don't have any predefined library functions like
502 // 'malloc'. Instead, we'll just error.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000503 if (S.getLangOpts().CPlusPlus &&
Douglas Gregord3a59182010-02-12 05:48:04 +0000504 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
505 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000506
507 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
508 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000509 R.isForRedeclaration(),
510 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000511 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000512 return true;
513 }
514
515 if (R.isForRedeclaration()) {
516 // If we're redeclaring this function anyway, forget that
517 // this was a builtin at all.
518 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
519 }
520
521 return false;
Douglas Gregord3a59182010-02-12 05:48:04 +0000522 }
523 }
524 }
525
526 return false;
527}
528
Douglas Gregor7454c562010-07-02 20:37:36 +0000529/// \brief Determine whether we can declare a special member function within
530/// the class at this point.
Richard Smith7d125a12012-11-27 21:20:31 +0000531static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +0000532 // We need to have a definition for the class.
533 if (!Class->getDefinition() || Class->isDependentContext())
534 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000535
Douglas Gregor7454c562010-07-02 20:37:36 +0000536 // We can't be in the middle of defining the class.
Richard Smith7d125a12012-11-27 21:20:31 +0000537 return !Class->isBeingDefined();
Douglas Gregor7454c562010-07-02 20:37:36 +0000538}
539
540void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smith7d125a12012-11-27 21:20:31 +0000541 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregora6d69502010-07-02 23:41:54 +0000542 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000543
544 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000545 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000546 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000547
Douglas Gregora6d69502010-07-02 23:41:54 +0000548 // If the copy constructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000549 if (Class->needsImplicitCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +0000550 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000551
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000552 // If the copy assignment operator has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000553 if (Class->needsImplicitCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000554 DeclareImplicitCopyAssignment(Class);
555
David Blaikiebbafb8a2012-03-11 07:00:24 +0000556 if (getLangOpts().CPlusPlus0x) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000557 // If the move constructor has not yet been declared, do so now.
558 if (Class->needsImplicitMoveConstructor())
559 DeclareImplicitMoveConstructor(Class); // might not actually do it
560
561 // If the move assignment operator has not yet been declared, do so now.
562 if (Class->needsImplicitMoveAssignment())
563 DeclareImplicitMoveAssignment(Class); // might not actually do it
564 }
565
Douglas Gregor7454c562010-07-02 20:37:36 +0000566 // If the destructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000567 if (Class->needsImplicitDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000568 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000569}
570
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000571/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000572/// special member function.
573static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
574 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000575 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000576 case DeclarationName::CXXDestructorName:
577 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000578
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000579 case DeclarationName::CXXOperatorName:
580 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000581
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000582 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000583 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000584 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000585
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000586 return false;
587}
588
589/// \brief If there are any implicit member functions with the given name
590/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000591static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000592 DeclarationName Name,
593 const DeclContext *DC) {
594 if (!DC)
595 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000596
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000597 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000598 case DeclarationName::CXXConstructorName:
599 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith7d125a12012-11-27 21:20:31 +0000600 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000601 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000602 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000603 S.DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +0000604 if (Record->needsImplicitCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000605 S.DeclareImplicitCopyConstructor(Class);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000606 if (S.getLangOpts().CPlusPlus0x &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000607 Record->needsImplicitMoveConstructor())
608 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000609 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000610 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000611
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000612 case DeclarationName::CXXDestructorName:
613 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith2be35f52012-12-01 02:35:44 +0000614 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smith7d125a12012-11-27 21:20:31 +0000615 CanDeclareSpecialMemberFunction(Record))
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000616 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000617 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000618
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000619 case DeclarationName::CXXOperatorName:
620 if (Name.getCXXOverloadedOperator() != OO_Equal)
621 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000622
Sebastian Redl22653ba2011-08-30 19:58:05 +0000623 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smith7d125a12012-11-27 21:20:31 +0000624 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000625 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smith2be35f52012-12-01 02:35:44 +0000626 if (Record->needsImplicitCopyAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000627 S.DeclareImplicitCopyAssignment(Class);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000628 if (S.getLangOpts().CPlusPlus0x &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000629 Record->needsImplicitMoveAssignment())
630 S.DeclareImplicitMoveAssignment(Class);
631 }
632 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000633 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000634
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000635 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000636 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000637 }
638}
Douglas Gregor7454c562010-07-02 20:37:36 +0000639
John McCall9f3059a2009-10-09 21:13:30 +0000640// Adds all qualifying matches for a name within a decl context to the
641// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000642static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000643 bool Found = false;
644
Douglas Gregor7454c562010-07-02 20:37:36 +0000645 // Lazily declare C++ special member functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000646 if (S.getLangOpts().CPlusPlus)
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000647 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000648
Douglas Gregor7454c562010-07-02 20:37:36 +0000649 // Perform lookup into this declaration context.
John McCallf6c8a4e2009-11-10 07:01:13 +0000650 DeclContext::lookup_const_iterator I, E;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000651 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall401982f2010-01-20 21:53:11 +0000652 NamedDecl *D = *I;
Douglas Gregor4a814562011-12-14 16:03:29 +0000653 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000654 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000655 Found = true;
656 }
657 }
John McCall9f3059a2009-10-09 21:13:30 +0000658
Douglas Gregord3a59182010-02-12 05:48:04 +0000659 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
660 return true;
661
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000662 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000663 != DeclarationName::CXXConversionFunctionName ||
664 R.getLookupName().getCXXNameType()->isDependentType() ||
665 !isa<CXXRecordDecl>(DC))
666 return Found;
667
668 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000669 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000670 // name lookup. Instead, any conversion function templates visible in the
671 // context of the use are considered. [...]
672 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000673 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000674 return Found;
675
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +0000676 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
677 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruth3a693b72010-01-31 11:44:02 +0000678 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
679 if (!ConvTemplate)
680 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000681
Chandler Carruth3a693b72010-01-31 11:44:02 +0000682 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000683 // add the conversion function template. When we deduce template
684 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000685 // type of the new declaration with the type of the function template.
686 if (R.isForRedeclaration()) {
687 R.addDecl(ConvTemplate);
688 Found = true;
689 continue;
690 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000691
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000692 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000693 // [...] For each such operator, if argument deduction succeeds
694 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000695 // name lookup.
696 //
697 // When referencing a conversion function for any purpose other than
698 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000699 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000700 // specialization into the result set. We do this to avoid forcing all
701 // callers to perform special deduction for conversion functions.
Craig Toppere6706e42012-09-19 02:26:47 +0000702 TemplateDeductionInfo Info(R.getNameLoc());
Chandler Carruth3a693b72010-01-31 11:44:02 +0000703 FunctionDecl *Specialization = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000704
705 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000706 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
707 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000708
Chandler Carruth3a693b72010-01-31 11:44:02 +0000709 // Compute the type of the function that we would expect the conversion
710 // function to have, if it were to match the name given.
711 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000712 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
713 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
Sebastian Redl7c6c9e92011-03-06 10:52:04 +0000714 EPI.ExceptionSpecType = EST_None;
John McCalldb40c7f2010-12-14 08:05:40 +0000715 EPI.NumExceptions = 0;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000716 QualType ExpectedType
717 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
John McCalldb40c7f2010-12-14 08:05:40 +0000718 0, 0, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000719
Chandler Carruth3a693b72010-01-31 11:44:02 +0000720 // Perform template argument deduction against the type that we would
721 // expect the function to have.
722 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
723 Specialization, Info)
724 == Sema::TDK_Success) {
725 R.addDecl(Specialization);
726 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000727 }
728 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000729
John McCall9f3059a2009-10-09 21:13:30 +0000730 return Found;
731}
732
John McCallf6c8a4e2009-11-10 07:01:13 +0000733// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000734static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000735CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000736 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000737
738 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
739
John McCallf6c8a4e2009-11-10 07:01:13 +0000740 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000741 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000742
John McCallf6c8a4e2009-11-10 07:01:13 +0000743 // Perform direct name lookup into the namespaces nominated by the
744 // using directives whose common ancestor is this namespace.
745 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
746 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000747
John McCallf6c8a4e2009-11-10 07:01:13 +0000748 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000749 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000750 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000751
752 R.resolveKind();
753
754 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000755}
756
757static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000758 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000759 return Ctx->isFileContext();
760 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000761}
Douglas Gregored8f2882009-01-30 01:04:22 +0000762
Douglas Gregor66230062010-03-15 14:33:29 +0000763// Find the next outer declaration context from this scope. This
764// routine actually returns the semantic outer context, which may
765// differ from the lexical context (encoded directly in the Scope
766// stack) when we are parsing a member of a class template. In this
767// case, the second element of the pair will be true, to indicate that
768// name lookup should continue searching in this semantic context when
769// it leaves the current template parameter scope.
770static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
771 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
772 DeclContext *Lexical = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000773 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000774 OuterS = OuterS->getParent()) {
775 if (OuterS->getEntity()) {
Douglas Gregorea166062010-03-15 15:26:48 +0000776 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor66230062010-03-15 14:33:29 +0000777 break;
778 }
779 }
780
781 // C++ [temp.local]p8:
782 // In the definition of a member of a class template that appears
783 // outside of the namespace containing the class template
784 // definition, the name of a template-parameter hides the name of
785 // a member of this namespace.
786 //
787 // Example:
788 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000789 // namespace N {
790 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000791 //
792 // template<class T> class B {
793 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000794 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000795 // }
796 //
797 // template<class C> void N::B<C>::f(C) {
798 // C b; // C is the template parameter, not N::C
799 // }
800 //
801 // In this example, the lexical context we return is the
802 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000803 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000804 !S->getParent()->isTemplateParamScope())
805 return std::make_pair(Lexical, false);
806
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000807 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000808 // For the example, this is the scope for the template parameters of
809 // template<class C>.
810 Scope *OutermostTemplateScope = S->getParent();
811 while (OutermostTemplateScope->getParent() &&
812 OutermostTemplateScope->getParent()->isTemplateParamScope())
813 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000814
Douglas Gregor66230062010-03-15 14:33:29 +0000815 // Find the namespace context in which the original scope occurs. In
816 // the example, this is namespace N.
817 DeclContext *Semantic = DC;
818 while (!Semantic->isFileContext())
819 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000820
Douglas Gregor66230062010-03-15 14:33:29 +0000821 // Find the declaration context just outside of the template
822 // parameter scope. This is the context in which the template is
823 // being lexically declaration (a namespace context). In the
824 // example, this is the global scope.
825 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
826 Lexical->Encloses(Semantic))
827 return std::make_pair(Semantic, true);
828
829 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000830}
831
John McCall27b18f82009-11-17 02:14:36 +0000832bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000833 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000834
835 DeclarationName Name = R.getLookupName();
836
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000837 // If this is the name of an implicitly-declared special member function,
838 // go through the scope stack to implicitly declare
839 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
840 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
841 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
842 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
843 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000844
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000845 // Implicitly declare member functions with the name we're looking for, if in
846 // fact we are in a scope where it matters.
847
Douglas Gregor889ceb72009-02-03 19:21:40 +0000848 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000849 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000850 I = IdResolver.begin(Name),
851 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000852
Douglas Gregor889ceb72009-02-03 19:21:40 +0000853 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000854 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000855 // ...During unqualified name lookup (3.4.1), the names appear as if
856 // they were declared in the nearest enclosing namespace which contains
857 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000858 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000859 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000860 //
861 // For example:
862 // namespace A { int i; }
863 // void foo() {
864 // int i;
865 // {
866 // using namespace A;
867 // ++i; // finds local 'i', A::i appears at global scope
868 // }
869 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000870 //
Douglas Gregor66230062010-03-15 14:33:29 +0000871 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor700792c2009-02-05 19:25:20 +0000872 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor3e51e172010-05-20 20:58:56 +0000873 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
874
Douglas Gregor889ceb72009-02-03 19:21:40 +0000875 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000876 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000877 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000878 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
John McCall9f3059a2009-10-09 21:13:30 +0000879 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +0000880 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000881 }
882 }
John McCall9f3059a2009-10-09 21:13:30 +0000883 if (Found) {
884 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000885 if (S->isClassScope())
886 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
887 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000888 return true;
889 }
890
Douglas Gregor66230062010-03-15 14:33:29 +0000891 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
892 S->getParent() && !S->getParent()->isTemplateParamScope()) {
893 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000894 // found nothing, so look into the contexts between the
Douglas Gregor66230062010-03-15 14:33:29 +0000895 // lexical and semantic declaration contexts returned by
896 // findOuterContext(). This implements the name lookup behavior
897 // of C++ [temp.local]p8.
898 Ctx = OutsideOfTemplateParamDC;
899 OutsideOfTemplateParamDC = 0;
900 }
901
902 if (Ctx) {
903 DeclContext *OuterCtx;
904 bool SearchAfterTemplateScope;
905 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
906 if (SearchAfterTemplateScope)
907 OutsideOfTemplateParamDC = OuterCtx;
908
Douglas Gregorea166062010-03-15 15:26:48 +0000909 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000910 // We do not directly look into transparent contexts, since
911 // those entities will be found in the nearest enclosing
912 // non-transparent context.
913 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000914 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000915
916 // We do not look directly into function or method contexts,
917 // since all of the local variables and parameters of the
918 // function/method are present within the Scope.
919 if (Ctx->isFunctionOrMethod()) {
920 // If we have an Objective-C instance method, look for ivars
921 // in the corresponding interface.
922 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
923 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
924 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
925 ObjCInterfaceDecl *ClassDeclared;
926 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000927 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +0000928 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000929 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
930 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +0000931 R.resolveKind();
932 return true;
933 }
934 }
935 }
936 }
937
938 continue;
939 }
940
Douglas Gregor7f737c02009-09-10 16:57:35 +0000941 // Perform qualified name lookup into this context.
942 // FIXME: In some cases, we know that every name that could be found by
943 // this qualified name lookup will also be on the identifier chain. For
944 // example, inside a class without any base classes, we never need to
945 // perform qualified lookup because all of the members are on top of the
946 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000947 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +0000948 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000949 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000950 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000951 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000952
John McCallf6c8a4e2009-11-10 07:01:13 +0000953 // Stop if we ran out of scopes.
954 // FIXME: This really, really shouldn't be happening.
955 if (!S) return false;
956
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +0000957 // If we are looking for members, no need to look into global/namespace scope.
958 if (R.getLookupKind() == LookupMemberName)
959 return false;
960
Douglas Gregor700792c2009-02-05 19:25:20 +0000961 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000962 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000963 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000964 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
965 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000966
John McCallf6c8a4e2009-11-10 07:01:13 +0000967 UnqualUsingDirectiveSet UDirs;
968 UDirs.visitScopeChain(Initial, S);
969 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000970
Douglas Gregor700792c2009-02-05 19:25:20 +0000971 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000972 // Unqualified name lookup in C++ requires looking into scopes
973 // that aren't strictly lexical, and therefore we walk through the
974 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000975
Douglas Gregor889ceb72009-02-03 19:21:40 +0000976 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000977 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000978 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000979 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000980 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000981 // We found something. Look for anything else in our scope
982 // with this same name and in an acceptable identifier
983 // namespace, so that we can construct an overload set if we
984 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000985 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +0000986 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000987 }
988 }
989
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000990 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +0000991 R.resolveKind();
992 return true;
993 }
994
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000995 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
996 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
997 S->getParent() && !S->getParent()->isTemplateParamScope()) {
998 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000999 // found nothing, so look into the contexts between the
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001000 // lexical and semantic declaration contexts returned by
1001 // findOuterContext(). This implements the name lookup behavior
1002 // of C++ [temp.local]p8.
1003 Ctx = OutsideOfTemplateParamDC;
1004 OutsideOfTemplateParamDC = 0;
1005 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001006
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001007 if (Ctx) {
1008 DeclContext *OuterCtx;
1009 bool SearchAfterTemplateScope;
1010 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1011 if (SearchAfterTemplateScope)
1012 OutsideOfTemplateParamDC = OuterCtx;
1013
1014 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1015 // We do not directly look into transparent contexts, since
1016 // those entities will be found in the nearest enclosing
1017 // non-transparent context.
1018 if (Ctx->isTransparentContext())
1019 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001020
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001021 // If we have a context, and it's not a context stashed in the
1022 // template parameter scope for an out-of-line definition, also
1023 // look into that context.
1024 if (!(Found && S && S->isTemplateParamScope())) {
1025 assert(Ctx->isFileContext() &&
1026 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001027
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001028 // Look into context considering using-directives.
1029 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1030 Found = true;
1031 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001032
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001033 if (Found) {
1034 R.resolveKind();
1035 return true;
1036 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001037
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001038 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1039 return false;
1040 }
1041 }
1042
Douglas Gregor3ce74932010-02-05 07:07:10 +00001043 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001044 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001045 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001046
John McCall9f3059a2009-10-09 21:13:30 +00001047 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001048}
1049
Douglas Gregor4a814562011-12-14 16:03:29 +00001050/// \brief Retrieve the visible declaration corresponding to D, if any.
1051///
1052/// This routine determines whether the declaration D is visible in the current
1053/// module, with the current imports. If not, it checks whether any
1054/// redeclaration of D is visible, and if so, returns that declaration.
1055///
1056/// \returns D, or a visible previous declaration of D, whichever is more recent
1057/// and visible. If no declaration of D is visible, returns null.
1058static NamedDecl *getVisibleDecl(NamedDecl *D) {
1059 if (LookupResult::isVisible(D))
1060 return D;
1061
Douglas Gregor54079202012-01-06 22:05:37 +00001062 for (Decl::redecl_iterator RD = D->redecls_begin(), RDEnd = D->redecls_end();
1063 RD != RDEnd; ++RD) {
David Blaikie40ed2972012-06-06 20:45:41 +00001064 if (NamedDecl *ND = dyn_cast<NamedDecl>(*RD)) {
Douglas Gregor54079202012-01-06 22:05:37 +00001065 if (LookupResult::isVisible(ND))
1066 return ND;
1067 }
Douglas Gregor4a814562011-12-14 16:03:29 +00001068 }
1069
1070 return 0;
1071}
1072
Douglas Gregor34074322009-01-14 22:20:51 +00001073/// @brief Perform unqualified name lookup starting from a given
1074/// scope.
1075///
1076/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1077/// used to find names within the current scope. For example, 'x' in
1078/// @code
1079/// int x;
1080/// int f() {
1081/// return x; // unqualified name look finds 'x' in the global scope
1082/// }
1083/// @endcode
1084///
1085/// Different lookup criteria can find different names. For example, a
1086/// particular scope can have both a struct and a function of the same
1087/// name, and each can be found by certain lookup criteria. For more
1088/// information about lookup criteria, see the documentation for the
1089/// class LookupCriteria.
1090///
1091/// @param S The scope from which unqualified name lookup will
1092/// begin. If the lookup criteria permits, name lookup may also search
1093/// in the parent scopes.
1094///
James Dennett91738ff2012-06-22 10:32:46 +00001095/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1096/// look up and the lookup kind), and is updated with the results of lookup
1097/// including zero or more declarations and possibly additional information
1098/// used to diagnose ambiguities.
Douglas Gregor34074322009-01-14 22:20:51 +00001099///
James Dennett91738ff2012-06-22 10:32:46 +00001100/// @returns \c true if lookup succeeded and false otherwise.
John McCall27b18f82009-11-17 02:14:36 +00001101bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1102 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001103 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001104
John McCall27b18f82009-11-17 02:14:36 +00001105 LookupNameKind NameKind = R.getLookupKind();
1106
David Blaikiebbafb8a2012-03-11 07:00:24 +00001107 if (!getLangOpts().CPlusPlus) {
Douglas Gregor34074322009-01-14 22:20:51 +00001108 // Unqualified name lookup in C/Objective-C is purely lexical, so
1109 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001110 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001111 // Find the nearest non-transparent declaration scope.
1112 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +00001113 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +00001114 static_cast<DeclContext *>(S->getEntity())
1115 ->isTransparentContext()))
1116 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001117 }
1118
John McCallea305ed2009-12-18 10:40:03 +00001119 unsigned IDNS = R.getIdentifierNamespace();
1120
Douglas Gregor34074322009-01-14 22:20:51 +00001121 // Scan up the scope chain looking for a decl that matches this
1122 // identifier that is in the appropriate namespace. This search
1123 // should not take long, as shadowing of names is uncommon, and
1124 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001125 bool LeftStartingScope = false;
1126
Douglas Gregored8f2882009-01-30 01:04:22 +00001127 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001128 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001129 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001130 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001131 if (NameKind == LookupRedeclarationWithLinkage) {
1132 // Determine whether this (or a previous) declaration is
1133 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001134 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001135 LeftStartingScope = true;
1136
1137 // If we found something outside of our starting scope that
1138 // does not have linkage, skip it.
1139 if (LeftStartingScope && !((*I)->hasLinkage()))
1140 continue;
1141 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001142 else if (NameKind == LookupObjCImplicitSelfParam &&
1143 !isa<ImplicitParamDecl>(*I))
1144 continue;
1145
Douglas Gregor2a5d1482011-12-02 20:08:44 +00001146 // If this declaration is module-private and it came from an AST
1147 // file, we can't see it.
Douglas Gregor5c193c72012-01-05 01:11:47 +00001148 NamedDecl *D = R.isHiddenDeclarationVisible()? *I : getVisibleDecl(*I);
Douglas Gregor4a814562011-12-14 16:03:29 +00001149 if (!D)
Douglas Gregor2a5d1482011-12-02 20:08:44 +00001150 continue;
Douglas Gregor4a814562011-12-14 16:03:29 +00001151
1152 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001153
Douglas Gregorb59643b2012-01-03 23:26:26 +00001154 // Check whether there are any other declarations with the same name
1155 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001156 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001157 // Find the scope in which this declaration was declared (if it
1158 // actually exists in a Scope).
1159 while (S && !S->isDeclScope(D))
1160 S = S->getParent();
1161
1162 // If the scope containing the declaration is the translation unit,
1163 // then we'll need to perform our checks based on the matching
1164 // DeclContexts rather than matching scopes.
1165 if (S && isNamespaceOrTranslationUnitScope(S))
1166 S = 0;
1167
1168 // Compute the DeclContext, if we need it.
1169 DeclContext *DC = 0;
1170 if (!S)
1171 DC = (*I)->getDeclContext()->getRedeclContext();
1172
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001173 IdentifierResolver::iterator LastI = I;
1174 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001175 if (S) {
1176 // Match based on scope.
1177 if (!S->isDeclScope(*LastI))
1178 break;
1179 } else {
1180 // Match based on DeclContext.
1181 DeclContext *LastDC
1182 = (*LastI)->getDeclContext()->getRedeclContext();
1183 if (!LastDC->Equals(DC))
1184 break;
1185 }
1186
1187 // If the declaration isn't in the right namespace, skip it.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001188 if (!(*LastI)->isInIdentifierNamespace(IDNS))
1189 continue;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001190
Douglas Gregor5c193c72012-01-05 01:11:47 +00001191 D = R.isHiddenDeclarationVisible()? *LastI : getVisibleDecl(*LastI);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001192 if (D)
1193 R.addDecl(D);
1194 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001195
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001196 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001197 }
John McCall9f3059a2009-10-09 21:13:30 +00001198 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001199 }
Douglas Gregor34074322009-01-14 22:20:51 +00001200 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001201 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001202 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001203 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001204 }
1205
1206 // If we didn't find a use of this identifier, and if the identifier
1207 // corresponds to a compiler builtin, create the decl object for the builtin
1208 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001209 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1210 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001211
Axel Naumann016538a2011-02-24 16:47:47 +00001212 // If we didn't find a use of this identifier, the ExternalSource
1213 // may be able to handle the situation.
1214 // Note: some lookup failures are expected!
1215 // See e.g. R.isForRedeclaration().
1216 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001217}
1218
John McCall6538c932009-10-10 05:48:19 +00001219/// @brief Perform qualified name lookup in the namespaces nominated by
1220/// using directives by the given context.
1221///
1222/// C++98 [namespace.qual]p2:
James Dennett51a8d8b2012-06-19 21:05:49 +00001223/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6538c932009-10-10 05:48:19 +00001224/// (where X is the global namespace), let S be the set of all
1225/// declarations of m in X and in the transitive closure of all
1226/// namespaces nominated by using-directives in X and its used
1227/// namespaces, except that using-directives are ignored in any
1228/// namespace, including X, directly containing one or more
1229/// declarations of m. No namespace is searched more than once in
1230/// the lookup of a name. If S is the empty set, the program is
1231/// ill-formed. Otherwise, if S has exactly one member, or if the
1232/// context of the reference is a using-declaration
1233/// (namespace.udecl), S is the required set of declarations of
1234/// m. Otherwise if the use of m is not one that allows a unique
1235/// declaration to be chosen from S, the program is ill-formed.
James Dennett51a8d8b2012-06-19 21:05:49 +00001236///
John McCall6538c932009-10-10 05:48:19 +00001237/// C++98 [namespace.qual]p5:
1238/// During the lookup of a qualified namespace member name, if the
1239/// lookup finds more than one declaration of the member, and if one
1240/// declaration introduces a class name or enumeration name and the
1241/// other declarations either introduce the same object, the same
1242/// enumerator or a set of functions, the non-type name hides the
1243/// class or enumeration name if and only if the declarations are
1244/// from the same namespace; otherwise (the declarations are from
1245/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001246static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001247 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001248 assert(StartDC->isFileContext() && "start context is not a file context");
1249
1250 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1251 DeclContext::udir_iterator E = StartDC->using_directives_end();
1252
1253 if (I == E) return false;
1254
1255 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001256 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001257 Visited.insert(StartDC);
1258
1259 // We have not yet looked into these namespaces, much less added
1260 // their "using-children" to the queue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001261 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001262
1263 // We have already looked into the initial namespace; seed the queue
1264 // with its using-children.
1265 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +00001266 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001267 if (Visited.insert(ND))
John McCall6538c932009-10-10 05:48:19 +00001268 Queue.push_back(ND);
1269 }
1270
1271 // The easiest way to implement the restriction in [namespace.qual]p5
1272 // is to check whether any of the individual results found a tag
1273 // and, if so, to declare an ambiguity if the final result is not
1274 // a tag.
1275 bool FoundTag = false;
1276 bool FoundNonTag = false;
1277
John McCall5cebab12009-11-18 07:57:50 +00001278 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001279
1280 bool Found = false;
1281 while (!Queue.empty()) {
1282 NamespaceDecl *ND = Queue.back();
1283 Queue.pop_back();
1284
1285 // We go through some convolutions here to avoid copying results
1286 // between LookupResults.
1287 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001288 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001289 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001290
1291 if (FoundDirect) {
1292 // First do any local hiding.
1293 DirectR.resolveKind();
1294
1295 // If the local result is a tag, remember that.
1296 if (DirectR.isSingleTagDecl())
1297 FoundTag = true;
1298 else
1299 FoundNonTag = true;
1300
1301 // Append the local results to the total results if necessary.
1302 if (UseLocal) {
1303 R.addAllDecls(LocalR);
1304 LocalR.clear();
1305 }
1306 }
1307
1308 // If we find names in this namespace, ignore its using directives.
1309 if (FoundDirect) {
1310 Found = true;
1311 continue;
1312 }
1313
1314 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1315 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001316 if (Visited.insert(Nom))
John McCall6538c932009-10-10 05:48:19 +00001317 Queue.push_back(Nom);
1318 }
1319 }
1320
1321 if (Found) {
1322 if (FoundTag && FoundNonTag)
1323 R.setAmbiguousQualifiedTagHiding();
1324 else
1325 R.resolveKind();
1326 }
1327
1328 return Found;
1329}
1330
Douglas Gregor39982192010-08-15 06:18:01 +00001331/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001332static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor39982192010-08-15 06:18:01 +00001333 CXXBasePath &Path,
1334 void *Name) {
1335 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001336
Douglas Gregor39982192010-08-15 06:18:01 +00001337 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1338 Path.Decls = BaseRecord->lookup(N);
1339 return Path.Decls.first != Path.Decls.second;
1340}
1341
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001342/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001343/// static members, nested types, and enumerators.
1344template<typename InputIterator>
1345static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1346 Decl *D = (*First)->getUnderlyingDecl();
1347 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1348 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001349
Douglas Gregorc0d24902010-10-22 22:08:47 +00001350 if (isa<CXXMethodDecl>(D)) {
1351 // Determine whether all of the methods are static.
1352 bool AllMethodsAreStatic = true;
1353 for(; First != Last; ++First) {
1354 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001355
Douglas Gregorc0d24902010-10-22 22:08:47 +00001356 if (!isa<CXXMethodDecl>(D)) {
1357 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1358 break;
1359 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001360
Douglas Gregorc0d24902010-10-22 22:08:47 +00001361 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1362 AllMethodsAreStatic = false;
1363 break;
1364 }
1365 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001366
Douglas Gregorc0d24902010-10-22 22:08:47 +00001367 if (AllMethodsAreStatic)
1368 return true;
1369 }
1370
1371 return false;
1372}
1373
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001374/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001375///
1376/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1377/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001378/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001379///
1380/// Different lookup criteria can find different names. For example, a
1381/// particular scope can have both a struct and a function of the same
1382/// name, and each can be found by certain lookup criteria. For more
1383/// information about lookup criteria, see the documentation for the
1384/// class LookupCriteria.
1385///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001386/// \param R captures both the lookup criteria and any lookup results found.
1387///
1388/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001389/// search. If the lookup criteria permits, name lookup may also search
1390/// in the parent contexts or (for C++ classes) base classes.
1391///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001392/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001393/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001394///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001395/// \returns true if lookup succeeded, false if it failed.
1396bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1397 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001398 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001399
John McCall27b18f82009-11-17 02:14:36 +00001400 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001401 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001402
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001403 // Make sure that the declaration context is complete.
1404 assert((!isa<TagDecl>(LookupCtx) ||
1405 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00001406 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith7d137e32012-03-23 03:33:32 +00001407 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001408 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001409
Douglas Gregor34074322009-01-14 22:20:51 +00001410 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001411 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001412 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001413 if (isa<CXXRecordDecl>(LookupCtx))
1414 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001415 return true;
1416 }
Douglas Gregor34074322009-01-14 22:20:51 +00001417
John McCall6538c932009-10-10 05:48:19 +00001418 // Don't descend into implied contexts for redeclarations.
1419 // C++98 [namespace.qual]p6:
1420 // In a declaration for a namespace member in which the
1421 // declarator-id is a qualified-id, given that the qualified-id
1422 // for the namespace member has the form
1423 // nested-name-specifier unqualified-id
1424 // the unqualified-id shall name a member of the namespace
1425 // designated by the nested-name-specifier.
1426 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001427 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001428 return false;
1429
John McCall27b18f82009-11-17 02:14:36 +00001430 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001431 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001432 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001433
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001434 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001435 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001436 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001437 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001438 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001439
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001440 // If we're performing qualified name lookup into a dependent class,
1441 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001442 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001443 // template instantiation time (at which point all bases will be available)
1444 // or we have to fail.
1445 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1446 LookupRec->hasAnyDependentBases()) {
1447 R.setNotFoundInCurrentInstantiation();
1448 return false;
1449 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001450
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001451 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001452 CXXBasePaths Paths;
1453 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001454
1455 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001456 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001457 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001458 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001459 case LookupOrdinaryName:
1460 case LookupMemberName:
1461 case LookupRedeclarationWithLinkage:
1462 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1463 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001464
Douglas Gregor36d1b142009-10-06 17:59:45 +00001465 case LookupTagName:
1466 BaseCallback = &CXXRecordDecl::FindTagMember;
1467 break;
John McCall84d87672009-12-10 09:41:52 +00001468
Douglas Gregor39982192010-08-15 06:18:01 +00001469 case LookupAnyName:
1470 BaseCallback = &LookupAnyMember;
1471 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001472
John McCall84d87672009-12-10 09:41:52 +00001473 case LookupUsingDeclName:
1474 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001475
Douglas Gregor36d1b142009-10-06 17:59:45 +00001476 case LookupOperatorName:
1477 case LookupNamespaceName:
1478 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001479 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001480 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001481 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001482
Douglas Gregor36d1b142009-10-06 17:59:45 +00001483 case LookupNestedNameSpecifierName:
1484 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1485 break;
1486 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001487
John McCall27b18f82009-11-17 02:14:36 +00001488 if (!LookupRec->lookupInBases(BaseCallback,
1489 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001490 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001491
John McCall553c0792010-01-23 00:46:32 +00001492 R.setNamingClass(LookupRec);
1493
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001494 // C++ [class.member.lookup]p2:
1495 // [...] If the resulting set of declarations are not all from
1496 // sub-objects of the same type, or the set has a nonstatic member
1497 // and includes members from distinct sub-objects, there is an
1498 // ambiguity and the program is ill-formed. Otherwise that set is
1499 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001500 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001501 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001502 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001503
Douglas Gregor36d1b142009-10-06 17:59:45 +00001504 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001505 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001506 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001507
John McCall401982f2010-01-20 21:53:11 +00001508 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1509 // across all paths.
1510 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001511
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001512 // Determine whether we're looking at a distinct sub-object or not.
1513 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001514 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001515 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1516 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001517 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001518 }
1519
Douglas Gregorc0d24902010-10-22 22:08:47 +00001520 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001521 != Context.getCanonicalType(PathElement.Base->getType())) {
1522 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001523 // different types. If the declaration sets aren't the same, this
1524 // this lookup is ambiguous.
1525 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1526 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1527 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1528 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001529
Douglas Gregorc0d24902010-10-22 22:08:47 +00001530 while (FirstD != FirstPath->Decls.second &&
1531 CurrentD != Path->Decls.second) {
1532 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1533 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1534 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001535
Douglas Gregorc0d24902010-10-22 22:08:47 +00001536 ++FirstD;
1537 ++CurrentD;
1538 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001539
Douglas Gregorc0d24902010-10-22 22:08:47 +00001540 if (FirstD == FirstPath->Decls.second &&
1541 CurrentD == Path->Decls.second)
1542 continue;
1543 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001544
John McCall9f3059a2009-10-09 21:13:30 +00001545 R.setAmbiguousBaseSubobjectTypes(Paths);
1546 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001547 }
1548
Douglas Gregorc0d24902010-10-22 22:08:47 +00001549 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001550 // We have a different subobject of the same type.
1551
1552 // C++ [class.member.lookup]p5:
1553 // A static member, a nested type or an enumerator defined in
1554 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001555 // has more than one base class subobject of type T.
Douglas Gregorc0d24902010-10-22 22:08:47 +00001556 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001557 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001558
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001559 // We have found a nonstatic member name in multiple, distinct
1560 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001561 R.setAmbiguousBaseSubobjects(Paths);
1562 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001563 }
1564 }
1565
1566 // Lookup in a base class succeeded; return these results.
1567
John McCall9f3059a2009-10-09 21:13:30 +00001568 DeclContext::lookup_iterator I, E;
John McCall553c0792010-01-23 00:46:32 +00001569 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1570 NamedDecl *D = *I;
1571 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1572 D->getAccess());
1573 R.addDecl(D, AS);
1574 }
John McCall9f3059a2009-10-09 21:13:30 +00001575 R.resolveKind();
1576 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001577}
1578
1579/// @brief Performs name lookup for a name that was parsed in the
1580/// source code, and may contain a C++ scope specifier.
1581///
1582/// This routine is a convenience routine meant to be called from
1583/// contexts that receive a name and an optional C++ scope specifier
1584/// (e.g., "N::M::x"). It will then perform either qualified or
1585/// unqualified name lookup (with LookupQualifiedName or LookupName,
1586/// respectively) on the given name and return those results.
1587///
1588/// @param S The scope from which unqualified name lookup will
1589/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001590///
Douglas Gregore861bac2009-08-25 22:51:20 +00001591/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001592///
Douglas Gregore861bac2009-08-25 22:51:20 +00001593/// @param EnteringContext Indicates whether we are going to enter the
1594/// context of the scope-specifier SS (if present).
1595///
John McCall9f3059a2009-10-09 21:13:30 +00001596/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001597bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001598 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001599 if (SS && SS->isInvalid()) {
1600 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001601 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001602 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001603 }
Mike Stump11289f42009-09-09 15:08:12 +00001604
Douglas Gregore861bac2009-08-25 22:51:20 +00001605 if (SS && SS->isSet()) {
1606 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001607 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001608 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001609 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001610 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001611
John McCall27b18f82009-11-17 02:14:36 +00001612 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00001613 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001614 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001615
Douglas Gregore861bac2009-08-25 22:51:20 +00001616 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001617 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001618 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00001619 R.setNotFoundInCurrentInstantiation();
1620 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00001621 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001622 }
1623
Mike Stump11289f42009-09-09 15:08:12 +00001624 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001625 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001626}
1627
Douglas Gregor889ceb72009-02-03 19:21:40 +00001628
James Dennett41725122012-06-22 10:16:05 +00001629/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001630/// from name lookup.
1631///
James Dennett41725122012-06-22 10:16:05 +00001632/// \param Result The result of the ambiguous lookup to be diagnosed.
Mike Stump11289f42009-09-09 15:08:12 +00001633///
James Dennett41725122012-06-22 10:16:05 +00001634/// \returns true
John McCall27b18f82009-11-17 02:14:36 +00001635bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001636 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1637
John McCall27b18f82009-11-17 02:14:36 +00001638 DeclarationName Name = Result.getLookupName();
1639 SourceLocation NameLoc = Result.getNameLoc();
1640 SourceRange LookupRange = Result.getContextRange();
1641
John McCall6538c932009-10-10 05:48:19 +00001642 switch (Result.getAmbiguityKind()) {
1643 case LookupResult::AmbiguousBaseSubobjects: {
1644 CXXBasePaths *Paths = Result.getBasePaths();
1645 QualType SubobjectType = Paths->front().back().Base->getType();
1646 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1647 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1648 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001649
John McCall6538c932009-10-10 05:48:19 +00001650 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1651 while (isa<CXXMethodDecl>(*Found) &&
1652 cast<CXXMethodDecl>(*Found)->isStatic())
1653 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001654
John McCall6538c932009-10-10 05:48:19 +00001655 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001656
John McCall6538c932009-10-10 05:48:19 +00001657 return true;
1658 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001659
John McCall6538c932009-10-10 05:48:19 +00001660 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001661 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1662 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001663
John McCall6538c932009-10-10 05:48:19 +00001664 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001665 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001666 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1667 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001668 Path != PathEnd; ++Path) {
1669 Decl *D = *Path->Decls.first;
1670 if (DeclsPrinted.insert(D).second)
1671 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1672 }
1673
Douglas Gregor1c846b02009-01-16 00:38:09 +00001674 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001675 }
1676
John McCall6538c932009-10-10 05:48:19 +00001677 case LookupResult::AmbiguousTagHiding: {
1678 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001679
John McCall6538c932009-10-10 05:48:19 +00001680 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1681
1682 LookupResult::iterator DI, DE = Result.end();
1683 for (DI = Result.begin(); DI != DE; ++DI)
1684 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1685 TagDecls.insert(TD);
1686 Diag(TD->getLocation(), diag::note_hidden_tag);
1687 }
1688
1689 for (DI = Result.begin(); DI != DE; ++DI)
1690 if (!isa<TagDecl>(*DI))
1691 Diag((*DI)->getLocation(), diag::note_hiding_object);
1692
1693 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001694 LookupResult::Filter F = Result.makeFilter();
1695 while (F.hasNext()) {
1696 if (TagDecls.count(F.next()))
1697 F.erase();
1698 }
1699 F.done();
John McCall6538c932009-10-10 05:48:19 +00001700
1701 return true;
1702 }
1703
1704 case LookupResult::AmbiguousReference: {
1705 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001706
John McCall6538c932009-10-10 05:48:19 +00001707 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1708 for (; DI != DE; ++DI)
1709 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001710
John McCall6538c932009-10-10 05:48:19 +00001711 return true;
1712 }
1713 }
1714
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001715 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001716}
Douglas Gregore254f902009-02-04 00:32:51 +00001717
John McCallf24d7bb2010-05-28 18:45:08 +00001718namespace {
1719 struct AssociatedLookup {
John McCall7d8b0412012-08-24 20:38:34 +00001720 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallf24d7bb2010-05-28 18:45:08 +00001721 Sema::AssociatedNamespaceSet &Namespaces,
1722 Sema::AssociatedClassSet &Classes)
John McCall7d8b0412012-08-24 20:38:34 +00001723 : S(S), Namespaces(Namespaces), Classes(Classes),
1724 InstantiationLoc(InstantiationLoc) {
John McCallf24d7bb2010-05-28 18:45:08 +00001725 }
1726
1727 Sema &S;
1728 Sema::AssociatedNamespaceSet &Namespaces;
1729 Sema::AssociatedClassSet &Classes;
John McCall7d8b0412012-08-24 20:38:34 +00001730 SourceLocation InstantiationLoc;
John McCallf24d7bb2010-05-28 18:45:08 +00001731 };
1732}
1733
Mike Stump11289f42009-09-09 15:08:12 +00001734static void
John McCallf24d7bb2010-05-28 18:45:08 +00001735addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001736
Douglas Gregor8b895222010-04-30 07:08:38 +00001737static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1738 DeclContext *Ctx) {
1739 // Add the associated namespace for this class.
1740
1741 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1742 // be a locally scoped record.
1743
Sebastian Redlbd595762010-08-31 20:53:31 +00001744 // We skip out of inline namespaces. The innermost non-inline namespace
1745 // contains all names of all its nested inline namespaces anyway, so we can
1746 // replace the entire inline namespace tree with its root.
1747 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1748 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00001749 Ctx = Ctx->getParent();
1750
John McCallc7e8e792009-08-07 22:18:02 +00001751 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001752 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001753}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001754
Mike Stump11289f42009-09-09 15:08:12 +00001755// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001756// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001757static void
John McCallf24d7bb2010-05-28 18:45:08 +00001758addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1759 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001760 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001761 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001762 switch (Arg.getKind()) {
1763 case TemplateArgument::Null:
1764 break;
Mike Stump11289f42009-09-09 15:08:12 +00001765
Douglas Gregor197e5f72009-07-08 07:51:57 +00001766 case TemplateArgument::Type:
1767 // [...] the namespaces and classes associated with the types of the
1768 // template arguments provided for template type parameters (excluding
1769 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001770 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001771 break;
Mike Stump11289f42009-09-09 15:08:12 +00001772
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001773 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001774 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00001775 // [...] the namespaces in which any template template arguments are
1776 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001777 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001778 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00001779 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001780 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001781 DeclContext *Ctx = ClassTemplate->getDeclContext();
1782 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001783 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001784 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001785 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001786 }
1787 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001788 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001789
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001790 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001791 case TemplateArgument::Integral:
1792 case TemplateArgument::Expression:
Eli Friedmanb826a002012-09-26 02:36:12 +00001793 case TemplateArgument::NullPtr:
Mike Stump11289f42009-09-09 15:08:12 +00001794 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001795 // associated namespaces. ]
1796 break;
Mike Stump11289f42009-09-09 15:08:12 +00001797
Douglas Gregor197e5f72009-07-08 07:51:57 +00001798 case TemplateArgument::Pack:
1799 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1800 PEnd = Arg.pack_end();
1801 P != PEnd; ++P)
John McCallf24d7bb2010-05-28 18:45:08 +00001802 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001803 break;
1804 }
1805}
1806
Douglas Gregore254f902009-02-04 00:32:51 +00001807// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001808// argument-dependent lookup with an argument of class type
1809// (C++ [basic.lookup.koenig]p2).
1810static void
John McCallf24d7bb2010-05-28 18:45:08 +00001811addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1812 CXXRecordDecl *Class) {
1813
1814 // Just silently ignore anything whose name is __va_list_tag.
1815 if (Class->getDeclName() == Result.S.VAListTagName)
1816 return;
1817
Douglas Gregore254f902009-02-04 00:32:51 +00001818 // C++ [basic.lookup.koenig]p2:
1819 // [...]
1820 // -- If T is a class type (including unions), its associated
1821 // classes are: the class itself; the class of which it is a
1822 // member, if any; and its direct and indirect base
1823 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001824 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001825
1826 // Add the class of which it is a member, if any.
1827 DeclContext *Ctx = Class->getDeclContext();
1828 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001829 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001830 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001831 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001832
Douglas Gregore254f902009-02-04 00:32:51 +00001833 // Add the class itself. If we've already seen this class, we don't
1834 // need to visit base classes.
John McCallf24d7bb2010-05-28 18:45:08 +00001835 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00001836 return;
1837
Mike Stump11289f42009-09-09 15:08:12 +00001838 // -- If T is a template-id, its associated namespaces and classes are
1839 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001840 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001841 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001842 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001843 // namespaces in which any template template arguments are defined; and
1844 // the classes in which any member templates used as template template
1845 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001846 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001847 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001848 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1849 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1850 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001851 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001852 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001853 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001854
Douglas Gregor197e5f72009-07-08 07:51:57 +00001855 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1856 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00001857 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001858 }
Mike Stump11289f42009-09-09 15:08:12 +00001859
John McCall67da35c2010-02-04 22:26:26 +00001860 // Only recurse into base classes for complete types.
1861 if (!Class->hasDefinition()) {
John McCall7d8b0412012-08-24 20:38:34 +00001862 QualType type = Result.S.Context.getTypeDeclType(Class);
1863 if (Result.S.RequireCompleteType(Result.InstantiationLoc, type,
1864 /*no diagnostic*/ 0))
1865 return;
John McCall67da35c2010-02-04 22:26:26 +00001866 }
1867
Douglas Gregore254f902009-02-04 00:32:51 +00001868 // Add direct and indirect base classes along with their associated
1869 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001870 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00001871 Bases.push_back(Class);
1872 while (!Bases.empty()) {
1873 // Pop this class off the stack.
1874 Class = Bases.back();
1875 Bases.pop_back();
1876
1877 // Visit the base classes.
1878 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1879 BaseEnd = Class->bases_end();
1880 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001881 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001882 // In dependent contexts, we do ADL twice, and the first time around,
1883 // the base type might be a dependent TemplateSpecializationType, or a
1884 // TemplateTypeParmType. If that happens, simply ignore it.
1885 // FIXME: If we want to support export, we probably need to add the
1886 // namespace of the template in a TemplateSpecializationType, or even
1887 // the classes and namespaces of known non-dependent arguments.
1888 if (!BaseType)
1889 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001890 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001891 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00001892 // Find the associated namespace for this base class.
1893 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00001894 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001895
1896 // Make sure we visit the bases of this base class.
1897 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1898 Bases.push_back(BaseDecl);
1899 }
1900 }
1901 }
1902}
1903
1904// \brief Add the associated classes and namespaces for
1905// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001906// (C++ [basic.lookup.koenig]p2).
1907static void
John McCallf24d7bb2010-05-28 18:45:08 +00001908addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00001909 // C++ [basic.lookup.koenig]p2:
1910 //
1911 // For each argument type T in the function call, there is a set
1912 // of zero or more associated namespaces and a set of zero or more
1913 // associated classes to be considered. The sets of namespaces and
1914 // classes is determined entirely by the types of the function
1915 // arguments (and the namespace of any template template
1916 // argument). Typedef names and using-declarations used to specify
1917 // the types do not contribute to this set. The sets of namespaces
1918 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00001919
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001920 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00001921 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1922
Douglas Gregore254f902009-02-04 00:32:51 +00001923 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00001924 switch (T->getTypeClass()) {
1925
1926#define TYPE(Class, Base)
1927#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1928#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1929#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1930#define ABSTRACT_TYPE(Class, Base)
1931#include "clang/AST/TypeNodes.def"
1932 // T is canonical. We can also ignore dependent types because
1933 // we don't need to do ADL at the definition point, but if we
1934 // wanted to implement template export (or if we find some other
1935 // use for associated classes and namespaces...) this would be
1936 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00001937 break;
Douglas Gregore254f902009-02-04 00:32:51 +00001938
John McCall0af3d3b2010-05-28 06:08:54 +00001939 // -- If T is a pointer to U or an array of U, its associated
1940 // namespaces and classes are those associated with U.
1941 case Type::Pointer:
1942 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1943 continue;
1944 case Type::ConstantArray:
1945 case Type::IncompleteArray:
1946 case Type::VariableArray:
1947 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1948 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001949
John McCall0af3d3b2010-05-28 06:08:54 +00001950 // -- If T is a fundamental type, its associated sets of
1951 // namespaces and classes are both empty.
1952 case Type::Builtin:
1953 break;
1954
1955 // -- If T is a class type (including unions), its associated
1956 // classes are: the class itself; the class of which it is a
1957 // member, if any; and its direct and indirect base
1958 // classes. Its associated namespaces are the namespaces in
1959 // which its associated classes are defined.
1960 case Type::Record: {
1961 CXXRecordDecl *Class
1962 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001963 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00001964 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00001965 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00001966
John McCall0af3d3b2010-05-28 06:08:54 +00001967 // -- If T is an enumeration type, its associated namespace is
1968 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001969 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00001970 // it has no associated class.
1971 case Type::Enum: {
1972 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001973
John McCall0af3d3b2010-05-28 06:08:54 +00001974 DeclContext *Ctx = Enum->getDeclContext();
1975 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001976 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001977
John McCall0af3d3b2010-05-28 06:08:54 +00001978 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001979 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001980
John McCall0af3d3b2010-05-28 06:08:54 +00001981 break;
1982 }
1983
1984 // -- If T is a function type, its associated namespaces and
1985 // classes are those associated with the function parameter
1986 // types and those associated with the return type.
1987 case Type::FunctionProto: {
1988 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1989 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1990 ArgEnd = Proto->arg_type_end();
1991 Arg != ArgEnd; ++Arg)
1992 Queue.push_back(Arg->getTypePtr());
1993 // fallthrough
1994 }
1995 case Type::FunctionNoProto: {
1996 const FunctionType *FnType = cast<FunctionType>(T);
1997 T = FnType->getResultType().getTypePtr();
1998 continue;
1999 }
2000
2001 // -- If T is a pointer to a member function of a class X, its
2002 // associated namespaces and classes are those associated
2003 // with the function parameter types and return type,
2004 // together with those associated with X.
2005 //
2006 // -- If T is a pointer to a data member of class X, its
2007 // associated namespaces and classes are those associated
2008 // with the member type together with those associated with
2009 // X.
2010 case Type::MemberPointer: {
2011 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2012
2013 // Queue up the class type into which this points.
2014 Queue.push_back(MemberPtr->getClass());
2015
2016 // And directly continue with the pointee type.
2017 T = MemberPtr->getPointeeType().getTypePtr();
2018 continue;
2019 }
2020
2021 // As an extension, treat this like a normal pointer.
2022 case Type::BlockPointer:
2023 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2024 continue;
2025
2026 // References aren't covered by the standard, but that's such an
2027 // obvious defect that we cover them anyway.
2028 case Type::LValueReference:
2029 case Type::RValueReference:
2030 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2031 continue;
2032
2033 // These are fundamental types.
2034 case Type::Vector:
2035 case Type::ExtVector:
2036 case Type::Complex:
2037 break;
2038
Douglas Gregor8e936662011-04-12 01:02:45 +00002039 // If T is an Objective-C object or interface type, or a pointer to an
2040 // object or interface type, the associated namespace is the global
2041 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002042 case Type::ObjCObject:
2043 case Type::ObjCInterface:
2044 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002045 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002046 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002047
2048 // Atomic types are just wrappers; use the associations of the
2049 // contained type.
2050 case Type::Atomic:
2051 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2052 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002053 }
2054
2055 if (Queue.empty()) break;
2056 T = Queue.back();
2057 Queue.pop_back();
Douglas Gregore254f902009-02-04 00:32:51 +00002058 }
Douglas Gregore254f902009-02-04 00:32:51 +00002059}
2060
2061/// \brief Find the associated classes and namespaces for
2062/// argument-dependent lookup for a call with the given set of
2063/// arguments.
2064///
2065/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002066/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002067/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002068void
John McCall7d8b0412012-08-24 20:38:34 +00002069Sema::FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
2070 llvm::ArrayRef<Expr *> Args,
Douglas Gregore254f902009-02-04 00:32:51 +00002071 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00002072 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002073 AssociatedNamespaces.clear();
2074 AssociatedClasses.clear();
2075
John McCall7d8b0412012-08-24 20:38:34 +00002076 AssociatedLookup Result(*this, InstantiationLoc,
2077 AssociatedNamespaces, AssociatedClasses);
John McCallf24d7bb2010-05-28 18:45:08 +00002078
Douglas Gregore254f902009-02-04 00:32:51 +00002079 // C++ [basic.lookup.koenig]p2:
2080 // For each argument type T in the function call, there is a set
2081 // of zero or more associated namespaces and a set of zero or more
2082 // associated classes to be considered. The sets of namespaces and
2083 // classes is determined entirely by the types of the function
2084 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002085 // argument).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002086 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregore254f902009-02-04 00:32:51 +00002087 Expr *Arg = Args[ArgIdx];
2088
2089 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002090 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002091 continue;
2092 }
2093
2094 // [...] In addition, if the argument is the name or address of a
2095 // set of overloaded functions and/or function templates, its
2096 // associated classes and namespaces are the union of those
2097 // associated with each of the members of the set: the namespace
2098 // in which the function or function template is defined and the
2099 // classes and namespaces associated with its (non-dependent)
2100 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002101 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002102 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002103 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002104 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002105
John McCallf24d7bb2010-05-28 18:45:08 +00002106 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2107 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002108
John McCallf24d7bb2010-05-28 18:45:08 +00002109 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2110 I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002111 // Look through any using declarations to find the underlying function.
2112 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002113
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002114 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2115 if (!FDecl)
2116 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002117
2118 // Add the classes and namespaces associated with the parameter
2119 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002120 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002121 }
2122 }
2123}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002124
2125/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2126/// an acceptable non-member overloaded operator for a call whose
2127/// arguments have types T1 (and, if non-empty, T2). This routine
2128/// implements the check in C++ [over.match.oper]p3b2 concerning
2129/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00002130static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002131IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2132 QualType T1, QualType T2,
2133 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00002134 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2135 return true;
2136
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002137 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2138 return true;
2139
John McCall9dd450b2009-09-21 23:43:11 +00002140 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002141 if (Proto->getNumArgs() < 1)
2142 return false;
2143
2144 if (T1->isEnumeralType()) {
2145 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002146 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002147 return true;
2148 }
2149
2150 if (Proto->getNumArgs() < 2)
2151 return false;
2152
2153 if (!T2.isNull() && T2->isEnumeralType()) {
2154 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002155 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002156 return true;
2157 }
2158
2159 return false;
2160}
2161
John McCall5cebab12009-11-18 07:57:50 +00002162NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002163 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002164 LookupNameKind NameKind,
2165 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002166 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002167 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002168 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002169}
2170
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002171/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002172ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002173 SourceLocation IdLoc,
2174 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002175 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002176 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002177 return cast_or_null<ObjCProtocolDecl>(D);
2178}
2179
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002180void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002181 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002182 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002183 // C++ [over.match.oper]p3:
2184 // -- The set of non-member candidates is the result of the
2185 // unqualified lookup of operator@ in the context of the
2186 // expression according to the usual rules for name lookup in
2187 // unqualified function calls (3.4.2) except that all member
2188 // functions are ignored. However, if no operand has a class
2189 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00002190 // that have a first parameter of type T1 or "reference to
2191 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002192 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00002193 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002194 // when T2 is an enumeration type, are candidate functions.
2195 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002196 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2197 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002198
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002199 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2200
John McCall9f3059a2009-10-09 21:13:30 +00002201 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002202 return;
2203
2204 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2205 Op != OpEnd; ++Op) {
Douglas Gregor645d76f2010-04-25 20:25:43 +00002206 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2207 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002208 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor645d76f2010-04-25 20:25:43 +00002209 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00002210 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor645d76f2010-04-25 20:25:43 +00002211 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor15448f82009-06-27 21:05:07 +00002212 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00002213 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00002214 // later?
2215 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor645d76f2010-04-25 20:25:43 +00002216 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor15448f82009-06-27 21:05:07 +00002217 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002218 }
2219}
2220
Alexis Hunt1da39282011-06-24 02:11:39 +00002221Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002222 CXXSpecialMember SM,
2223 bool ConstArg,
2224 bool VolatileArg,
2225 bool RValueThis,
2226 bool ConstThis,
2227 bool VolatileThis) {
Richard Smith7d125a12012-11-27 21:20:31 +00002228 assert(CanDeclareSpecialMemberFunction(RD) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002229 "doing special member lookup into record that isn't fully complete");
Richard Smith7d125a12012-11-27 21:20:31 +00002230 RD = RD->getDefinition();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002231 if (RValueThis || ConstThis || VolatileThis)
2232 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2233 "constructors and destructors always have unqualified lvalue this");
2234 if (ConstArg || VolatileArg)
2235 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2236 "parameter-less special members can't have qualified arguments");
2237
2238 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002239 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002240 ID.AddInteger(SM);
2241 ID.AddInteger(ConstArg);
2242 ID.AddInteger(VolatileArg);
2243 ID.AddInteger(RValueThis);
2244 ID.AddInteger(ConstThis);
2245 ID.AddInteger(VolatileThis);
2246
2247 void *InsertPoint;
2248 SpecialMemberOverloadResult *Result =
2249 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2250
2251 // This was already cached
2252 if (Result)
2253 return Result;
2254
Alexis Huntba8e18d2011-06-07 00:11:58 +00002255 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2256 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002257 SpecialMemberCache.InsertNode(Result, InsertPoint);
2258
2259 if (SM == CXXDestructor) {
Richard Smith2be35f52012-12-01 02:35:44 +00002260 if (RD->needsImplicitDestructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002261 DeclareImplicitDestructor(RD);
2262 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002263 assert(DD && "record without a destructor");
2264 Result->setMethod(DD);
Richard Smith852265f2012-03-30 20:53:28 +00002265 Result->setKind(DD->isDeleted() ?
2266 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith83c478d2012-04-20 18:46:14 +00002267 SpecialMemberOverloadResult::Success);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002268 return Result;
2269 }
2270
Alexis Hunteef8ee02011-06-10 03:50:41 +00002271 // Prepare for overload resolution. Here we construct a synthetic argument
2272 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002273 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002274 DeclarationName Name;
2275 Expr *Arg = 0;
2276 unsigned NumArgs;
2277
Richard Smith83c478d2012-04-20 18:46:14 +00002278 QualType ArgType = CanTy;
2279 ExprValueKind VK = VK_LValue;
2280
Alexis Hunteef8ee02011-06-10 03:50:41 +00002281 if (SM == CXXDefaultConstructor) {
2282 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2283 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002284 if (RD->needsImplicitDefaultConstructor())
2285 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002286 } else {
2287 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2288 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smith2be35f52012-12-01 02:35:44 +00002289 if (RD->needsImplicitCopyConstructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002290 DeclareImplicitCopyConstructor(RD);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002291 if (getLangOpts().CPlusPlus0x && RD->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002292 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002293 } else {
2294 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smith2be35f52012-12-01 02:35:44 +00002295 if (RD->needsImplicitCopyAssignment())
Alexis Hunt1da39282011-06-24 02:11:39 +00002296 DeclareImplicitCopyAssignment(RD);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002297 if (getLangOpts().CPlusPlus0x && RD->needsImplicitMoveAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002298 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002299 }
2300
Alexis Hunteef8ee02011-06-10 03:50:41 +00002301 if (ConstArg)
2302 ArgType.addConst();
2303 if (VolatileArg)
2304 ArgType.addVolatile();
2305
2306 // This isn't /really/ specified by the standard, but it's implied
2307 // we should be working from an RValue in the case of move to ensure
2308 // that we prefer to bind to rvalue references, and an LValue in the
2309 // case of copy to ensure we don't bind to rvalue references.
2310 // Possibly an XValue is actually correct in the case of move, but
2311 // there is no semantic difference for class types in this restricted
2312 // case.
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002313 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002314 VK = VK_LValue;
2315 else
2316 VK = VK_RValue;
Richard Smith83c478d2012-04-20 18:46:14 +00002317 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00002318
Richard Smith83c478d2012-04-20 18:46:14 +00002319 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2320
2321 if (SM != CXXDefaultConstructor) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002322 NumArgs = 1;
Richard Smith83c478d2012-04-20 18:46:14 +00002323 Arg = &FakeArg;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002324 }
2325
2326 // Create the object argument
2327 QualType ThisTy = CanTy;
2328 if (ConstThis)
2329 ThisTy.addConst();
2330 if (VolatileThis)
2331 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002332 Expr::Classification Classification =
Richard Smith83c478d2012-04-20 18:46:14 +00002333 OpaqueValueExpr(SourceLocation(), ThisTy,
2334 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002335
2336 // Now we perform lookup on the name we computed earlier and do overload
2337 // resolution. Lookup is only performed directly into the class since there
2338 // will always be a (possibly implicit) declaration to shadow any others.
2339 OverloadCandidateSet OCS((SourceLocation()));
2340 DeclContext::lookup_iterator I, E;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002341
Alexis Hunt1da39282011-06-24 02:11:39 +00002342 llvm::tie(I, E) = RD->lookup(Name);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002343 assert((I != E) &&
2344 "lookup for a constructor or assignment operator was empty");
2345 for ( ; I != E; ++I) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002346 Decl *Cand = *I;
Alexis Hunt080709f2011-06-23 00:26:20 +00002347
Alexis Hunt1da39282011-06-24 02:11:39 +00002348 if (Cand->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002349 continue;
2350
Alexis Hunt1da39282011-06-24 02:11:39 +00002351 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2352 // FIXME: [namespace.udecl]p15 says that we should only consider a
2353 // using declaration here if it does not match a declaration in the
2354 // derived class. We do not implement this correctly in other cases
2355 // either.
2356 Cand = U->getTargetDecl();
2357
2358 if (Cand->isInvalidDecl())
2359 continue;
2360 }
2361
2362 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002363 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Alexis Hunt1da39282011-06-24 02:11:39 +00002364 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002365 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2366 OCS, true);
Alexis Hunt080709f2011-06-23 00:26:20 +00002367 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002368 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2369 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt2949f022011-06-22 02:58:46 +00002370 } else if (FunctionTemplateDecl *Tmpl =
Alexis Hunt1da39282011-06-24 02:11:39 +00002371 dyn_cast<FunctionTemplateDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002372 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2373 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002374 RD, 0, ThisTy, Classification,
2375 llvm::makeArrayRef(&Arg, NumArgs),
Alexis Hunt080709f2011-06-23 00:26:20 +00002376 OCS, true);
2377 else
2378 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002379 0, llvm::makeArrayRef(&Arg, NumArgs),
2380 OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002381 } else {
2382 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002383 }
2384 }
2385
2386 OverloadCandidateSet::iterator Best;
2387 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2388 case OR_Success:
2389 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith83c478d2012-04-20 18:46:14 +00002390 Result->setKind(SpecialMemberOverloadResult::Success);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002391 break;
2392
2393 case OR_Deleted:
2394 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith852265f2012-03-30 20:53:28 +00002395 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002396 break;
2397
2398 case OR_Ambiguous:
Richard Smith852265f2012-03-30 20:53:28 +00002399 Result->setMethod(0);
2400 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2401 break;
2402
Alexis Hunteef8ee02011-06-10 03:50:41 +00002403 case OR_No_Viable_Function:
2404 Result->setMethod(0);
Richard Smith852265f2012-03-30 20:53:28 +00002405 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002406 break;
2407 }
2408
2409 return Result;
2410}
2411
2412/// \brief Look up the default constructor for the given class.
2413CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002414 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002415 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2416 false, false);
2417
2418 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002419}
2420
Alexis Hunt491ec602011-06-21 23:42:56 +00002421/// \brief Look up the copying constructor for the given class.
2422CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith83c478d2012-04-20 18:46:14 +00002423 unsigned Quals) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002424 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2425 "non-const, non-volatile qualifiers for copy ctor arg");
2426 SpecialMemberOverloadResult *Result =
2427 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2428 Quals & Qualifiers::Volatile, false, false, false);
2429
Alexis Hunt899bd442011-06-10 04:44:37 +00002430 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2431}
2432
Sebastian Redl22653ba2011-08-30 19:58:05 +00002433/// \brief Look up the moving constructor for the given class.
Richard Smith1c6461e2012-07-18 03:36:00 +00002434CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2435 unsigned Quals) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002436 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002437 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2438 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002439
2440 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2441}
2442
Douglas Gregor52b72822010-07-02 23:12:18 +00002443/// \brief Look up the constructors for the given class.
2444DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002445 // If the implicit constructors have not yet been declared, do so now.
Richard Smith7d125a12012-11-27 21:20:31 +00002446 if (CanDeclareSpecialMemberFunction(Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00002447 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002448 DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +00002449 if (Class->needsImplicitCopyConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002450 DeclareImplicitCopyConstructor(Class);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002451 if (getLangOpts().CPlusPlus0x && Class->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002452 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00002453 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002454
Douglas Gregor52b72822010-07-02 23:12:18 +00002455 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2456 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2457 return Class->lookup(Name);
2458}
2459
Alexis Hunt491ec602011-06-21 23:42:56 +00002460/// \brief Look up the copying assignment operator for the given class.
2461CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2462 unsigned Quals, bool RValueThis,
Richard Smith83c478d2012-04-20 18:46:14 +00002463 unsigned ThisQuals) {
Alexis Hunt491ec602011-06-21 23:42:56 +00002464 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2465 "non-const, non-volatile qualifiers for copy assignment arg");
2466 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2467 "non-const, non-volatile qualifiers for copy assignment this");
2468 SpecialMemberOverloadResult *Result =
2469 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2470 Quals & Qualifiers::Volatile, RValueThis,
2471 ThisQuals & Qualifiers::Const,
2472 ThisQuals & Qualifiers::Volatile);
2473
Alexis Hunt491ec602011-06-21 23:42:56 +00002474 return Result->getMethod();
2475}
2476
Sebastian Redl22653ba2011-08-30 19:58:05 +00002477/// \brief Look up the moving assignment operator for the given class.
2478CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith1c6461e2012-07-18 03:36:00 +00002479 unsigned Quals,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002480 bool RValueThis,
2481 unsigned ThisQuals) {
2482 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2483 "non-const, non-volatile qualifiers for copy assignment this");
2484 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002485 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2486 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002487 ThisQuals & Qualifiers::Const,
2488 ThisQuals & Qualifiers::Volatile);
2489
2490 return Result->getMethod();
2491}
2492
Douglas Gregore71edda2010-07-01 22:47:18 +00002493/// \brief Look for the destructor of the given class.
2494///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00002495/// During semantic analysis, this routine should be used in lieu of
2496/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00002497///
2498/// \returns The destructor for this class.
2499CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002500 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2501 false, false, false,
2502 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00002503}
2504
Richard Smithbcc22fc2012-03-09 08:00:36 +00002505/// LookupLiteralOperator - Determine which literal operator should be used for
2506/// a user-defined literal, per C++11 [lex.ext].
2507///
2508/// Normal overload resolution is not used to select which literal operator to
2509/// call for a user-defined literal. Look up the provided literal operator name,
2510/// and filter the results to the appropriate set for the given argument types.
2511Sema::LiteralOperatorLookupResult
2512Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2513 ArrayRef<QualType> ArgTys,
2514 bool AllowRawAndTemplate) {
2515 LookupName(R, S);
2516 assert(R.getResultKind() != LookupResult::Ambiguous &&
2517 "literal operator lookup can't be ambiguous");
2518
2519 // Filter the lookup results appropriately.
2520 LookupResult::Filter F = R.makeFilter();
2521
2522 bool FoundTemplate = false;
2523 bool FoundRaw = false;
2524 bool FoundExactMatch = false;
2525
2526 while (F.hasNext()) {
2527 Decl *D = F.next();
2528 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2529 D = USD->getTargetDecl();
2530
2531 bool IsTemplate = isa<FunctionTemplateDecl>(D);
2532 bool IsRaw = false;
2533 bool IsExactMatch = false;
2534
2535 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2536 if (FD->getNumParams() == 1 &&
2537 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2538 IsRaw = true;
2539 else {
2540 IsExactMatch = true;
2541 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2542 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2543 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2544 IsExactMatch = false;
2545 break;
2546 }
2547 }
2548 }
2549 }
2550
2551 if (IsExactMatch) {
2552 FoundExactMatch = true;
2553 AllowRawAndTemplate = false;
2554 if (FoundRaw || FoundTemplate) {
2555 // Go through again and remove the raw and template decls we've
2556 // already found.
2557 F.restart();
2558 FoundRaw = FoundTemplate = false;
2559 }
2560 } else if (AllowRawAndTemplate && (IsTemplate || IsRaw)) {
2561 FoundTemplate |= IsTemplate;
2562 FoundRaw |= IsRaw;
2563 } else {
2564 F.erase();
2565 }
2566 }
2567
2568 F.done();
2569
2570 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2571 // parameter type, that is used in preference to a raw literal operator
2572 // or literal operator template.
2573 if (FoundExactMatch)
2574 return LOLR_Cooked;
2575
2576 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2577 // operator template, but not both.
2578 if (FoundRaw && FoundTemplate) {
2579 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
2580 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2581 Decl *D = *I;
2582 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2583 D = USD->getTargetDecl();
2584 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2585 D = FunTmpl->getTemplatedDecl();
2586 NoteOverloadCandidate(cast<FunctionDecl>(D));
2587 }
2588 return LOLR_Error;
2589 }
2590
2591 if (FoundRaw)
2592 return LOLR_Raw;
2593
2594 if (FoundTemplate)
2595 return LOLR_Template;
2596
2597 // Didn't find anything we could use.
2598 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2599 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
2600 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRawAndTemplate;
2601 return LOLR_Error;
2602}
2603
John McCall8fe68082010-01-26 07:16:45 +00002604void ADLResult::insert(NamedDecl *New) {
2605 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2606
2607 // If we haven't yet seen a decl for this key, or the last decl
2608 // was exactly this one, we're done.
2609 if (Old == 0 || Old == New) {
2610 Old = New;
2611 return;
2612 }
2613
2614 // Otherwise, decide which is a more recent redeclaration.
2615 FunctionDecl *OldFD, *NewFD;
2616 if (isa<FunctionTemplateDecl>(New)) {
2617 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2618 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2619 } else {
2620 OldFD = cast<FunctionDecl>(Old);
2621 NewFD = cast<FunctionDecl>(New);
2622 }
2623
2624 FunctionDecl *Cursor = NewFD;
2625 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002626 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00002627
2628 // If we got to the end without finding OldFD, OldFD is the newer
2629 // declaration; leave things as they are.
2630 if (!Cursor) return;
2631
2632 // If we do find OldFD, then NewFD is newer.
2633 if (Cursor == OldFD) break;
2634
2635 // Otherwise, keep looking.
2636 }
2637
2638 Old = New;
2639}
2640
Sebastian Redlc057f422009-10-23 19:23:15 +00002641void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Richard Smithe06a2c12012-02-25 06:24:24 +00002642 SourceLocation Loc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002643 llvm::ArrayRef<Expr *> Args,
Richard Smithb6626742012-10-18 17:56:02 +00002644 ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002645 // Find all of the associated namespaces and classes based on the
2646 // arguments we have.
2647 AssociatedNamespaceSet AssociatedNamespaces;
2648 AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00002649 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCallc7e8e792009-08-07 22:18:02 +00002650 AssociatedNamespaces,
2651 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002652
Sebastian Redlc057f422009-10-23 19:23:15 +00002653 QualType T1, T2;
2654 if (Operator) {
2655 T1 = Args[0]->getType();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002656 if (Args.size() >= 2)
Sebastian Redlc057f422009-10-23 19:23:15 +00002657 T2 = Args[1]->getType();
2658 }
2659
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002660 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002661 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2662 // and let Y be the lookup set produced by argument dependent
2663 // lookup (defined as follows). If X contains [...] then Y is
2664 // empty. Otherwise Y is the set of declarations found in the
2665 // namespaces associated with the argument types as described
2666 // below. The set of declarations found by the lookup of the name
2667 // is the union of X and Y.
2668 //
2669 // Here, we compute Y and add its members to the overloaded
2670 // candidate set.
2671 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00002672 NSEnd = AssociatedNamespaces.end();
2673 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002674 // When considering an associated namespace, the lookup is the
2675 // same as the lookup performed when the associated namespace is
2676 // used as a qualifier (3.4.3.2) except that:
2677 //
2678 // -- Any using-directives in the associated namespace are
2679 // ignored.
2680 //
John McCallc7e8e792009-08-07 22:18:02 +00002681 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002682 // associated classes are visible within their respective
2683 // namespaces even if they are not visible during an ordinary
2684 // lookup (11.4).
2685 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00002686 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00002687 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00002688 // If the only declaration here is an ordinary friend, consider
2689 // it only if it was declared in an associated classes.
2690 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00002691 DeclContext *LexDC = D->getLexicalDeclContext();
2692 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2693 continue;
2694 }
Mike Stump11289f42009-09-09 15:08:12 +00002695
John McCall91f61fc2010-01-26 06:04:06 +00002696 if (isa<UsingShadowDecl>(D))
2697 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002698
John McCall91f61fc2010-01-26 06:04:06 +00002699 if (isa<FunctionDecl>(D)) {
2700 if (Operator &&
2701 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2702 T1, T2, Context))
2703 continue;
John McCall8fe68082010-01-26 07:16:45 +00002704 } else if (!isa<FunctionTemplateDecl>(D))
2705 continue;
2706
2707 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002708 }
2709 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002710}
Douglas Gregor2d435302009-12-30 17:04:44 +00002711
2712//----------------------------------------------------------------------------
2713// Search for all visible declarations.
2714//----------------------------------------------------------------------------
2715VisibleDeclConsumer::~VisibleDeclConsumer() { }
2716
2717namespace {
2718
2719class ShadowContextRAII;
2720
2721class VisibleDeclsRecord {
2722public:
2723 /// \brief An entry in the shadow map, which is optimized to store a
2724 /// single declaration (the common case) but can also store a list
2725 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002726 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00002727
2728private:
2729 /// \brief A mapping from declaration names to the declarations that have
2730 /// this name within a particular scope.
2731 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2732
2733 /// \brief A list of shadow maps, which is used to model name hiding.
2734 std::list<ShadowMap> ShadowMaps;
2735
2736 /// \brief The declaration contexts we have already visited.
2737 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2738
2739 friend class ShadowContextRAII;
2740
2741public:
2742 /// \brief Determine whether we have already visited this context
2743 /// (and, if not, note that we are going to visit that context now).
2744 bool visitedContext(DeclContext *Ctx) {
2745 return !VisitedContexts.insert(Ctx);
2746 }
2747
Douglas Gregor39982192010-08-15 06:18:01 +00002748 bool alreadyVisitedContext(DeclContext *Ctx) {
2749 return VisitedContexts.count(Ctx);
2750 }
2751
Douglas Gregor2d435302009-12-30 17:04:44 +00002752 /// \brief Determine whether the given declaration is hidden in the
2753 /// current scope.
2754 ///
2755 /// \returns the declaration that hides the given declaration, or
2756 /// NULL if no such declaration exists.
2757 NamedDecl *checkHidden(NamedDecl *ND);
2758
2759 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002760 void add(NamedDecl *ND) {
2761 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2762 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002763};
2764
2765/// \brief RAII object that records when we've entered a shadow context.
2766class ShadowContextRAII {
2767 VisibleDeclsRecord &Visible;
2768
2769 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2770
2771public:
2772 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2773 Visible.ShadowMaps.push_back(ShadowMap());
2774 }
2775
2776 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00002777 Visible.ShadowMaps.pop_back();
2778 }
2779};
2780
2781} // end anonymous namespace
2782
Douglas Gregor2d435302009-12-30 17:04:44 +00002783NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002784 // Look through using declarations.
2785 ND = ND->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002786
Douglas Gregor2d435302009-12-30 17:04:44 +00002787 unsigned IDNS = ND->getIdentifierNamespace();
2788 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2789 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2790 SM != SMEnd; ++SM) {
2791 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2792 if (Pos == SM->end())
2793 continue;
2794
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002795 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor2d435302009-12-30 17:04:44 +00002796 IEnd = Pos->second.end();
2797 I != IEnd; ++I) {
2798 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +00002799 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002800 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00002801 Decl::IDNS_ObjCProtocol)))
2802 continue;
2803
2804 // Protocols are in distinct namespaces from everything else.
2805 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2806 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2807 (*I)->getIdentifierNamespace() != IDNS)
2808 continue;
2809
Douglas Gregor09bbc652010-01-14 15:47:35 +00002810 // Functions and function templates in the same scope overload
2811 // rather than hide. FIXME: Look for hiding based on function
2812 // signatures!
Douglas Gregor200c99d2010-01-14 03:35:48 +00002813 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002814 ND->isFunctionOrFunctionTemplate() &&
2815 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002816 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002817
Douglas Gregor2d435302009-12-30 17:04:44 +00002818 // We've found a declaration that hides this one.
2819 return *I;
2820 }
2821 }
2822
2823 return 0;
2824}
2825
2826static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2827 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002828 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002829 VisibleDeclConsumer &Consumer,
2830 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002831 if (!Ctx)
2832 return;
2833
Douglas Gregor2d435302009-12-30 17:04:44 +00002834 // Make sure we don't visit the same context twice.
2835 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2836 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002837
Douglas Gregor7454c562010-07-02 20:37:36 +00002838 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2839 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2840
Douglas Gregor2d435302009-12-30 17:04:44 +00002841 // Enumerate all of the results in this context.
Nick Lewyckyc3921482012-04-03 21:44:08 +00002842 for (DeclContext::all_lookups_iterator L = Ctx->lookups_begin(),
2843 LEnd = Ctx->lookups_end();
2844 L != LEnd; ++L) {
2845 for (DeclContext::lookup_result R = *L; R.first != R.second; ++R.first) {
2846 if (NamedDecl *ND = dyn_cast<NamedDecl>(*R.first)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00002847 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00002848 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002849 Visited.add(ND);
2850 }
Douglas Gregora3b23b02010-12-09 21:44:02 +00002851 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002852 }
2853 }
2854
2855 // Traverse using directives for qualified name lookup.
2856 if (QualifiedNameLookup) {
2857 ShadowContextRAII Shadow(Visited);
2858 DeclContext::udir_iterator I, E;
2859 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002860 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002861 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002862 }
2863 }
2864
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002865 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00002866 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00002867 if (!Record->hasDefinition())
2868 return;
2869
Douglas Gregor2d435302009-12-30 17:04:44 +00002870 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2871 BEnd = Record->bases_end();
2872 B != BEnd; ++B) {
2873 QualType BaseType = B->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002874
Douglas Gregor2d435302009-12-30 17:04:44 +00002875 // Don't look into dependent bases, because name lookup can't look
2876 // there anyway.
2877 if (BaseType->isDependentType())
2878 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002879
Douglas Gregor2d435302009-12-30 17:04:44 +00002880 const RecordType *Record = BaseType->getAs<RecordType>();
2881 if (!Record)
2882 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002883
Douglas Gregor2d435302009-12-30 17:04:44 +00002884 // FIXME: It would be nice to be able to determine whether referencing
2885 // a particular member would be ambiguous. For example, given
2886 //
2887 // struct A { int member; };
2888 // struct B { int member; };
2889 // struct C : A, B { };
2890 //
2891 // void f(C *c) { c->### }
2892 //
2893 // accessing 'member' would result in an ambiguity. However, we
2894 // could be smart enough to qualify the member with the base
2895 // class, e.g.,
2896 //
2897 // c->B::member
2898 //
2899 // or
2900 //
2901 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002902
Douglas Gregor2d435302009-12-30 17:04:44 +00002903 // Find results in this base class (and its bases).
2904 ShadowContextRAII Shadow(Visited);
2905 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002906 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002907 }
2908 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002909
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002910 // Traverse the contexts of Objective-C classes.
2911 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2912 // Traverse categories.
2913 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2914 Category; Category = Category->getNextClassCategory()) {
2915 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002916 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002917 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002918 }
2919
2920 // Traverse protocols.
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002921 for (ObjCInterfaceDecl::all_protocol_iterator
2922 I = IFace->all_referenced_protocol_begin(),
2923 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002924 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002925 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002926 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002927 }
2928
2929 // Traverse the superclass.
2930 if (IFace->getSuperClass()) {
2931 ShadowContextRAII Shadow(Visited);
2932 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002933 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002934 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002935
Douglas Gregor0b59e802010-04-19 18:02:19 +00002936 // If there is an implementation, traverse it. We do this to find
2937 // synthesized ivars.
2938 if (IFace->getImplementation()) {
2939 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002940 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky13668f22012-04-03 20:26:45 +00002941 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor0b59e802010-04-19 18:02:19 +00002942 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002943 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2944 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2945 E = Protocol->protocol_end(); I != E; ++I) {
2946 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002947 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002948 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002949 }
2950 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2951 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2952 E = Category->protocol_end(); I != E; ++I) {
2953 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002954 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002955 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002956 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002957
Douglas Gregor0b59e802010-04-19 18:02:19 +00002958 // If there is an implementation, traverse it.
2959 if (Category->getImplementation()) {
2960 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002961 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00002962 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002963 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002964 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002965}
2966
2967static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2968 UnqualUsingDirectiveSet &UDirs,
2969 VisibleDeclConsumer &Consumer,
2970 VisibleDeclsRecord &Visited) {
2971 if (!S)
2972 return;
2973
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002974 if (!S->getEntity() ||
2975 (!S->getParent() &&
Douglas Gregor39982192010-08-15 06:18:01 +00002976 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002977 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2978 // Walk through the declarations in this Scope.
2979 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2980 D != DEnd; ++D) {
John McCall48871652010-08-21 09:40:31 +00002981 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor4a814562011-12-14 16:03:29 +00002982 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00002983 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002984 Visited.add(ND);
2985 }
2986 }
2987 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002988
Douglas Gregor66230062010-03-15 14:33:29 +00002989 // FIXME: C++ [temp.local]p8
Douglas Gregor2d435302009-12-30 17:04:44 +00002990 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00002991 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002992 // Look into this scope's declaration context, along with any of its
2993 // parent lookup contexts (e.g., enclosing classes), up to the point
2994 // where we hit the context stored in the next outer scope.
2995 Entity = (DeclContext *)S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00002996 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002997
Douglas Gregorea166062010-03-15 15:26:48 +00002998 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00002999 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003000 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3001 if (Method->isInstanceMethod()) {
3002 // For instance methods, look for ivars in the method's interface.
3003 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3004 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003005 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003006 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Fariborz Jahanian97d744b2011-08-31 22:24:06 +00003007 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003008 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003009 }
3010
3011 // We've already performed all of the name lookup that we need
3012 // to for Objective-C methods; the next context will be the
3013 // outer scope.
3014 break;
3015 }
3016
Douglas Gregor2d435302009-12-30 17:04:44 +00003017 if (Ctx->isFunctionOrMethod())
3018 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003019
3020 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003021 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003022 }
3023 } else if (!S->getParent()) {
3024 // Look into the translation unit scope. We walk through the translation
3025 // unit's declaration context, because the Scope itself won't have all of
3026 // the declarations if we loaded a precompiled header.
3027 // FIXME: We would like the translation unit's Scope object to point to the
3028 // translation unit, so we don't need this special "if" branch. However,
3029 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003030 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00003031 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003032 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00003033 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003034 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003035 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003036 }
3037
Douglas Gregor2d435302009-12-30 17:04:44 +00003038 if (Entity) {
3039 // Lookup visible declarations in any namespaces found by using
3040 // directives.
3041 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
3042 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
3043 for (; UI != UEnd; ++UI)
3044 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003045 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003046 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003047 }
3048
3049 // Lookup names in the parent scope.
3050 ShadowContextRAII Shadow(Visited);
3051 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3052}
3053
3054void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003055 VisibleDeclConsumer &Consumer,
3056 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003057 // Determine the set of using directives available during
3058 // unqualified name lookup.
3059 Scope *Initial = S;
3060 UnqualUsingDirectiveSet UDirs;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003061 if (getLangOpts().CPlusPlus) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003062 // Find the first namespace or translation-unit scope.
3063 while (S && !isNamespaceOrTranslationUnitScope(S))
3064 S = S->getParent();
3065
3066 UDirs.visitScopeChain(Initial, S);
3067 }
3068 UDirs.done();
3069
3070 // Look for visible declarations.
3071 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3072 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003073 if (!IncludeGlobalScope)
3074 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003075 ShadowContextRAII Shadow(Visited);
3076 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3077}
3078
3079void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003080 VisibleDeclConsumer &Consumer,
3081 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003082 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3083 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003084 if (!IncludeGlobalScope)
3085 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003086 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003087 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003088 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003089}
3090
Chris Lattner43e7f312011-02-18 02:08:43 +00003091/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003092/// If GnuLabelLoc is a valid source location, then this is a definition
3093/// of an __label__ label name, otherwise it is a normal label definition
3094/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003095LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003096 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003097 // Do a lookup to see if we have a label with this name already.
Chris Lattner43e7f312011-02-18 02:08:43 +00003098 NamedDecl *Res = 0;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003099
3100 if (GnuLabelLoc.isValid()) {
3101 // Local label definitions always shadow existing labels.
3102 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3103 Scope *S = CurScope;
3104 PushOnScopeChains(Res, S, true);
3105 return cast<LabelDecl>(Res);
3106 }
3107
3108 // Not a GNU local label.
3109 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3110 // If we found a label, check to see if it is in the same context as us.
3111 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003112 if (Res && Res->getDeclContext() != CurContext)
3113 Res = 0;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003114 if (Res == 0) {
3115 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003116 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3117 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003118 assert(S && "Not in a function?");
3119 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003120 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003121 return cast<LabelDecl>(Res);
3122}
3123
3124//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003125// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003126//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003127
3128namespace {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003129
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003130typedef llvm::SmallVector<TypoCorrection, 1> TypoResultList;
3131typedef llvm::StringMap<TypoResultList, llvm::BumpPtrAllocator> TypoResultsMap;
Benjamin Kramer73faad62012-04-14 08:26:28 +00003132typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003133
3134static const unsigned MaxTypoDistanceResultSets = 5;
3135
Douglas Gregor2d435302009-12-30 17:04:44 +00003136class TypoCorrectionConsumer : public VisibleDeclConsumer {
3137 /// \brief The name written that is a typo in the source.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003138 StringRef Typo;
Douglas Gregor2d435302009-12-30 17:04:44 +00003139
3140 /// \brief The results found that have the smallest edit distance
3141 /// found (so far) with the typo name.
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003142 ///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003143 /// The pointer value being set to the current DeclContext indicates
3144 /// whether there is a keyword with this name.
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003145 TypoEditDistanceMap CorrectionResults;
Douglas Gregor2d435302009-12-30 17:04:44 +00003146
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003147 Sema &SemaRef;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003148
Douglas Gregor2d435302009-12-30 17:04:44 +00003149public:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003150 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003151 : Typo(Typo->getName()),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003152 SemaRef(SemaRef) { }
Douglas Gregor2d435302009-12-30 17:04:44 +00003153
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003154 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3155 bool InBaseClass);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003156 void FoundName(StringRef Name);
3157 void addKeywordResult(StringRef Keyword);
3158 void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003159 NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003160 void addCorrection(TypoCorrection Correction);
Douglas Gregor2d435302009-12-30 17:04:44 +00003161
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003162 typedef TypoResultsMap::iterator result_iterator;
3163 typedef TypoEditDistanceMap::iterator distance_iterator;
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003164 distance_iterator begin() { return CorrectionResults.begin(); }
3165 distance_iterator end() { return CorrectionResults.end(); }
3166 void erase(distance_iterator I) { CorrectionResults.erase(I); }
3167 unsigned size() const { return CorrectionResults.size(); }
3168 bool empty() const { return CorrectionResults.empty(); }
Douglas Gregor2d435302009-12-30 17:04:44 +00003169
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003170 TypoResultList &operator[](StringRef Name) {
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003171 return CorrectionResults.begin()->second[Name];
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003172 }
3173
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003174 unsigned getBestEditDistance(bool Normalized) {
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003175 if (CorrectionResults.empty())
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003176 return (std::numeric_limits<unsigned>::max)();
3177
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003178 unsigned BestED = CorrectionResults.begin()->first;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003179 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003180 }
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003181
3182 TypoResultsMap &getBestResults() {
3183 return CorrectionResults.begin()->second;
3184 }
3185
Douglas Gregor2d435302009-12-30 17:04:44 +00003186};
3187
3188}
3189
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003190void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003191 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003192 // Don't consider hidden names for typo correction.
3193 if (Hiding)
3194 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003195
Douglas Gregor2d435302009-12-30 17:04:44 +00003196 // Only consider entities with identifiers for names, ignoring
3197 // special names (constructors, overloaded operators, selectors,
3198 // etc.).
3199 IdentifierInfo *Name = ND->getIdentifier();
3200 if (!Name)
3201 return;
3202
Douglas Gregor57756ea2010-10-14 22:11:03 +00003203 FoundName(Name->getName());
3204}
3205
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003206void TypoCorrectionConsumer::FoundName(StringRef Name) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003207 // Use a simple length-based heuristic to determine the minimum possible
3208 // edit distance. If the minimum isn't good enough, bail out early.
3209 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003210 if (MinED && Typo.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00003211 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003212
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003213 // Compute an upper bound on the allowable edit distance, so that the
3214 // edit-distance algorithm can short-circuit.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003215 unsigned UpperBound = (Typo.size() + 2) / 3;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003216
Douglas Gregor2d435302009-12-30 17:04:44 +00003217 // Compute the edit distance between the typo and the name of this
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003218 // entity, and add the identifier to the list of results.
3219 addName(Name, NULL, Typo.edit_distance(Name, true, UpperBound));
Douglas Gregor2d435302009-12-30 17:04:44 +00003220}
3221
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003222void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003223 // Compute the edit distance between the typo and this keyword,
3224 // and add the keyword to the list of results.
3225 addName(Keyword, NULL, Typo.edit_distance(Keyword), NULL, true);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003226}
3227
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003228void TypoCorrectionConsumer::addName(StringRef Name,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003229 NamedDecl *ND,
3230 unsigned Distance,
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003231 NestedNameSpecifier *NNS,
3232 bool isKeyword) {
3233 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
3234 if (isKeyword) TC.makeKeyword();
3235 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003236}
3237
3238void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003239 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003240 TypoResultList &CList =
3241 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003242
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003243 if (!CList.empty() && !CList.back().isResolved())
3244 CList.pop_back();
3245 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3246 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3247 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3248 RI != RIEnd; ++RI) {
3249 // If the Correction refers to a decl already in the result list,
3250 // replace the existing result if the string representation of Correction
3251 // comes before the current result alphabetically, then stop as there is
3252 // nothing more to be done to add Correction to the candidate set.
3253 if (RI->getCorrectionDecl() == NewND) {
3254 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3255 *RI = Correction;
3256 return;
3257 }
3258 }
3259 }
3260 if (CList.empty() || Correction.isResolved())
3261 CList.push_back(Correction);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003262
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003263 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
3264 erase(llvm::prior(CorrectionResults.end()));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003265}
3266
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003267// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3268// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3269// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3270static void getNestedNameSpecifierIdentifiers(
3271 NestedNameSpecifier *NNS,
3272 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3273 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3274 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3275 else
3276 Identifiers.clear();
3277
3278 const IdentifierInfo *II = NULL;
3279
3280 switch (NNS->getKind()) {
3281 case NestedNameSpecifier::Identifier:
3282 II = NNS->getAsIdentifier();
3283 break;
3284
3285 case NestedNameSpecifier::Namespace:
3286 if (NNS->getAsNamespace()->isAnonymousNamespace())
3287 return;
3288 II = NNS->getAsNamespace()->getIdentifier();
3289 break;
3290
3291 case NestedNameSpecifier::NamespaceAlias:
3292 II = NNS->getAsNamespaceAlias()->getIdentifier();
3293 break;
3294
3295 case NestedNameSpecifier::TypeSpecWithTemplate:
3296 case NestedNameSpecifier::TypeSpec:
3297 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3298 break;
3299
3300 case NestedNameSpecifier::Global:
3301 return;
3302 }
3303
3304 if (II)
3305 Identifiers.push_back(II);
3306}
3307
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003308namespace {
3309
3310class SpecifierInfo {
3311 public:
3312 DeclContext* DeclCtx;
3313 NestedNameSpecifier* NameSpecifier;
3314 unsigned EditDistance;
3315
3316 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3317 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3318};
3319
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003320typedef SmallVector<DeclContext*, 4> DeclContextList;
3321typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003322
3323class NamespaceSpecifierSet {
3324 ASTContext &Context;
3325 DeclContextList CurContextChain;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003326 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3327 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003328 bool isSorted;
3329
3330 SpecifierInfoList Specifiers;
3331 llvm::SmallSetVector<unsigned, 4> Distances;
3332 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3333
3334 /// \brief Helper for building the list of DeclContexts between the current
3335 /// context and the top of the translation unit
3336 static DeclContextList BuildContextChain(DeclContext *Start);
3337
3338 void SortNamespaces();
3339
3340 public:
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003341 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3342 CXXScopeSpec *CurScopeSpec)
Benjamin Kramerde1d6232011-07-05 09:46:31 +00003343 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003344 isSorted(true) {
3345 if (CurScopeSpec && CurScopeSpec->getScopeRep())
3346 getNestedNameSpecifierIdentifiers(CurScopeSpec->getScopeRep(),
3347 CurNameSpecifierIdentifiers);
3348 // Build the list of identifiers that would be used for an absolute
Benjamin Kramer474261a2012-06-02 10:20:41 +00003349 // (from the global context) NestedNameSpecifier referring to the current
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003350 // context.
3351 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3352 CEnd = CurContextChain.rend();
3353 C != CEnd; ++C) {
3354 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3355 CurContextIdentifiers.push_back(ND->getIdentifier());
3356 }
3357 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003358
3359 /// \brief Add the namespace to the set, computing the corresponding
3360 /// NestedNameSpecifier and its distance in the process.
3361 void AddNamespace(NamespaceDecl *ND);
3362
3363 typedef SpecifierInfoList::iterator iterator;
3364 iterator begin() {
3365 if (!isSorted) SortNamespaces();
3366 return Specifiers.begin();
3367 }
3368 iterator end() { return Specifiers.end(); }
3369};
3370
3371}
3372
3373DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003374 assert(Start && "Bulding a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003375 DeclContextList Chain;
3376 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3377 DC = DC->getLookupParent()) {
3378 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3379 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3380 !(ND && ND->isAnonymousNamespace()))
3381 Chain.push_back(DC->getPrimaryContext());
3382 }
3383 return Chain;
3384}
3385
3386void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003387 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003388 sortedDistances.append(Distances.begin(), Distances.end());
3389
3390 if (sortedDistances.size() > 1)
3391 std::sort(sortedDistances.begin(), sortedDistances.end());
3392
3393 Specifiers.clear();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003394 for (SmallVector<unsigned, 4>::iterator DI = sortedDistances.begin(),
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003395 DIEnd = sortedDistances.end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003396 DI != DIEnd; ++DI) {
3397 SpecifierInfoList &SpecList = DistanceMap[*DI];
3398 Specifiers.append(SpecList.begin(), SpecList.end());
3399 }
3400
3401 isSorted = true;
3402}
3403
3404void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003405 DeclContext *Ctx = cast<DeclContext>(ND);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003406 NestedNameSpecifier *NNS = NULL;
3407 unsigned NumSpecifiers = 0;
3408 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003409 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003410
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003411 // Eliminate common elements from the two DeclContext chains.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003412 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3413 CEnd = CurContextChain.rend();
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003414 C != CEnd && !NamespaceDeclChain.empty() &&
3415 NamespaceDeclChain.back() == *C; ++C) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003416 NamespaceDeclChain.pop_back();
3417 }
3418
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003419 // Add an explicit leading '::' specifier if needed.
3420 if (NamespaceDecl *ND =
Kaelyn Uhrain618f97c2012-02-15 22:59:03 +00003421 NamespaceDeclChain.empty() ? NULL :
3422 dyn_cast_or_null<NamespaceDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003423 IdentifierInfo *Name = ND->getIdentifier();
3424 if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3425 Name) != CurContextIdentifiers.end() ||
3426 std::find(CurNameSpecifierIdentifiers.begin(),
3427 CurNameSpecifierIdentifiers.end(),
3428 Name) != CurNameSpecifierIdentifiers.end()) {
3429 NamespaceDeclChain = FullNamespaceDeclChain;
3430 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3431 }
3432 }
3433
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003434 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3435 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3436 CEnd = NamespaceDeclChain.rend();
3437 C != CEnd; ++C) {
3438 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3439 if (ND) {
3440 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3441 ++NumSpecifiers;
3442 }
3443 }
3444
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003445 // If the built NestedNameSpecifier would be replacing an existing
3446 // NestedNameSpecifier, use the number of component identifiers that
3447 // would need to be changed as the edit distance instead of the number
3448 // of components in the built NestedNameSpecifier.
3449 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3450 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3451 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3452 NumSpecifiers = llvm::ComputeEditDistance(
3453 llvm::ArrayRef<const IdentifierInfo*>(CurNameSpecifierIdentifiers),
3454 llvm::ArrayRef<const IdentifierInfo*>(NewNameSpecifierIdentifiers));
3455 }
3456
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003457 isSorted = false;
3458 Distances.insert(NumSpecifiers);
3459 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003460}
3461
Douglas Gregord507d772010-10-20 03:06:34 +00003462/// \brief Perform name lookup for a possible result for typo correction.
3463static void LookupPotentialTypoResult(Sema &SemaRef,
3464 LookupResult &Res,
3465 IdentifierInfo *Name,
3466 Scope *S, CXXScopeSpec *SS,
3467 DeclContext *MemberContext,
3468 bool EnteringContext,
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003469 bool isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00003470 Res.suppressDiagnostics();
3471 Res.clear();
3472 Res.setLookupName(Name);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003473 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00003474 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003475 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00003476 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3477 Res.addDecl(Ivar);
3478 Res.resolveKind();
3479 return;
3480 }
3481 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003482
Douglas Gregord507d772010-10-20 03:06:34 +00003483 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3484 Res.addDecl(Prop);
3485 Res.resolveKind();
3486 return;
3487 }
3488 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003489
Douglas Gregord507d772010-10-20 03:06:34 +00003490 SemaRef.LookupQualifiedName(Res, MemberContext);
3491 return;
3492 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003493
3494 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00003495 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003496
Douglas Gregord507d772010-10-20 03:06:34 +00003497 // Fake ivar lookup; this should really be part of
3498 // LookupParsedName.
3499 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3500 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003501 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00003502 (Res.isSingleResult() &&
3503 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003504 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00003505 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3506 Res.addDecl(IV);
3507 Res.resolveKind();
3508 }
3509 }
3510 }
3511}
3512
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003513/// \brief Add keywords to the consumer as possible typo corrections.
3514static void AddKeywordsToConsumer(Sema &SemaRef,
3515 TypoCorrectionConsumer &Consumer,
Richard Smithb3a1df02012-06-08 21:35:42 +00003516 Scope *S, CorrectionCandidateCallback &CCC,
3517 bool AfterNestedNameSpecifier) {
3518 if (AfterNestedNameSpecifier) {
3519 // For 'X::', we know exactly which keywords can appear next.
3520 Consumer.addKeywordResult("template");
3521 if (CCC.WantExpressionKeywords)
3522 Consumer.addKeywordResult("operator");
3523 return;
3524 }
3525
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003526 if (CCC.WantObjCSuper)
3527 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003528
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003529 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003530 // Add type-specifier keywords to the set of results.
3531 const char *CTypeSpecs[] = {
3532 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00003533 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003534 "_Complex", "_Imaginary",
3535 // storage-specifiers as well
3536 "extern", "inline", "static", "typedef"
3537 };
3538
3539 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3540 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3541 Consumer.addKeywordResult(CTypeSpecs[I]);
3542
David Blaikiebbafb8a2012-03-11 07:00:24 +00003543 if (SemaRef.getLangOpts().C99)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003544 Consumer.addKeywordResult("restrict");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003545 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003546 Consumer.addKeywordResult("bool");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003547 else if (SemaRef.getLangOpts().C99)
Douglas Gregor3b22a882011-07-01 21:27:45 +00003548 Consumer.addKeywordResult("_Bool");
3549
David Blaikiebbafb8a2012-03-11 07:00:24 +00003550 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003551 Consumer.addKeywordResult("class");
3552 Consumer.addKeywordResult("typename");
3553 Consumer.addKeywordResult("wchar_t");
3554
David Blaikiebbafb8a2012-03-11 07:00:24 +00003555 if (SemaRef.getLangOpts().CPlusPlus0x) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003556 Consumer.addKeywordResult("char16_t");
3557 Consumer.addKeywordResult("char32_t");
3558 Consumer.addKeywordResult("constexpr");
3559 Consumer.addKeywordResult("decltype");
3560 Consumer.addKeywordResult("thread_local");
3561 }
3562 }
3563
David Blaikiebbafb8a2012-03-11 07:00:24 +00003564 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003565 Consumer.addKeywordResult("typeof");
3566 }
3567
David Blaikiebbafb8a2012-03-11 07:00:24 +00003568 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003569 Consumer.addKeywordResult("const_cast");
3570 Consumer.addKeywordResult("dynamic_cast");
3571 Consumer.addKeywordResult("reinterpret_cast");
3572 Consumer.addKeywordResult("static_cast");
3573 }
3574
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003575 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003576 Consumer.addKeywordResult("sizeof");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003577 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003578 Consumer.addKeywordResult("false");
3579 Consumer.addKeywordResult("true");
3580 }
3581
David Blaikiebbafb8a2012-03-11 07:00:24 +00003582 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003583 const char *CXXExprs[] = {
3584 "delete", "new", "operator", "throw", "typeid"
3585 };
3586 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3587 for (unsigned I = 0; I != NumCXXExprs; ++I)
3588 Consumer.addKeywordResult(CXXExprs[I]);
3589
3590 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3591 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3592 Consumer.addKeywordResult("this");
3593
David Blaikiebbafb8a2012-03-11 07:00:24 +00003594 if (SemaRef.getLangOpts().CPlusPlus0x) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003595 Consumer.addKeywordResult("alignof");
3596 Consumer.addKeywordResult("nullptr");
3597 }
3598 }
Jordan Rose58d54722012-06-30 21:33:57 +00003599
3600 if (SemaRef.getLangOpts().C11) {
3601 // FIXME: We should not suggest _Alignof if the alignof macro
3602 // is present.
3603 Consumer.addKeywordResult("_Alignof");
3604 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003605 }
3606
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003607 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003608 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3609 // Statements.
3610 const char *CStmts[] = {
3611 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3612 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3613 for (unsigned I = 0; I != NumCStmts; ++I)
3614 Consumer.addKeywordResult(CStmts[I]);
3615
David Blaikiebbafb8a2012-03-11 07:00:24 +00003616 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003617 Consumer.addKeywordResult("catch");
3618 Consumer.addKeywordResult("try");
3619 }
3620
3621 if (S && S->getBreakParent())
3622 Consumer.addKeywordResult("break");
3623
3624 if (S && S->getContinueParent())
3625 Consumer.addKeywordResult("continue");
3626
3627 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3628 Consumer.addKeywordResult("case");
3629 Consumer.addKeywordResult("default");
3630 }
3631 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003632 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003633 Consumer.addKeywordResult("namespace");
3634 Consumer.addKeywordResult("template");
3635 }
3636
3637 if (S && S->isClassScope()) {
3638 Consumer.addKeywordResult("explicit");
3639 Consumer.addKeywordResult("friend");
3640 Consumer.addKeywordResult("mutable");
3641 Consumer.addKeywordResult("private");
3642 Consumer.addKeywordResult("protected");
3643 Consumer.addKeywordResult("public");
3644 Consumer.addKeywordResult("virtual");
3645 }
3646 }
3647
David Blaikiebbafb8a2012-03-11 07:00:24 +00003648 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003649 Consumer.addKeywordResult("using");
3650
David Blaikiebbafb8a2012-03-11 07:00:24 +00003651 if (SemaRef.getLangOpts().CPlusPlus0x)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003652 Consumer.addKeywordResult("static_assert");
3653 }
3654 }
3655}
3656
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003657static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3658 TypoCorrection &Candidate) {
3659 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3660 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3661}
3662
Douglas Gregor2d435302009-12-30 17:04:44 +00003663/// \brief Try to "correct" a typo in the source code by finding
3664/// visible declarations whose names are similar to the name that was
3665/// present in the source code.
3666///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003667/// \param TypoName the \c DeclarationNameInfo structure that contains
3668/// the name that was present in the source code along with its location.
3669///
3670/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00003671///
3672/// \param S the scope in which name lookup occurs.
3673///
3674/// \param SS the nested-name-specifier that precedes the name we're
3675/// looking for, if present.
3676///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003677/// \param CCC A CorrectionCandidateCallback object that provides further
3678/// validation of typo correction candidates. It also provides flags for
3679/// determining the set of keywords permitted.
3680///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003681/// \param MemberContext if non-NULL, the context in which to look for
3682/// a member access expression.
3683///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003684/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00003685/// the nested-name-specifier SS.
3686///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003687/// \param OPT when non-NULL, the search for visible declarations will
3688/// also walk the protocols in the qualified interfaces of \p OPT.
3689///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003690/// \returns a \c TypoCorrection containing the corrected name if the typo
3691/// along with information such as the \c NamedDecl where the corrected name
3692/// was declared, and any additional \c NestedNameSpecifier needed to access
3693/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3694TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3695 Sema::LookupNameKind LookupKind,
3696 Scope *S, CXXScopeSpec *SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00003697 CorrectionCandidateCallback &CCC,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003698 DeclContext *MemberContext,
3699 bool EnteringContext,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003700 const ObjCObjectPointerType *OPT) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003701 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003702 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003703
Francois Pichet9c391132011-12-03 15:55:29 +00003704 // In Microsoft mode, don't perform typo correction in a template member
3705 // function dependent context because it interferes with the "lookup into
3706 // dependent bases of class templates" feature.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003707 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichet9c391132011-12-03 15:55:29 +00003708 isa<CXXMethodDecl>(CurContext))
3709 return TypoCorrection();
3710
Douglas Gregor2d435302009-12-30 17:04:44 +00003711 // We only attempt to correct typos for identifiers.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003712 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor2d435302009-12-30 17:04:44 +00003713 if (!Typo)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003714 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00003715
3716 // If the scope specifier itself was invalid, don't try to correct
3717 // typos.
3718 if (SS && SS->isInvalid())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003719 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00003720
3721 // Never try to correct typos during template deduction or
3722 // instantiation.
3723 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003724 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003725
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003726 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003727
3728 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003729
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003730 // If a callback object considers an empty typo correction candidate to be
3731 // viable, assume it does not do any actual validation of the candidates.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003732 TypoCorrection EmptyCorrection;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003733 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003734
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003735 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor87074f12010-10-20 01:32:02 +00003736 bool IsUnqualifiedLookup = false;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003737 DeclContext *QualifiedDC = MemberContext;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003738 if (MemberContext) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003739 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003740
3741 // Look in qualified interfaces.
3742 if (OPT) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003743 for (ObjCObjectPointerType::qual_iterator
3744 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003745 I != E; ++I)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003746 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003747 }
3748 } else if (SS && SS->isSet()) {
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003749 QualifiedDC = computeDeclContext(*SS, EnteringContext);
3750 if (!QualifiedDC)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003751 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003752
Douglas Gregor87074f12010-10-20 01:32:02 +00003753 // Provide a stop gap for files that are just seriously broken. Trying
3754 // to correct all typos can turn into a HUGE performance penalty, causing
3755 // some files to take minutes to get rejected by the parser.
3756 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003757 return TypoCorrection();
Douglas Gregor87074f12010-10-20 01:32:02 +00003758 ++TyposCorrected;
3759
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003760 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
Douglas Gregor2d435302009-12-30 17:04:44 +00003761 } else {
Douglas Gregor87074f12010-10-20 01:32:02 +00003762 IsUnqualifiedLookup = true;
3763 UnqualifiedTyposCorrectedMap::iterator Cached
3764 = UnqualifiedTyposCorrected.find(Typo);
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003765 if (Cached != UnqualifiedTyposCorrected.end()) {
3766 // Add the cached value, unless it's a keyword or fails validation. In the
3767 // keyword case, we'll end up adding the keyword below.
3768 if (Cached->second) {
3769 if (!Cached->second.isKeyword() &&
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003770 isCandidateViable(CCC, Cached->second))
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003771 Consumer.addCorrection(Cached->second);
3772 } else {
3773 // Only honor no-correction cache hits when a callback that will validate
3774 // correction candidates is not being used.
3775 if (!ValidatingCallback)
3776 return TypoCorrection();
3777 }
3778 }
3779 if (Cached == UnqualifiedTyposCorrected.end()) {
Douglas Gregor87074f12010-10-20 01:32:02 +00003780 // Provide a stop gap for files that are just seriously broken. Trying
3781 // to correct all typos can turn into a HUGE performance penalty, causing
3782 // some files to take minutes to get rejected by the parser.
3783 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003784 return TypoCorrection();
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003785 }
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003786 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003787
Douglas Gregorb11f9452012-03-26 16:54:18 +00003788 // Determine whether we are going to search in the various namespaces for
3789 // corrections.
3790 bool SearchNamespaces
Kaelyn Uhrainf4657d52012-04-03 18:20:11 +00003791 = getLangOpts().CPlusPlus &&
Douglas Gregorb11f9452012-03-26 16:54:18 +00003792 (IsUnqualifiedLookup || (QualifiedDC && QualifiedDC->isNamespace()));
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00003793 // In a few cases we *only* want to search for corrections bases on just
3794 // adding or changing the nested name specifier.
3795 bool AllowOnlyNNSChanges = Typo->getName().size() < 3;
Douglas Gregorb11f9452012-03-26 16:54:18 +00003796
3797 if (IsUnqualifiedLookup || SearchNamespaces) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003798 // For unqualified lookup, look through all of the names that we have
3799 // seen in this translation unit.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003800 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003801 for (IdentifierTable::iterator I = Context.Idents.begin(),
3802 IEnd = Context.Idents.end();
3803 I != IEnd; ++I)
3804 Consumer.FoundName(I->getKey());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003805
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003806 // Walk through identifiers in external identifier sources.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003807 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003808 if (IdentifierInfoLookup *External
3809 = Context.Idents.getExternalIdentifierLookup()) {
Dylan Noblesmithe2778992012-02-05 02:12:40 +00003810 OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003811 do {
3812 StringRef Name = Iter->Next();
3813 if (Name.empty())
3814 break;
Douglas Gregor57756ea2010-10-14 22:11:03 +00003815
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003816 Consumer.FoundName(Name);
3817 } while (true);
Douglas Gregor57756ea2010-10-14 22:11:03 +00003818 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003819 }
3820
Richard Smithb3a1df02012-06-08 21:35:42 +00003821 AddKeywordsToConsumer(*this, Consumer, S, CCC, SS && SS->isNotEmpty());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003822
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003823 // If we haven't found anything, we're done.
Douglas Gregor87074f12010-10-20 01:32:02 +00003824 if (Consumer.empty()) {
3825 // If this was an unqualified lookup, note that no correction was found.
3826 if (IsUnqualifiedLookup)
3827 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003828
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003829 return TypoCorrection();
Douglas Gregor87074f12010-10-20 01:32:02 +00003830 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003831
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00003832 // Make sure the best edit distance (prior to adding any namespace qualifiers)
3833 // is not more that about a third of the length of the typo's identifier.
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003834 unsigned ED = Consumer.getBestEditDistance(true);
Douglas Gregor87074f12010-10-20 01:32:02 +00003835 if (ED > 0 && Typo->getName().size() / ED < 3) {
3836 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregoraf1daa92010-10-27 14:20:34 +00003837 if (IsUnqualifiedLookup)
Douglas Gregor87074f12010-10-20 01:32:02 +00003838 (void)UnqualifiedTyposCorrected[Typo];
3839
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003840 return TypoCorrection();
3841 }
3842
Douglas Gregorb11f9452012-03-26 16:54:18 +00003843 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
3844 // to search those namespaces.
3845 if (SearchNamespaces) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003846 // Load any externally-known namespaces.
3847 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003848 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003849 LoadedExternalKnownNamespaces = true;
3850 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
3851 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
3852 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
3853 }
3854
3855 for (llvm::DenseMap<NamespaceDecl*, bool>::iterator
3856 KNI = KnownNamespaces.begin(),
3857 KNIEnd = KnownNamespaces.end();
3858 KNI != KNIEnd; ++KNI)
3859 Namespaces.AddNamespace(KNI->first);
Douglas Gregor87074f12010-10-20 01:32:02 +00003860 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003861
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003862 // Weed out any names that could not be found by name lookup or, if a
3863 // CorrectionCandidateCallback object was provided, failed validation.
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003864 llvm::SmallVector<TypoCorrection, 16> QualifiedResults;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003865 LookupResult TmpRes(*this, TypoName, LookupKind);
3866 TmpRes.suppressDiagnostics();
3867 while (!Consumer.empty()) {
3868 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3869 unsigned ED = DI->first;
Benjamin Kramer73faad62012-04-14 08:26:28 +00003870 for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(),
3871 IEnd = DI->second.end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003872 I != IEnd; /* Increment in loop. */) {
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00003873 // If we only want nested name specifier corrections, ignore potential
3874 // corrections that have a different base identifier from the typo.
3875 if (AllowOnlyNNSChanges &&
3876 I->second.front().getCorrectionAsIdentifierInfo() != Typo) {
3877 TypoCorrectionConsumer::result_iterator Prev = I;
3878 ++I;
3879 DI->second.erase(Prev);
3880 continue;
3881 }
3882
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003883 // If the item already has been looked up or is a keyword, keep it.
3884 // If a validator callback object was given, drop the correction
3885 // unless it passes validation.
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003886 bool Viable = false;
Benjamin Kramera2dcac12012-07-27 10:21:08 +00003887 for (TypoResultList::iterator RI = I->second.begin();
3888 RI != I->second.end(); /* Increment in loop. */) {
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003889 TypoResultList::iterator Prev = RI;
3890 ++RI;
3891 if (Prev->isResolved()) {
3892 if (!isCandidateViable(CCC, *Prev))
Benjamin Kramera2dcac12012-07-27 10:21:08 +00003893 RI = I->second.erase(Prev);
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003894 else
3895 Viable = true;
3896 }
3897 }
3898 if (Viable || I->second.empty()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003899 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003900 ++I;
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003901 if (!Viable)
Benjamin Kramer73faad62012-04-14 08:26:28 +00003902 DI->second.erase(Prev);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003903 continue;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003904 }
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003905 assert(I->second.size() == 1 && "Expected a single unresolved candidate");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003906
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003907 // Perform name lookup on this name.
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003908 TypoCorrection &Candidate = I->second.front();
3909 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003910 LookupPotentialTypoResult(*this, TmpRes, Name, S, SS, MemberContext,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00003911 EnteringContext, CCC.IsObjCIvarLookup);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003912
3913 switch (TmpRes.getResultKind()) {
3914 case LookupResult::NotFound:
3915 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain5a43b462011-09-07 20:25:59 +00003916 case LookupResult::FoundUnresolvedValue:
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003917 QualifiedResults.push_back(Candidate);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003918 // We didn't find this name in our scope, or didn't like what we found;
3919 // ignore it.
3920 {
3921 TypoCorrectionConsumer::result_iterator Next = I;
3922 ++Next;
Benjamin Kramer73faad62012-04-14 08:26:28 +00003923 DI->second.erase(I);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003924 I = Next;
3925 }
3926 break;
3927
3928 case LookupResult::Ambiguous:
3929 // We don't deal with ambiguities.
3930 return TypoCorrection();
3931
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003932 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003933 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003934 // Store all of the Decls for overloaded symbols
3935 for (LookupResult::iterator TRD = TmpRes.begin(),
3936 TRDEnd = TmpRes.end();
3937 TRD != TRDEnd; ++TRD)
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003938 Candidate.addCorrectionDecl(*TRD);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003939 ++I;
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003940 if (!isCandidateViable(CCC, Candidate))
Benjamin Kramer73faad62012-04-14 08:26:28 +00003941 DI->second.erase(Prev);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003942 break;
3943 }
3944
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003945 case LookupResult::Found: {
3946 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003947 Candidate.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003948 ++I;
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003949 if (!isCandidateViable(CCC, Candidate))
Benjamin Kramer73faad62012-04-14 08:26:28 +00003950 DI->second.erase(Prev);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003951 break;
3952 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003953
3954 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003955 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003956
Benjamin Kramer73faad62012-04-14 08:26:28 +00003957 if (DI->second.empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003958 Consumer.erase(DI);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003959 else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !ED)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003960 // If there are results in the closest possible bucket, stop
3961 break;
3962
3963 // Only perform the qualified lookups for C++
Douglas Gregorb11f9452012-03-26 16:54:18 +00003964 if (SearchNamespaces) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003965 TmpRes.suppressDiagnostics();
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003966 for (llvm::SmallVector<TypoCorrection,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003967 16>::iterator QRI = QualifiedResults.begin(),
3968 QRIEnd = QualifiedResults.end();
3969 QRI != QRIEnd; ++QRI) {
3970 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
3971 NIEnd = Namespaces.end();
3972 NI != NIEnd; ++NI) {
3973 DeclContext *Ctx = NI->DeclCtx;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003974
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003975 // FIXME: Stop searching once the namespaces are too far away to create
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003976 // acceptable corrections for this identifier (since the namespaces
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003977 // are sorted in ascending order by edit distance).
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003978
3979 TmpRes.clear();
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003980 TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003981 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
3982
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003983 // Any corrections added below will be validated in subsequent
3984 // iterations of the main while() loop over the Consumer's contents.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003985 switch (TmpRes.getResultKind()) {
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003986 case LookupResult::Found: {
3987 TypoCorrection TC(*QRI);
3988 TC.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
3989 TC.setCorrectionSpecifier(NI->NameSpecifier);
3990 TC.setQualifierDistance(NI->EditDistance);
3991 Consumer.addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003992 break;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003993 }
3994 case LookupResult::FoundOverloaded: {
3995 TypoCorrection TC(*QRI);
3996 TC.setCorrectionSpecifier(NI->NameSpecifier);
3997 TC.setQualifierDistance(NI->EditDistance);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003998 for (LookupResult::iterator TRD = TmpRes.begin(),
3999 TRDEnd = TmpRes.end();
4000 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004001 TC.addCorrectionDecl(*TRD);
4002 Consumer.addCorrection(TC);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004003 break;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004004 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004005 case LookupResult::NotFound:
4006 case LookupResult::NotFoundInCurrentInstantiation:
4007 case LookupResult::Ambiguous:
Kaelyn Uhrain5a43b462011-09-07 20:25:59 +00004008 case LookupResult::FoundUnresolvedValue:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004009 break;
4010 }
4011 }
4012 }
4013 }
4014
4015 QualifiedResults.clear();
4016 }
4017
4018 // No corrections remain...
4019 if (Consumer.empty()) return TypoCorrection();
4020
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00004021 TypoResultsMap &BestResults = Consumer.getBestResults();
4022 ED = Consumer.getBestEditDistance(true);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004023
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004024 if (!AllowOnlyNNSChanges && ED > 0 && Typo->getName().size() / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004025 // If this was an unqualified lookup and we believe the callback
4026 // object wouldn't have filtered out possible corrections, note
4027 // that no correction was found.
4028 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004029 (void)UnqualifiedTyposCorrected[Typo];
4030
4031 return TypoCorrection();
4032 }
4033
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004034 // If only a single name remains, return that result.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004035 if (BestResults.size() == 1) {
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004036 const TypoResultList &CorrectionList = BestResults.begin()->second;
4037 const TypoCorrection &Result = CorrectionList.front();
4038 if (CorrectionList.size() != 1) return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004039
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00004040 // Don't correct to a keyword that's the same as the typo; the keyword
4041 // wasn't actually in scope.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004042 if (ED == 0 && Result.isKeyword()) return TypoCorrection();
4043
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004044 // Record the correction for unqualified lookup.
4045 if (IsUnqualifiedLookup)
4046 UnqualifiedTyposCorrected[Typo] = Result;
4047
David Blaikie04ea41c2012-10-12 20:00:44 +00004048 TypoCorrection TC = Result;
4049 TC.setCorrectionRange(SS, TypoName);
4050 return TC;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004051 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004052 else if (BestResults.size() > 1
4053 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4054 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4055 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4056 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00004057 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004058 && BestResults["super"].front().isKeyword()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004059 // Prefer 'super' when we're completing in a message-receiver
4060 // context.
4061
4062 // Don't correct to a keyword that's the same as the typo; the keyword
4063 // wasn't actually in scope.
4064 if (ED == 0) return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004065
Douglas Gregor87074f12010-10-20 01:32:02 +00004066 // Record the correction for unqualified lookup.
4067 if (IsUnqualifiedLookup)
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004068 UnqualifiedTyposCorrected[Typo] = BestResults["super"].front();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004069
David Blaikie04ea41c2012-10-12 20:00:44 +00004070 TypoCorrection TC = BestResults["super"].front();
4071 TC.setCorrectionRange(SS, TypoName);
4072 return TC;
Douglas Gregoraf9eb592010-10-15 13:35:25 +00004073 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004074
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004075 // If this was an unqualified lookup and we believe the callback object did
4076 // not filter out possible corrections, note that no correction was found.
4077 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregor87074f12010-10-20 01:32:02 +00004078 (void)UnqualifiedTyposCorrected[Typo];
4079
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004080 return TypoCorrection();
4081}
4082
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004083void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4084 if (!CDecl) return;
4085
4086 if (isKeyword())
4087 CorrectionDecls.clear();
4088
Kaelyn Uhrainf60b55a2012-11-19 18:49:53 +00004089 CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004090
4091 if (!CorrectionName)
4092 CorrectionName = CDecl->getDeclName();
4093}
4094
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004095std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4096 if (CorrectionNameSpec) {
4097 std::string tmpBuffer;
4098 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4099 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
Benjamin Kramer73faad62012-04-14 08:26:28 +00004100 CorrectionName.printName(PrefixOStream);
4101 return PrefixOStream.str();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004102 }
4103
4104 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00004105}