blob: 80a50e0c791523fa839b517227deae99c38b75df [file] [log] [blame]
Douglas Gregor34074322009-01-14 22:20:51 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000016#include "clang/Sema/Lookup.h"
Alexis Hunt4ac55e32011-06-04 04:32:43 +000017#include "clang/Sema/Overload.h"
John McCall8b0666c2010-08-20 18:27:03 +000018#include "clang/Sema/DeclSpec.h"
John McCallcc14d1f2010-08-24 08:50:51 +000019#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000020#include "clang/Sema/ScopeInfo.h"
John McCall19c1bfd2010-08-25 05:32:35 +000021#include "clang/Sema/TemplateDeduction.h"
Axel Naumann016538a2011-02-24 16:47:47 +000022#include "clang/Sema/ExternalSemaSource.h"
Douglas Gregorc2fa1692011-06-28 16:20:02 +000023#include "clang/Sema/TypoCorrection.h"
Douglas Gregor960b5bc2009-01-15 00:26:24 +000024#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000025#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000026#include "clang/AST/Decl.h"
27#include "clang/AST/DeclCXX.h"
Nick Lewyckyc3921482012-04-03 21:44:08 +000028#include "clang/AST/DeclLookups.h"
Douglas Gregor34074322009-01-14 22:20:51 +000029#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000030#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000031#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000032#include "clang/AST/ExprCXX.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000033#include "clang/Basic/Builtins.h"
Douglas Gregor34074322009-01-14 22:20:51 +000034#include "clang/Basic/LangOptions.h"
Douglas Gregorcdd11d42012-02-01 17:04:21 +000035#include "llvm/ADT/SetVector.h"
Douglas Gregor34074322009-01-14 22:20:51 +000036#include "llvm/ADT/STLExtras.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.
531static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
532 const CXXRecordDecl *Class) {
533 // We need to have a definition for the class.
534 if (!Class->getDefinition() || Class->isDependentContext())
535 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000536
Douglas Gregor7454c562010-07-02 20:37:36 +0000537 // We can't be in the middle of defining the class.
538 if (const RecordType *RecordTy
539 = Context.getTypeDeclType(Class)->getAs<RecordType>())
540 return !RecordTy->isBeingDefined();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000541
Douglas Gregor7454c562010-07-02 20:37:36 +0000542 return false;
543}
544
545void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000546 if (!CanDeclareSpecialMemberFunction(Context, Class))
547 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000548
549 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000550 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000551 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000552
Douglas Gregora6d69502010-07-02 23:41:54 +0000553 // If the copy constructor has not yet been declared, do so now.
554 if (!Class->hasDeclaredCopyConstructor())
555 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000556
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000557 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000558 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000559 DeclareImplicitCopyAssignment(Class);
560
David Blaikiebbafb8a2012-03-11 07:00:24 +0000561 if (getLangOpts().CPlusPlus0x) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000562 // If the move constructor has not yet been declared, do so now.
563 if (Class->needsImplicitMoveConstructor())
564 DeclareImplicitMoveConstructor(Class); // might not actually do it
565
566 // If the move assignment operator has not yet been declared, do so now.
567 if (Class->needsImplicitMoveAssignment())
568 DeclareImplicitMoveAssignment(Class); // might not actually do it
569 }
570
Douglas Gregor7454c562010-07-02 20:37:36 +0000571 // If the destructor has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000572 if (!Class->hasDeclaredDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000573 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000574}
575
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000576/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000577/// special member function.
578static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
579 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000580 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000581 case DeclarationName::CXXDestructorName:
582 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000583
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000584 case DeclarationName::CXXOperatorName:
585 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000586
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000587 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000588 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000589 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000590
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000591 return false;
592}
593
594/// \brief If there are any implicit member functions with the given name
595/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000596static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000597 DeclarationName Name,
598 const DeclContext *DC) {
599 if (!DC)
600 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000601
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000602 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000603 case DeclarationName::CXXConstructorName:
604 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor9672f922010-07-03 00:47:00 +0000605 if (Record->getDefinition() &&
606 CanDeclareSpecialMemberFunction(S.Context, Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000607 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000608 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000609 S.DeclareImplicitDefaultConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000610 if (!Record->hasDeclaredCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000611 S.DeclareImplicitCopyConstructor(Class);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000612 if (S.getLangOpts().CPlusPlus0x &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000613 Record->needsImplicitMoveConstructor())
614 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000615 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000616 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000617
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000618 case DeclarationName::CXXDestructorName:
619 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
620 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
621 CanDeclareSpecialMemberFunction(S.Context, Record))
622 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000623 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000624
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000625 case DeclarationName::CXXOperatorName:
626 if (Name.getCXXOverloadedOperator() != OO_Equal)
627 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000628
Sebastian Redl22653ba2011-08-30 19:58:05 +0000629 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
630 if (Record->getDefinition() &&
631 CanDeclareSpecialMemberFunction(S.Context, Record)) {
632 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
633 if (!Record->hasDeclaredCopyAssignment())
634 S.DeclareImplicitCopyAssignment(Class);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000635 if (S.getLangOpts().CPlusPlus0x &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000636 Record->needsImplicitMoveAssignment())
637 S.DeclareImplicitMoveAssignment(Class);
638 }
639 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000640 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000641
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000642 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000643 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000644 }
645}
Douglas Gregor7454c562010-07-02 20:37:36 +0000646
John McCall9f3059a2009-10-09 21:13:30 +0000647// Adds all qualifying matches for a name within a decl context to the
648// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000649static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000650 bool Found = false;
651
Douglas Gregor7454c562010-07-02 20:37:36 +0000652 // Lazily declare C++ special member functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000653 if (S.getLangOpts().CPlusPlus)
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000654 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000655
Douglas Gregor7454c562010-07-02 20:37:36 +0000656 // Perform lookup into this declaration context.
John McCallf6c8a4e2009-11-10 07:01:13 +0000657 DeclContext::lookup_const_iterator I, E;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000658 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall401982f2010-01-20 21:53:11 +0000659 NamedDecl *D = *I;
Douglas Gregor4a814562011-12-14 16:03:29 +0000660 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000661 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000662 Found = true;
663 }
664 }
John McCall9f3059a2009-10-09 21:13:30 +0000665
Douglas Gregord3a59182010-02-12 05:48:04 +0000666 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
667 return true;
668
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000669 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000670 != DeclarationName::CXXConversionFunctionName ||
671 R.getLookupName().getCXXNameType()->isDependentType() ||
672 !isa<CXXRecordDecl>(DC))
673 return Found;
674
675 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000676 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000677 // name lookup. Instead, any conversion function templates visible in the
678 // context of the use are considered. [...]
679 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000680 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000681 return Found;
682
683 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000684 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
Chandler Carruth3a693b72010-01-31 11:44:02 +0000685 UEnd = Unresolved->end(); U != UEnd; ++U) {
686 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
687 if (!ConvTemplate)
688 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000689
Chandler Carruth3a693b72010-01-31 11:44:02 +0000690 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000691 // add the conversion function template. When we deduce template
692 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000693 // type of the new declaration with the type of the function template.
694 if (R.isForRedeclaration()) {
695 R.addDecl(ConvTemplate);
696 Found = true;
697 continue;
698 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000699
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000700 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000701 // [...] For each such operator, if argument deduction succeeds
702 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000703 // name lookup.
704 //
705 // When referencing a conversion function for any purpose other than
706 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000707 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000708 // specialization into the result set. We do this to avoid forcing all
709 // callers to perform special deduction for conversion functions.
John McCall19c1bfd2010-08-25 05:32:35 +0000710 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruth3a693b72010-01-31 11:44:02 +0000711 FunctionDecl *Specialization = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000712
713 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000714 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
715 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000716
Chandler Carruth3a693b72010-01-31 11:44:02 +0000717 // Compute the type of the function that we would expect the conversion
718 // function to have, if it were to match the name given.
719 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000720 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
721 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
Sebastian Redl7c6c9e92011-03-06 10:52:04 +0000722 EPI.ExceptionSpecType = EST_None;
John McCalldb40c7f2010-12-14 08:05:40 +0000723 EPI.NumExceptions = 0;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000724 QualType ExpectedType
725 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
John McCalldb40c7f2010-12-14 08:05:40 +0000726 0, 0, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000727
Chandler Carruth3a693b72010-01-31 11:44:02 +0000728 // Perform template argument deduction against the type that we would
729 // expect the function to have.
730 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
731 Specialization, Info)
732 == Sema::TDK_Success) {
733 R.addDecl(Specialization);
734 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000735 }
736 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000737
John McCall9f3059a2009-10-09 21:13:30 +0000738 return Found;
739}
740
John McCallf6c8a4e2009-11-10 07:01:13 +0000741// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000742static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000743CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000744 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000745
746 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
747
John McCallf6c8a4e2009-11-10 07:01:13 +0000748 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000749 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000750
John McCallf6c8a4e2009-11-10 07:01:13 +0000751 // Perform direct name lookup into the namespaces nominated by the
752 // using directives whose common ancestor is this namespace.
753 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
754 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000755
John McCallf6c8a4e2009-11-10 07:01:13 +0000756 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000757 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000758 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000759
760 R.resolveKind();
761
762 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000763}
764
765static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000766 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000767 return Ctx->isFileContext();
768 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000769}
Douglas Gregored8f2882009-01-30 01:04:22 +0000770
Douglas Gregor66230062010-03-15 14:33:29 +0000771// Find the next outer declaration context from this scope. This
772// routine actually returns the semantic outer context, which may
773// differ from the lexical context (encoded directly in the Scope
774// stack) when we are parsing a member of a class template. In this
775// case, the second element of the pair will be true, to indicate that
776// name lookup should continue searching in this semantic context when
777// it leaves the current template parameter scope.
778static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
779 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
780 DeclContext *Lexical = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000781 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000782 OuterS = OuterS->getParent()) {
783 if (OuterS->getEntity()) {
Douglas Gregorea166062010-03-15 15:26:48 +0000784 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor66230062010-03-15 14:33:29 +0000785 break;
786 }
787 }
788
789 // C++ [temp.local]p8:
790 // In the definition of a member of a class template that appears
791 // outside of the namespace containing the class template
792 // definition, the name of a template-parameter hides the name of
793 // a member of this namespace.
794 //
795 // Example:
796 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000797 // namespace N {
798 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000799 //
800 // template<class T> class B {
801 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000802 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000803 // }
804 //
805 // template<class C> void N::B<C>::f(C) {
806 // C b; // C is the template parameter, not N::C
807 // }
808 //
809 // In this example, the lexical context we return is the
810 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000811 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000812 !S->getParent()->isTemplateParamScope())
813 return std::make_pair(Lexical, false);
814
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000815 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000816 // For the example, this is the scope for the template parameters of
817 // template<class C>.
818 Scope *OutermostTemplateScope = S->getParent();
819 while (OutermostTemplateScope->getParent() &&
820 OutermostTemplateScope->getParent()->isTemplateParamScope())
821 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000822
Douglas Gregor66230062010-03-15 14:33:29 +0000823 // Find the namespace context in which the original scope occurs. In
824 // the example, this is namespace N.
825 DeclContext *Semantic = DC;
826 while (!Semantic->isFileContext())
827 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000828
Douglas Gregor66230062010-03-15 14:33:29 +0000829 // Find the declaration context just outside of the template
830 // parameter scope. This is the context in which the template is
831 // being lexically declaration (a namespace context). In the
832 // example, this is the global scope.
833 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
834 Lexical->Encloses(Semantic))
835 return std::make_pair(Semantic, true);
836
837 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000838}
839
John McCall27b18f82009-11-17 02:14:36 +0000840bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000841 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000842
843 DeclarationName Name = R.getLookupName();
844
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000845 // If this is the name of an implicitly-declared special member function,
846 // go through the scope stack to implicitly declare
847 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
848 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
849 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
850 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
851 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000852
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000853 // Implicitly declare member functions with the name we're looking for, if in
854 // fact we are in a scope where it matters.
855
Douglas Gregor889ceb72009-02-03 19:21:40 +0000856 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000857 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000858 I = IdResolver.begin(Name),
859 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000860
Douglas Gregor889ceb72009-02-03 19:21:40 +0000861 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000862 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000863 // ...During unqualified name lookup (3.4.1), the names appear as if
864 // they were declared in the nearest enclosing namespace which contains
865 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000866 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000867 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000868 //
869 // For example:
870 // namespace A { int i; }
871 // void foo() {
872 // int i;
873 // {
874 // using namespace A;
875 // ++i; // finds local 'i', A::i appears at global scope
876 // }
877 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000878 //
Douglas Gregor66230062010-03-15 14:33:29 +0000879 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor700792c2009-02-05 19:25:20 +0000880 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor3e51e172010-05-20 20:58:56 +0000881 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
882
Douglas Gregor889ceb72009-02-03 19:21:40 +0000883 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000884 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000885 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000886 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
John McCall9f3059a2009-10-09 21:13:30 +0000887 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +0000888 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000889 }
890 }
John McCall9f3059a2009-10-09 21:13:30 +0000891 if (Found) {
892 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000893 if (S->isClassScope())
894 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
895 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000896 return true;
897 }
898
Douglas Gregor66230062010-03-15 14:33:29 +0000899 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
900 S->getParent() && !S->getParent()->isTemplateParamScope()) {
901 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000902 // found nothing, so look into the contexts between the
Douglas Gregor66230062010-03-15 14:33:29 +0000903 // lexical and semantic declaration contexts returned by
904 // findOuterContext(). This implements the name lookup behavior
905 // of C++ [temp.local]p8.
906 Ctx = OutsideOfTemplateParamDC;
907 OutsideOfTemplateParamDC = 0;
908 }
909
910 if (Ctx) {
911 DeclContext *OuterCtx;
912 bool SearchAfterTemplateScope;
913 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
914 if (SearchAfterTemplateScope)
915 OutsideOfTemplateParamDC = OuterCtx;
916
Douglas Gregorea166062010-03-15 15:26:48 +0000917 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000918 // We do not directly look into transparent contexts, since
919 // those entities will be found in the nearest enclosing
920 // non-transparent context.
921 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000922 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000923
924 // We do not look directly into function or method contexts,
925 // since all of the local variables and parameters of the
926 // function/method are present within the Scope.
927 if (Ctx->isFunctionOrMethod()) {
928 // If we have an Objective-C instance method, look for ivars
929 // in the corresponding interface.
930 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
931 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
932 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
933 ObjCInterfaceDecl *ClassDeclared;
934 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000935 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +0000936 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000937 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
938 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +0000939 R.resolveKind();
940 return true;
941 }
942 }
943 }
944 }
945
946 continue;
947 }
948
Douglas Gregor7f737c02009-09-10 16:57:35 +0000949 // Perform qualified name lookup into this context.
950 // FIXME: In some cases, we know that every name that could be found by
951 // this qualified name lookup will also be on the identifier chain. For
952 // example, inside a class without any base classes, we never need to
953 // perform qualified lookup because all of the members are on top of the
954 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000955 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +0000956 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000957 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000958 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000959 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000960
John McCallf6c8a4e2009-11-10 07:01:13 +0000961 // Stop if we ran out of scopes.
962 // FIXME: This really, really shouldn't be happening.
963 if (!S) return false;
964
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +0000965 // If we are looking for members, no need to look into global/namespace scope.
966 if (R.getLookupKind() == LookupMemberName)
967 return false;
968
Douglas Gregor700792c2009-02-05 19:25:20 +0000969 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000970 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000971 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000972 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
973 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000974
John McCallf6c8a4e2009-11-10 07:01:13 +0000975 UnqualUsingDirectiveSet UDirs;
976 UDirs.visitScopeChain(Initial, S);
977 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000978
Douglas Gregor700792c2009-02-05 19:25:20 +0000979 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000980 // Unqualified name lookup in C++ requires looking into scopes
981 // that aren't strictly lexical, and therefore we walk through the
982 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000983
Douglas Gregor889ceb72009-02-03 19:21:40 +0000984 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000985 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000986 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000987 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000988 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000989 // We found something. Look for anything else in our scope
990 // with this same name and in an acceptable identifier
991 // namespace, so that we can construct an overload set if we
992 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000993 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +0000994 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000995 }
996 }
997
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000998 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +0000999 R.resolveKind();
1000 return true;
1001 }
1002
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001003 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1004 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1005 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1006 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001007 // found nothing, so look into the contexts between the
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001008 // lexical and semantic declaration contexts returned by
1009 // findOuterContext(). This implements the name lookup behavior
1010 // of C++ [temp.local]p8.
1011 Ctx = OutsideOfTemplateParamDC;
1012 OutsideOfTemplateParamDC = 0;
1013 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001014
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001015 if (Ctx) {
1016 DeclContext *OuterCtx;
1017 bool SearchAfterTemplateScope;
1018 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1019 if (SearchAfterTemplateScope)
1020 OutsideOfTemplateParamDC = OuterCtx;
1021
1022 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1023 // We do not directly look into transparent contexts, since
1024 // those entities will be found in the nearest enclosing
1025 // non-transparent context.
1026 if (Ctx->isTransparentContext())
1027 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001028
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001029 // If we have a context, and it's not a context stashed in the
1030 // template parameter scope for an out-of-line definition, also
1031 // look into that context.
1032 if (!(Found && S && S->isTemplateParamScope())) {
1033 assert(Ctx->isFileContext() &&
1034 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001035
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001036 // Look into context considering using-directives.
1037 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1038 Found = true;
1039 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001040
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001041 if (Found) {
1042 R.resolveKind();
1043 return true;
1044 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001045
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001046 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1047 return false;
1048 }
1049 }
1050
Douglas Gregor3ce74932010-02-05 07:07:10 +00001051 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001052 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001053 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001054
John McCall9f3059a2009-10-09 21:13:30 +00001055 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001056}
1057
Douglas Gregor4a814562011-12-14 16:03:29 +00001058/// \brief Retrieve the visible declaration corresponding to D, if any.
1059///
1060/// This routine determines whether the declaration D is visible in the current
1061/// module, with the current imports. If not, it checks whether any
1062/// redeclaration of D is visible, and if so, returns that declaration.
1063///
1064/// \returns D, or a visible previous declaration of D, whichever is more recent
1065/// and visible. If no declaration of D is visible, returns null.
1066static NamedDecl *getVisibleDecl(NamedDecl *D) {
1067 if (LookupResult::isVisible(D))
1068 return D;
1069
Douglas Gregor54079202012-01-06 22:05:37 +00001070 for (Decl::redecl_iterator RD = D->redecls_begin(), RDEnd = D->redecls_end();
1071 RD != RDEnd; ++RD) {
David Blaikie40ed2972012-06-06 20:45:41 +00001072 if (NamedDecl *ND = dyn_cast<NamedDecl>(*RD)) {
Douglas Gregor54079202012-01-06 22:05:37 +00001073 if (LookupResult::isVisible(ND))
1074 return ND;
1075 }
Douglas Gregor4a814562011-12-14 16:03:29 +00001076 }
1077
1078 return 0;
1079}
1080
Douglas Gregor34074322009-01-14 22:20:51 +00001081/// @brief Perform unqualified name lookup starting from a given
1082/// scope.
1083///
1084/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1085/// used to find names within the current scope. For example, 'x' in
1086/// @code
1087/// int x;
1088/// int f() {
1089/// return x; // unqualified name look finds 'x' in the global scope
1090/// }
1091/// @endcode
1092///
1093/// Different lookup criteria can find different names. For example, a
1094/// particular scope can have both a struct and a function of the same
1095/// name, and each can be found by certain lookup criteria. For more
1096/// information about lookup criteria, see the documentation for the
1097/// class LookupCriteria.
1098///
1099/// @param S The scope from which unqualified name lookup will
1100/// begin. If the lookup criteria permits, name lookup may also search
1101/// in the parent scopes.
1102///
James Dennett91738ff2012-06-22 10:32:46 +00001103/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1104/// look up and the lookup kind), and is updated with the results of lookup
1105/// including zero or more declarations and possibly additional information
1106/// used to diagnose ambiguities.
Douglas Gregor34074322009-01-14 22:20:51 +00001107///
James Dennett91738ff2012-06-22 10:32:46 +00001108/// @returns \c true if lookup succeeded and false otherwise.
John McCall27b18f82009-11-17 02:14:36 +00001109bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1110 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001111 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001112
John McCall27b18f82009-11-17 02:14:36 +00001113 LookupNameKind NameKind = R.getLookupKind();
1114
David Blaikiebbafb8a2012-03-11 07:00:24 +00001115 if (!getLangOpts().CPlusPlus) {
Douglas Gregor34074322009-01-14 22:20:51 +00001116 // Unqualified name lookup in C/Objective-C is purely lexical, so
1117 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001118 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001119 // Find the nearest non-transparent declaration scope.
1120 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +00001121 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +00001122 static_cast<DeclContext *>(S->getEntity())
1123 ->isTransparentContext()))
1124 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001125 }
1126
John McCallea305ed2009-12-18 10:40:03 +00001127 unsigned IDNS = R.getIdentifierNamespace();
1128
Douglas Gregor34074322009-01-14 22:20:51 +00001129 // Scan up the scope chain looking for a decl that matches this
1130 // identifier that is in the appropriate namespace. This search
1131 // should not take long, as shadowing of names is uncommon, and
1132 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001133 bool LeftStartingScope = false;
1134
Douglas Gregored8f2882009-01-30 01:04:22 +00001135 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001136 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001137 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001138 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001139 if (NameKind == LookupRedeclarationWithLinkage) {
1140 // Determine whether this (or a previous) declaration is
1141 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001142 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001143 LeftStartingScope = true;
1144
1145 // If we found something outside of our starting scope that
1146 // does not have linkage, skip it.
1147 if (LeftStartingScope && !((*I)->hasLinkage()))
1148 continue;
1149 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001150 else if (NameKind == LookupObjCImplicitSelfParam &&
1151 !isa<ImplicitParamDecl>(*I))
1152 continue;
1153
Douglas Gregor2a5d1482011-12-02 20:08:44 +00001154 // If this declaration is module-private and it came from an AST
1155 // file, we can't see it.
Douglas Gregor5c193c72012-01-05 01:11:47 +00001156 NamedDecl *D = R.isHiddenDeclarationVisible()? *I : getVisibleDecl(*I);
Douglas Gregor4a814562011-12-14 16:03:29 +00001157 if (!D)
Douglas Gregor2a5d1482011-12-02 20:08:44 +00001158 continue;
Douglas Gregor4a814562011-12-14 16:03:29 +00001159
1160 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001161
Douglas Gregorb59643b2012-01-03 23:26:26 +00001162 // Check whether there are any other declarations with the same name
1163 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001164 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001165 // Find the scope in which this declaration was declared (if it
1166 // actually exists in a Scope).
1167 while (S && !S->isDeclScope(D))
1168 S = S->getParent();
1169
1170 // If the scope containing the declaration is the translation unit,
1171 // then we'll need to perform our checks based on the matching
1172 // DeclContexts rather than matching scopes.
1173 if (S && isNamespaceOrTranslationUnitScope(S))
1174 S = 0;
1175
1176 // Compute the DeclContext, if we need it.
1177 DeclContext *DC = 0;
1178 if (!S)
1179 DC = (*I)->getDeclContext()->getRedeclContext();
1180
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001181 IdentifierResolver::iterator LastI = I;
1182 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001183 if (S) {
1184 // Match based on scope.
1185 if (!S->isDeclScope(*LastI))
1186 break;
1187 } else {
1188 // Match based on DeclContext.
1189 DeclContext *LastDC
1190 = (*LastI)->getDeclContext()->getRedeclContext();
1191 if (!LastDC->Equals(DC))
1192 break;
1193 }
1194
1195 // If the declaration isn't in the right namespace, skip it.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001196 if (!(*LastI)->isInIdentifierNamespace(IDNS))
1197 continue;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001198
Douglas Gregor5c193c72012-01-05 01:11:47 +00001199 D = R.isHiddenDeclarationVisible()? *LastI : getVisibleDecl(*LastI);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001200 if (D)
1201 R.addDecl(D);
1202 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001203
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001204 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001205 }
John McCall9f3059a2009-10-09 21:13:30 +00001206 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001207 }
Douglas Gregor34074322009-01-14 22:20:51 +00001208 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001209 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001210 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001211 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001212 }
1213
1214 // If we didn't find a use of this identifier, and if the identifier
1215 // corresponds to a compiler builtin, create the decl object for the builtin
1216 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001217 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1218 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001219
Axel Naumann016538a2011-02-24 16:47:47 +00001220 // If we didn't find a use of this identifier, the ExternalSource
1221 // may be able to handle the situation.
1222 // Note: some lookup failures are expected!
1223 // See e.g. R.isForRedeclaration().
1224 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001225}
1226
John McCall6538c932009-10-10 05:48:19 +00001227/// @brief Perform qualified name lookup in the namespaces nominated by
1228/// using directives by the given context.
1229///
1230/// C++98 [namespace.qual]p2:
James Dennett51a8d8b2012-06-19 21:05:49 +00001231/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6538c932009-10-10 05:48:19 +00001232/// (where X is the global namespace), let S be the set of all
1233/// declarations of m in X and in the transitive closure of all
1234/// namespaces nominated by using-directives in X and its used
1235/// namespaces, except that using-directives are ignored in any
1236/// namespace, including X, directly containing one or more
1237/// declarations of m. No namespace is searched more than once in
1238/// the lookup of a name. If S is the empty set, the program is
1239/// ill-formed. Otherwise, if S has exactly one member, or if the
1240/// context of the reference is a using-declaration
1241/// (namespace.udecl), S is the required set of declarations of
1242/// m. Otherwise if the use of m is not one that allows a unique
1243/// declaration to be chosen from S, the program is ill-formed.
James Dennett51a8d8b2012-06-19 21:05:49 +00001244///
John McCall6538c932009-10-10 05:48:19 +00001245/// C++98 [namespace.qual]p5:
1246/// During the lookup of a qualified namespace member name, if the
1247/// lookup finds more than one declaration of the member, and if one
1248/// declaration introduces a class name or enumeration name and the
1249/// other declarations either introduce the same object, the same
1250/// enumerator or a set of functions, the non-type name hides the
1251/// class or enumeration name if and only if the declarations are
1252/// from the same namespace; otherwise (the declarations are from
1253/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001254static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001255 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001256 assert(StartDC->isFileContext() && "start context is not a file context");
1257
1258 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1259 DeclContext::udir_iterator E = StartDC->using_directives_end();
1260
1261 if (I == E) return false;
1262
1263 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001264 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001265 Visited.insert(StartDC);
1266
1267 // We have not yet looked into these namespaces, much less added
1268 // their "using-children" to the queue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001269 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001270
1271 // We have already looked into the initial namespace; seed the queue
1272 // with its using-children.
1273 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +00001274 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001275 if (Visited.insert(ND))
John McCall6538c932009-10-10 05:48:19 +00001276 Queue.push_back(ND);
1277 }
1278
1279 // The easiest way to implement the restriction in [namespace.qual]p5
1280 // is to check whether any of the individual results found a tag
1281 // and, if so, to declare an ambiguity if the final result is not
1282 // a tag.
1283 bool FoundTag = false;
1284 bool FoundNonTag = false;
1285
John McCall5cebab12009-11-18 07:57:50 +00001286 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001287
1288 bool Found = false;
1289 while (!Queue.empty()) {
1290 NamespaceDecl *ND = Queue.back();
1291 Queue.pop_back();
1292
1293 // We go through some convolutions here to avoid copying results
1294 // between LookupResults.
1295 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001296 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001297 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001298
1299 if (FoundDirect) {
1300 // First do any local hiding.
1301 DirectR.resolveKind();
1302
1303 // If the local result is a tag, remember that.
1304 if (DirectR.isSingleTagDecl())
1305 FoundTag = true;
1306 else
1307 FoundNonTag = true;
1308
1309 // Append the local results to the total results if necessary.
1310 if (UseLocal) {
1311 R.addAllDecls(LocalR);
1312 LocalR.clear();
1313 }
1314 }
1315
1316 // If we find names in this namespace, ignore its using directives.
1317 if (FoundDirect) {
1318 Found = true;
1319 continue;
1320 }
1321
1322 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1323 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001324 if (Visited.insert(Nom))
John McCall6538c932009-10-10 05:48:19 +00001325 Queue.push_back(Nom);
1326 }
1327 }
1328
1329 if (Found) {
1330 if (FoundTag && FoundNonTag)
1331 R.setAmbiguousQualifiedTagHiding();
1332 else
1333 R.resolveKind();
1334 }
1335
1336 return Found;
1337}
1338
Douglas Gregor39982192010-08-15 06:18:01 +00001339/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001340static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor39982192010-08-15 06:18:01 +00001341 CXXBasePath &Path,
1342 void *Name) {
1343 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001344
Douglas Gregor39982192010-08-15 06:18:01 +00001345 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1346 Path.Decls = BaseRecord->lookup(N);
1347 return Path.Decls.first != Path.Decls.second;
1348}
1349
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001350/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001351/// static members, nested types, and enumerators.
1352template<typename InputIterator>
1353static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1354 Decl *D = (*First)->getUnderlyingDecl();
1355 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1356 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001357
Douglas Gregorc0d24902010-10-22 22:08:47 +00001358 if (isa<CXXMethodDecl>(D)) {
1359 // Determine whether all of the methods are static.
1360 bool AllMethodsAreStatic = true;
1361 for(; First != Last; ++First) {
1362 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001363
Douglas Gregorc0d24902010-10-22 22:08:47 +00001364 if (!isa<CXXMethodDecl>(D)) {
1365 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1366 break;
1367 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001368
Douglas Gregorc0d24902010-10-22 22:08:47 +00001369 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1370 AllMethodsAreStatic = false;
1371 break;
1372 }
1373 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001374
Douglas Gregorc0d24902010-10-22 22:08:47 +00001375 if (AllMethodsAreStatic)
1376 return true;
1377 }
1378
1379 return false;
1380}
1381
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001382/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001383///
1384/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1385/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001386/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001387///
1388/// Different lookup criteria can find different names. For example, a
1389/// particular scope can have both a struct and a function of the same
1390/// name, and each can be found by certain lookup criteria. For more
1391/// information about lookup criteria, see the documentation for the
1392/// class LookupCriteria.
1393///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001394/// \param R captures both the lookup criteria and any lookup results found.
1395///
1396/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001397/// search. If the lookup criteria permits, name lookup may also search
1398/// in the parent contexts or (for C++ classes) base classes.
1399///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001400/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001401/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001402///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001403/// \returns true if lookup succeeded, false if it failed.
1404bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1405 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001406 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001407
John McCall27b18f82009-11-17 02:14:36 +00001408 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001409 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001410
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001411 // Make sure that the declaration context is complete.
1412 assert((!isa<TagDecl>(LookupCtx) ||
1413 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00001414 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith7d137e32012-03-23 03:33:32 +00001415 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001416 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001417
Douglas Gregor34074322009-01-14 22:20:51 +00001418 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001419 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001420 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001421 if (isa<CXXRecordDecl>(LookupCtx))
1422 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001423 return true;
1424 }
Douglas Gregor34074322009-01-14 22:20:51 +00001425
John McCall6538c932009-10-10 05:48:19 +00001426 // Don't descend into implied contexts for redeclarations.
1427 // C++98 [namespace.qual]p6:
1428 // In a declaration for a namespace member in which the
1429 // declarator-id is a qualified-id, given that the qualified-id
1430 // for the namespace member has the form
1431 // nested-name-specifier unqualified-id
1432 // the unqualified-id shall name a member of the namespace
1433 // designated by the nested-name-specifier.
1434 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001435 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001436 return false;
1437
John McCall27b18f82009-11-17 02:14:36 +00001438 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001439 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001440 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001441
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001442 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001443 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001444 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001445 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001446 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001447
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001448 // If we're performing qualified name lookup into a dependent class,
1449 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001450 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001451 // template instantiation time (at which point all bases will be available)
1452 // or we have to fail.
1453 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1454 LookupRec->hasAnyDependentBases()) {
1455 R.setNotFoundInCurrentInstantiation();
1456 return false;
1457 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001458
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001459 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001460 CXXBasePaths Paths;
1461 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001462
1463 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001464 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001465 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001466 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001467 case LookupOrdinaryName:
1468 case LookupMemberName:
1469 case LookupRedeclarationWithLinkage:
1470 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1471 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001472
Douglas Gregor36d1b142009-10-06 17:59:45 +00001473 case LookupTagName:
1474 BaseCallback = &CXXRecordDecl::FindTagMember;
1475 break;
John McCall84d87672009-12-10 09:41:52 +00001476
Douglas Gregor39982192010-08-15 06:18:01 +00001477 case LookupAnyName:
1478 BaseCallback = &LookupAnyMember;
1479 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001480
John McCall84d87672009-12-10 09:41:52 +00001481 case LookupUsingDeclName:
1482 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001483
Douglas Gregor36d1b142009-10-06 17:59:45 +00001484 case LookupOperatorName:
1485 case LookupNamespaceName:
1486 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001487 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001488 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001489 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001490
Douglas Gregor36d1b142009-10-06 17:59:45 +00001491 case LookupNestedNameSpecifierName:
1492 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1493 break;
1494 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001495
John McCall27b18f82009-11-17 02:14:36 +00001496 if (!LookupRec->lookupInBases(BaseCallback,
1497 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001498 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001499
John McCall553c0792010-01-23 00:46:32 +00001500 R.setNamingClass(LookupRec);
1501
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001502 // C++ [class.member.lookup]p2:
1503 // [...] If the resulting set of declarations are not all from
1504 // sub-objects of the same type, or the set has a nonstatic member
1505 // and includes members from distinct sub-objects, there is an
1506 // ambiguity and the program is ill-formed. Otherwise that set is
1507 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001508 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001509 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001510 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001511
Douglas Gregor36d1b142009-10-06 17:59:45 +00001512 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001513 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001514 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001515
John McCall401982f2010-01-20 21:53:11 +00001516 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1517 // across all paths.
1518 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001519
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001520 // Determine whether we're looking at a distinct sub-object or not.
1521 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001522 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001523 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1524 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001525 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001526 }
1527
Douglas Gregorc0d24902010-10-22 22:08:47 +00001528 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001529 != Context.getCanonicalType(PathElement.Base->getType())) {
1530 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001531 // different types. If the declaration sets aren't the same, this
1532 // this lookup is ambiguous.
1533 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1534 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1535 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1536 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001537
Douglas Gregorc0d24902010-10-22 22:08:47 +00001538 while (FirstD != FirstPath->Decls.second &&
1539 CurrentD != Path->Decls.second) {
1540 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1541 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1542 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001543
Douglas Gregorc0d24902010-10-22 22:08:47 +00001544 ++FirstD;
1545 ++CurrentD;
1546 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001547
Douglas Gregorc0d24902010-10-22 22:08:47 +00001548 if (FirstD == FirstPath->Decls.second &&
1549 CurrentD == Path->Decls.second)
1550 continue;
1551 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001552
John McCall9f3059a2009-10-09 21:13:30 +00001553 R.setAmbiguousBaseSubobjectTypes(Paths);
1554 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001555 }
1556
Douglas Gregorc0d24902010-10-22 22:08:47 +00001557 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001558 // We have a different subobject of the same type.
1559
1560 // C++ [class.member.lookup]p5:
1561 // A static member, a nested type or an enumerator defined in
1562 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001563 // has more than one base class subobject of type T.
Douglas Gregorc0d24902010-10-22 22:08:47 +00001564 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001565 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001566
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001567 // We have found a nonstatic member name in multiple, distinct
1568 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001569 R.setAmbiguousBaseSubobjects(Paths);
1570 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001571 }
1572 }
1573
1574 // Lookup in a base class succeeded; return these results.
1575
John McCall9f3059a2009-10-09 21:13:30 +00001576 DeclContext::lookup_iterator I, E;
John McCall553c0792010-01-23 00:46:32 +00001577 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1578 NamedDecl *D = *I;
1579 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1580 D->getAccess());
1581 R.addDecl(D, AS);
1582 }
John McCall9f3059a2009-10-09 21:13:30 +00001583 R.resolveKind();
1584 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001585}
1586
1587/// @brief Performs name lookup for a name that was parsed in the
1588/// source code, and may contain a C++ scope specifier.
1589///
1590/// This routine is a convenience routine meant to be called from
1591/// contexts that receive a name and an optional C++ scope specifier
1592/// (e.g., "N::M::x"). It will then perform either qualified or
1593/// unqualified name lookup (with LookupQualifiedName or LookupName,
1594/// respectively) on the given name and return those results.
1595///
1596/// @param S The scope from which unqualified name lookup will
1597/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001598///
Douglas Gregore861bac2009-08-25 22:51:20 +00001599/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001600///
Douglas Gregore861bac2009-08-25 22:51:20 +00001601/// @param EnteringContext Indicates whether we are going to enter the
1602/// context of the scope-specifier SS (if present).
1603///
John McCall9f3059a2009-10-09 21:13:30 +00001604/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001605bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001606 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001607 if (SS && SS->isInvalid()) {
1608 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001609 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001610 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001611 }
Mike Stump11289f42009-09-09 15:08:12 +00001612
Douglas Gregore861bac2009-08-25 22:51:20 +00001613 if (SS && SS->isSet()) {
1614 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001615 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001616 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001617 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001618 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001619
John McCall27b18f82009-11-17 02:14:36 +00001620 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00001621 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001622 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001623
Douglas Gregore861bac2009-08-25 22:51:20 +00001624 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001625 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001626 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00001627 R.setNotFoundInCurrentInstantiation();
1628 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00001629 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001630 }
1631
Mike Stump11289f42009-09-09 15:08:12 +00001632 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001633 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001634}
1635
Douglas Gregor889ceb72009-02-03 19:21:40 +00001636
James Dennett41725122012-06-22 10:16:05 +00001637/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001638/// from name lookup.
1639///
James Dennett41725122012-06-22 10:16:05 +00001640/// \param Result The result of the ambiguous lookup to be diagnosed.
Mike Stump11289f42009-09-09 15:08:12 +00001641///
James Dennett41725122012-06-22 10:16:05 +00001642/// \returns true
John McCall27b18f82009-11-17 02:14:36 +00001643bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001644 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1645
John McCall27b18f82009-11-17 02:14:36 +00001646 DeclarationName Name = Result.getLookupName();
1647 SourceLocation NameLoc = Result.getNameLoc();
1648 SourceRange LookupRange = Result.getContextRange();
1649
John McCall6538c932009-10-10 05:48:19 +00001650 switch (Result.getAmbiguityKind()) {
1651 case LookupResult::AmbiguousBaseSubobjects: {
1652 CXXBasePaths *Paths = Result.getBasePaths();
1653 QualType SubobjectType = Paths->front().back().Base->getType();
1654 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1655 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1656 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001657
John McCall6538c932009-10-10 05:48:19 +00001658 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1659 while (isa<CXXMethodDecl>(*Found) &&
1660 cast<CXXMethodDecl>(*Found)->isStatic())
1661 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001662
John McCall6538c932009-10-10 05:48:19 +00001663 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001664
John McCall6538c932009-10-10 05:48:19 +00001665 return true;
1666 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001667
John McCall6538c932009-10-10 05:48:19 +00001668 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001669 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1670 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001671
John McCall6538c932009-10-10 05:48:19 +00001672 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001673 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001674 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1675 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001676 Path != PathEnd; ++Path) {
1677 Decl *D = *Path->Decls.first;
1678 if (DeclsPrinted.insert(D).second)
1679 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1680 }
1681
Douglas Gregor1c846b02009-01-16 00:38:09 +00001682 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001683 }
1684
John McCall6538c932009-10-10 05:48:19 +00001685 case LookupResult::AmbiguousTagHiding: {
1686 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001687
John McCall6538c932009-10-10 05:48:19 +00001688 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1689
1690 LookupResult::iterator DI, DE = Result.end();
1691 for (DI = Result.begin(); DI != DE; ++DI)
1692 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1693 TagDecls.insert(TD);
1694 Diag(TD->getLocation(), diag::note_hidden_tag);
1695 }
1696
1697 for (DI = Result.begin(); DI != DE; ++DI)
1698 if (!isa<TagDecl>(*DI))
1699 Diag((*DI)->getLocation(), diag::note_hiding_object);
1700
1701 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001702 LookupResult::Filter F = Result.makeFilter();
1703 while (F.hasNext()) {
1704 if (TagDecls.count(F.next()))
1705 F.erase();
1706 }
1707 F.done();
John McCall6538c932009-10-10 05:48:19 +00001708
1709 return true;
1710 }
1711
1712 case LookupResult::AmbiguousReference: {
1713 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001714
John McCall6538c932009-10-10 05:48:19 +00001715 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1716 for (; DI != DE; ++DI)
1717 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001718
John McCall6538c932009-10-10 05:48:19 +00001719 return true;
1720 }
1721 }
1722
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001723 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001724}
Douglas Gregore254f902009-02-04 00:32:51 +00001725
John McCallf24d7bb2010-05-28 18:45:08 +00001726namespace {
1727 struct AssociatedLookup {
John McCall7d8b0412012-08-24 20:38:34 +00001728 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallf24d7bb2010-05-28 18:45:08 +00001729 Sema::AssociatedNamespaceSet &Namespaces,
1730 Sema::AssociatedClassSet &Classes)
John McCall7d8b0412012-08-24 20:38:34 +00001731 : S(S), Namespaces(Namespaces), Classes(Classes),
1732 InstantiationLoc(InstantiationLoc) {
John McCallf24d7bb2010-05-28 18:45:08 +00001733 }
1734
1735 Sema &S;
1736 Sema::AssociatedNamespaceSet &Namespaces;
1737 Sema::AssociatedClassSet &Classes;
John McCall7d8b0412012-08-24 20:38:34 +00001738 SourceLocation InstantiationLoc;
John McCallf24d7bb2010-05-28 18:45:08 +00001739 };
1740}
1741
Mike Stump11289f42009-09-09 15:08:12 +00001742static void
John McCallf24d7bb2010-05-28 18:45:08 +00001743addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001744
Douglas Gregor8b895222010-04-30 07:08:38 +00001745static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1746 DeclContext *Ctx) {
1747 // Add the associated namespace for this class.
1748
1749 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1750 // be a locally scoped record.
1751
Sebastian Redlbd595762010-08-31 20:53:31 +00001752 // We skip out of inline namespaces. The innermost non-inline namespace
1753 // contains all names of all its nested inline namespaces anyway, so we can
1754 // replace the entire inline namespace tree with its root.
1755 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1756 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00001757 Ctx = Ctx->getParent();
1758
John McCallc7e8e792009-08-07 22:18:02 +00001759 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001760 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001761}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001762
Mike Stump11289f42009-09-09 15:08:12 +00001763// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001764// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001765static void
John McCallf24d7bb2010-05-28 18:45:08 +00001766addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1767 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001768 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001769 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001770 switch (Arg.getKind()) {
1771 case TemplateArgument::Null:
1772 break;
Mike Stump11289f42009-09-09 15:08:12 +00001773
Douglas Gregor197e5f72009-07-08 07:51:57 +00001774 case TemplateArgument::Type:
1775 // [...] the namespaces and classes associated with the types of the
1776 // template arguments provided for template type parameters (excluding
1777 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001778 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001779 break;
Mike Stump11289f42009-09-09 15:08:12 +00001780
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001781 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001782 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00001783 // [...] the namespaces in which any template template arguments are
1784 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001785 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001786 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00001787 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001788 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001789 DeclContext *Ctx = ClassTemplate->getDeclContext();
1790 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001791 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001792 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001793 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001794 }
1795 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001796 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001797
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001798 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001799 case TemplateArgument::Integral:
1800 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001801 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001802 // associated namespaces. ]
1803 break;
Mike Stump11289f42009-09-09 15:08:12 +00001804
Douglas Gregor197e5f72009-07-08 07:51:57 +00001805 case TemplateArgument::Pack:
1806 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1807 PEnd = Arg.pack_end();
1808 P != PEnd; ++P)
John McCallf24d7bb2010-05-28 18:45:08 +00001809 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001810 break;
1811 }
1812}
1813
Douglas Gregore254f902009-02-04 00:32:51 +00001814// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001815// argument-dependent lookup with an argument of class type
1816// (C++ [basic.lookup.koenig]p2).
1817static void
John McCallf24d7bb2010-05-28 18:45:08 +00001818addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1819 CXXRecordDecl *Class) {
1820
1821 // Just silently ignore anything whose name is __va_list_tag.
1822 if (Class->getDeclName() == Result.S.VAListTagName)
1823 return;
1824
Douglas Gregore254f902009-02-04 00:32:51 +00001825 // C++ [basic.lookup.koenig]p2:
1826 // [...]
1827 // -- If T is a class type (including unions), its associated
1828 // classes are: the class itself; the class of which it is a
1829 // member, if any; and its direct and indirect base
1830 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001831 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001832
1833 // Add the class of which it is a member, if any.
1834 DeclContext *Ctx = Class->getDeclContext();
1835 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001836 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001837 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001838 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001839
Douglas Gregore254f902009-02-04 00:32:51 +00001840 // Add the class itself. If we've already seen this class, we don't
1841 // need to visit base classes.
John McCallf24d7bb2010-05-28 18:45:08 +00001842 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00001843 return;
1844
Mike Stump11289f42009-09-09 15:08:12 +00001845 // -- If T is a template-id, its associated namespaces and classes are
1846 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001847 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001848 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001849 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001850 // namespaces in which any template template arguments are defined; and
1851 // the classes in which any member templates used as template template
1852 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001853 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001854 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001855 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1856 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1857 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001858 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001859 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001860 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001861
Douglas Gregor197e5f72009-07-08 07:51:57 +00001862 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1863 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00001864 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001865 }
Mike Stump11289f42009-09-09 15:08:12 +00001866
John McCall67da35c2010-02-04 22:26:26 +00001867 // Only recurse into base classes for complete types.
1868 if (!Class->hasDefinition()) {
John McCall7d8b0412012-08-24 20:38:34 +00001869 QualType type = Result.S.Context.getTypeDeclType(Class);
1870 if (Result.S.RequireCompleteType(Result.InstantiationLoc, type,
1871 /*no diagnostic*/ 0))
1872 return;
John McCall67da35c2010-02-04 22:26:26 +00001873 }
1874
Douglas Gregore254f902009-02-04 00:32:51 +00001875 // Add direct and indirect base classes along with their associated
1876 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001877 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00001878 Bases.push_back(Class);
1879 while (!Bases.empty()) {
1880 // Pop this class off the stack.
1881 Class = Bases.back();
1882 Bases.pop_back();
1883
1884 // Visit the base classes.
1885 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1886 BaseEnd = Class->bases_end();
1887 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001888 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001889 // In dependent contexts, we do ADL twice, and the first time around,
1890 // the base type might be a dependent TemplateSpecializationType, or a
1891 // TemplateTypeParmType. If that happens, simply ignore it.
1892 // FIXME: If we want to support export, we probably need to add the
1893 // namespace of the template in a TemplateSpecializationType, or even
1894 // the classes and namespaces of known non-dependent arguments.
1895 if (!BaseType)
1896 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001897 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001898 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00001899 // Find the associated namespace for this base class.
1900 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00001901 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001902
1903 // Make sure we visit the bases of this base class.
1904 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1905 Bases.push_back(BaseDecl);
1906 }
1907 }
1908 }
1909}
1910
1911// \brief Add the associated classes and namespaces for
1912// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001913// (C++ [basic.lookup.koenig]p2).
1914static void
John McCallf24d7bb2010-05-28 18:45:08 +00001915addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00001916 // C++ [basic.lookup.koenig]p2:
1917 //
1918 // For each argument type T in the function call, there is a set
1919 // of zero or more associated namespaces and a set of zero or more
1920 // associated classes to be considered. The sets of namespaces and
1921 // classes is determined entirely by the types of the function
1922 // arguments (and the namespace of any template template
1923 // argument). Typedef names and using-declarations used to specify
1924 // the types do not contribute to this set. The sets of namespaces
1925 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00001926
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001927 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00001928 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1929
Douglas Gregore254f902009-02-04 00:32:51 +00001930 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00001931 switch (T->getTypeClass()) {
1932
1933#define TYPE(Class, Base)
1934#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1935#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1936#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1937#define ABSTRACT_TYPE(Class, Base)
1938#include "clang/AST/TypeNodes.def"
1939 // T is canonical. We can also ignore dependent types because
1940 // we don't need to do ADL at the definition point, but if we
1941 // wanted to implement template export (or if we find some other
1942 // use for associated classes and namespaces...) this would be
1943 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00001944 break;
Douglas Gregore254f902009-02-04 00:32:51 +00001945
John McCall0af3d3b2010-05-28 06:08:54 +00001946 // -- If T is a pointer to U or an array of U, its associated
1947 // namespaces and classes are those associated with U.
1948 case Type::Pointer:
1949 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1950 continue;
1951 case Type::ConstantArray:
1952 case Type::IncompleteArray:
1953 case Type::VariableArray:
1954 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1955 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001956
John McCall0af3d3b2010-05-28 06:08:54 +00001957 // -- If T is a fundamental type, its associated sets of
1958 // namespaces and classes are both empty.
1959 case Type::Builtin:
1960 break;
1961
1962 // -- If T is a class type (including unions), its associated
1963 // classes are: the class itself; the class of which it is a
1964 // member, if any; and its direct and indirect base
1965 // classes. Its associated namespaces are the namespaces in
1966 // which its associated classes are defined.
1967 case Type::Record: {
1968 CXXRecordDecl *Class
1969 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001970 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00001971 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00001972 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00001973
John McCall0af3d3b2010-05-28 06:08:54 +00001974 // -- If T is an enumeration type, its associated namespace is
1975 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001976 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00001977 // it has no associated class.
1978 case Type::Enum: {
1979 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001980
John McCall0af3d3b2010-05-28 06:08:54 +00001981 DeclContext *Ctx = Enum->getDeclContext();
1982 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001983 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001984
John McCall0af3d3b2010-05-28 06:08:54 +00001985 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001986 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001987
John McCall0af3d3b2010-05-28 06:08:54 +00001988 break;
1989 }
1990
1991 // -- If T is a function type, its associated namespaces and
1992 // classes are those associated with the function parameter
1993 // types and those associated with the return type.
1994 case Type::FunctionProto: {
1995 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1996 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1997 ArgEnd = Proto->arg_type_end();
1998 Arg != ArgEnd; ++Arg)
1999 Queue.push_back(Arg->getTypePtr());
2000 // fallthrough
2001 }
2002 case Type::FunctionNoProto: {
2003 const FunctionType *FnType = cast<FunctionType>(T);
2004 T = FnType->getResultType().getTypePtr();
2005 continue;
2006 }
2007
2008 // -- If T is a pointer to a member function of a class X, its
2009 // associated namespaces and classes are those associated
2010 // with the function parameter types and return type,
2011 // together with those associated with X.
2012 //
2013 // -- If T is a pointer to a data member of class X, its
2014 // associated namespaces and classes are those associated
2015 // with the member type together with those associated with
2016 // X.
2017 case Type::MemberPointer: {
2018 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2019
2020 // Queue up the class type into which this points.
2021 Queue.push_back(MemberPtr->getClass());
2022
2023 // And directly continue with the pointee type.
2024 T = MemberPtr->getPointeeType().getTypePtr();
2025 continue;
2026 }
2027
2028 // As an extension, treat this like a normal pointer.
2029 case Type::BlockPointer:
2030 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2031 continue;
2032
2033 // References aren't covered by the standard, but that's such an
2034 // obvious defect that we cover them anyway.
2035 case Type::LValueReference:
2036 case Type::RValueReference:
2037 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2038 continue;
2039
2040 // These are fundamental types.
2041 case Type::Vector:
2042 case Type::ExtVector:
2043 case Type::Complex:
2044 break;
2045
Douglas Gregor8e936662011-04-12 01:02:45 +00002046 // If T is an Objective-C object or interface type, or a pointer to an
2047 // object or interface type, the associated namespace is the global
2048 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002049 case Type::ObjCObject:
2050 case Type::ObjCInterface:
2051 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002052 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002053 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002054
2055 // Atomic types are just wrappers; use the associations of the
2056 // contained type.
2057 case Type::Atomic:
2058 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2059 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002060 }
2061
2062 if (Queue.empty()) break;
2063 T = Queue.back();
2064 Queue.pop_back();
Douglas Gregore254f902009-02-04 00:32:51 +00002065 }
Douglas Gregore254f902009-02-04 00:32:51 +00002066}
2067
2068/// \brief Find the associated classes and namespaces for
2069/// argument-dependent lookup for a call with the given set of
2070/// arguments.
2071///
2072/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002073/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002074/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002075void
John McCall7d8b0412012-08-24 20:38:34 +00002076Sema::FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
2077 llvm::ArrayRef<Expr *> Args,
Douglas Gregore254f902009-02-04 00:32:51 +00002078 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00002079 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002080 AssociatedNamespaces.clear();
2081 AssociatedClasses.clear();
2082
John McCall7d8b0412012-08-24 20:38:34 +00002083 AssociatedLookup Result(*this, InstantiationLoc,
2084 AssociatedNamespaces, AssociatedClasses);
John McCallf24d7bb2010-05-28 18:45:08 +00002085
Douglas Gregore254f902009-02-04 00:32:51 +00002086 // C++ [basic.lookup.koenig]p2:
2087 // For each argument type T in the function call, there is a set
2088 // of zero or more associated namespaces and a set of zero or more
2089 // associated classes to be considered. The sets of namespaces and
2090 // classes is determined entirely by the types of the function
2091 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002092 // argument).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002093 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregore254f902009-02-04 00:32:51 +00002094 Expr *Arg = Args[ArgIdx];
2095
2096 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002097 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002098 continue;
2099 }
2100
2101 // [...] In addition, if the argument is the name or address of a
2102 // set of overloaded functions and/or function templates, its
2103 // associated classes and namespaces are the union of those
2104 // associated with each of the members of the set: the namespace
2105 // in which the function or function template is defined and the
2106 // classes and namespaces associated with its (non-dependent)
2107 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002108 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002109 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002110 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002111 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002112
John McCallf24d7bb2010-05-28 18:45:08 +00002113 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2114 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002115
John McCallf24d7bb2010-05-28 18:45:08 +00002116 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2117 I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002118 // Look through any using declarations to find the underlying function.
2119 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002120
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002121 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2122 if (!FDecl)
2123 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002124
2125 // Add the classes and namespaces associated with the parameter
2126 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002127 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002128 }
2129 }
2130}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002131
2132/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2133/// an acceptable non-member overloaded operator for a call whose
2134/// arguments have types T1 (and, if non-empty, T2). This routine
2135/// implements the check in C++ [over.match.oper]p3b2 concerning
2136/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00002137static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002138IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2139 QualType T1, QualType T2,
2140 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00002141 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2142 return true;
2143
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002144 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2145 return true;
2146
John McCall9dd450b2009-09-21 23:43:11 +00002147 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002148 if (Proto->getNumArgs() < 1)
2149 return false;
2150
2151 if (T1->isEnumeralType()) {
2152 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002153 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002154 return true;
2155 }
2156
2157 if (Proto->getNumArgs() < 2)
2158 return false;
2159
2160 if (!T2.isNull() && T2->isEnumeralType()) {
2161 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002162 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002163 return true;
2164 }
2165
2166 return false;
2167}
2168
John McCall5cebab12009-11-18 07:57:50 +00002169NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002170 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002171 LookupNameKind NameKind,
2172 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002173 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002174 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002175 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002176}
2177
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002178/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002179ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002180 SourceLocation IdLoc,
2181 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002182 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002183 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002184 return cast_or_null<ObjCProtocolDecl>(D);
2185}
2186
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002187void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002188 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002189 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002190 // C++ [over.match.oper]p3:
2191 // -- The set of non-member candidates is the result of the
2192 // unqualified lookup of operator@ in the context of the
2193 // expression according to the usual rules for name lookup in
2194 // unqualified function calls (3.4.2) except that all member
2195 // functions are ignored. However, if no operand has a class
2196 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00002197 // that have a first parameter of type T1 or "reference to
2198 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002199 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00002200 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002201 // when T2 is an enumeration type, are candidate functions.
2202 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002203 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2204 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002205
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002206 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2207
John McCall9f3059a2009-10-09 21:13:30 +00002208 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002209 return;
2210
2211 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2212 Op != OpEnd; ++Op) {
Douglas Gregor645d76f2010-04-25 20:25:43 +00002213 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2214 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002215 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor645d76f2010-04-25 20:25:43 +00002216 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00002217 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor645d76f2010-04-25 20:25:43 +00002218 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor15448f82009-06-27 21:05:07 +00002219 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00002220 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00002221 // later?
2222 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor645d76f2010-04-25 20:25:43 +00002223 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor15448f82009-06-27 21:05:07 +00002224 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002225 }
2226}
2227
Alexis Hunt1da39282011-06-24 02:11:39 +00002228Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002229 CXXSpecialMember SM,
2230 bool ConstArg,
2231 bool VolatileArg,
2232 bool RValueThis,
2233 bool ConstThis,
2234 bool VolatileThis) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002235 RD = RD->getDefinition();
2236 assert((RD && !RD->isBeingDefined()) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002237 "doing special member lookup into record that isn't fully complete");
2238 if (RValueThis || ConstThis || VolatileThis)
2239 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2240 "constructors and destructors always have unqualified lvalue this");
2241 if (ConstArg || VolatileArg)
2242 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2243 "parameter-less special members can't have qualified arguments");
2244
2245 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002246 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002247 ID.AddInteger(SM);
2248 ID.AddInteger(ConstArg);
2249 ID.AddInteger(VolatileArg);
2250 ID.AddInteger(RValueThis);
2251 ID.AddInteger(ConstThis);
2252 ID.AddInteger(VolatileThis);
2253
2254 void *InsertPoint;
2255 SpecialMemberOverloadResult *Result =
2256 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2257
2258 // This was already cached
2259 if (Result)
2260 return Result;
2261
Alexis Huntba8e18d2011-06-07 00:11:58 +00002262 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2263 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002264 SpecialMemberCache.InsertNode(Result, InsertPoint);
2265
2266 if (SM == CXXDestructor) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002267 if (!RD->hasDeclaredDestructor())
2268 DeclareImplicitDestructor(RD);
2269 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002270 assert(DD && "record without a destructor");
2271 Result->setMethod(DD);
Richard Smith852265f2012-03-30 20:53:28 +00002272 Result->setKind(DD->isDeleted() ?
2273 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith83c478d2012-04-20 18:46:14 +00002274 SpecialMemberOverloadResult::Success);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002275 return Result;
2276 }
2277
Alexis Hunteef8ee02011-06-10 03:50:41 +00002278 // Prepare for overload resolution. Here we construct a synthetic argument
2279 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002280 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002281 DeclarationName Name;
2282 Expr *Arg = 0;
2283 unsigned NumArgs;
2284
Richard Smith83c478d2012-04-20 18:46:14 +00002285 QualType ArgType = CanTy;
2286 ExprValueKind VK = VK_LValue;
2287
Alexis Hunteef8ee02011-06-10 03:50:41 +00002288 if (SM == CXXDefaultConstructor) {
2289 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2290 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002291 if (RD->needsImplicitDefaultConstructor())
2292 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002293 } else {
2294 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2295 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Alexis Hunt1da39282011-06-24 02:11:39 +00002296 if (!RD->hasDeclaredCopyConstructor())
2297 DeclareImplicitCopyConstructor(RD);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002298 if (getLangOpts().CPlusPlus0x && RD->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002299 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002300 } else {
2301 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Alexis Hunt1da39282011-06-24 02:11:39 +00002302 if (!RD->hasDeclaredCopyAssignment())
2303 DeclareImplicitCopyAssignment(RD);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002304 if (getLangOpts().CPlusPlus0x && RD->needsImplicitMoveAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002305 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002306 }
2307
Alexis Hunteef8ee02011-06-10 03:50:41 +00002308 if (ConstArg)
2309 ArgType.addConst();
2310 if (VolatileArg)
2311 ArgType.addVolatile();
2312
2313 // This isn't /really/ specified by the standard, but it's implied
2314 // we should be working from an RValue in the case of move to ensure
2315 // that we prefer to bind to rvalue references, and an LValue in the
2316 // case of copy to ensure we don't bind to rvalue references.
2317 // Possibly an XValue is actually correct in the case of move, but
2318 // there is no semantic difference for class types in this restricted
2319 // case.
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002320 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002321 VK = VK_LValue;
2322 else
2323 VK = VK_RValue;
Richard Smith83c478d2012-04-20 18:46:14 +00002324 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00002325
Richard Smith83c478d2012-04-20 18:46:14 +00002326 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2327
2328 if (SM != CXXDefaultConstructor) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002329 NumArgs = 1;
Richard Smith83c478d2012-04-20 18:46:14 +00002330 Arg = &FakeArg;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002331 }
2332
2333 // Create the object argument
2334 QualType ThisTy = CanTy;
2335 if (ConstThis)
2336 ThisTy.addConst();
2337 if (VolatileThis)
2338 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002339 Expr::Classification Classification =
Richard Smith83c478d2012-04-20 18:46:14 +00002340 OpaqueValueExpr(SourceLocation(), ThisTy,
2341 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002342
2343 // Now we perform lookup on the name we computed earlier and do overload
2344 // resolution. Lookup is only performed directly into the class since there
2345 // will always be a (possibly implicit) declaration to shadow any others.
2346 OverloadCandidateSet OCS((SourceLocation()));
2347 DeclContext::lookup_iterator I, E;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002348
Alexis Hunt1da39282011-06-24 02:11:39 +00002349 llvm::tie(I, E) = RD->lookup(Name);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002350 assert((I != E) &&
2351 "lookup for a constructor or assignment operator was empty");
2352 for ( ; I != E; ++I) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002353 Decl *Cand = *I;
Alexis Hunt080709f2011-06-23 00:26:20 +00002354
Alexis Hunt1da39282011-06-24 02:11:39 +00002355 if (Cand->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002356 continue;
2357
Alexis Hunt1da39282011-06-24 02:11:39 +00002358 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2359 // FIXME: [namespace.udecl]p15 says that we should only consider a
2360 // using declaration here if it does not match a declaration in the
2361 // derived class. We do not implement this correctly in other cases
2362 // either.
2363 Cand = U->getTargetDecl();
2364
2365 if (Cand->isInvalidDecl())
2366 continue;
2367 }
2368
2369 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002370 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Alexis Hunt1da39282011-06-24 02:11:39 +00002371 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002372 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2373 OCS, true);
Alexis Hunt080709f2011-06-23 00:26:20 +00002374 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002375 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2376 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt2949f022011-06-22 02:58:46 +00002377 } else if (FunctionTemplateDecl *Tmpl =
Alexis Hunt1da39282011-06-24 02:11:39 +00002378 dyn_cast<FunctionTemplateDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002379 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2380 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002381 RD, 0, ThisTy, Classification,
2382 llvm::makeArrayRef(&Arg, NumArgs),
Alexis Hunt080709f2011-06-23 00:26:20 +00002383 OCS, true);
2384 else
2385 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002386 0, llvm::makeArrayRef(&Arg, NumArgs),
2387 OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002388 } else {
2389 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002390 }
2391 }
2392
2393 OverloadCandidateSet::iterator Best;
2394 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2395 case OR_Success:
2396 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith83c478d2012-04-20 18:46:14 +00002397 Result->setKind(SpecialMemberOverloadResult::Success);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002398 break;
2399
2400 case OR_Deleted:
2401 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith852265f2012-03-30 20:53:28 +00002402 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002403 break;
2404
2405 case OR_Ambiguous:
Richard Smith852265f2012-03-30 20:53:28 +00002406 Result->setMethod(0);
2407 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2408 break;
2409
Alexis Hunteef8ee02011-06-10 03:50:41 +00002410 case OR_No_Viable_Function:
2411 Result->setMethod(0);
Richard Smith852265f2012-03-30 20:53:28 +00002412 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002413 break;
2414 }
2415
2416 return Result;
2417}
2418
2419/// \brief Look up the default constructor for the given class.
2420CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002421 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002422 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2423 false, false);
2424
2425 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002426}
2427
Alexis Hunt491ec602011-06-21 23:42:56 +00002428/// \brief Look up the copying constructor for the given class.
2429CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith83c478d2012-04-20 18:46:14 +00002430 unsigned Quals) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002431 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2432 "non-const, non-volatile qualifiers for copy ctor arg");
2433 SpecialMemberOverloadResult *Result =
2434 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2435 Quals & Qualifiers::Volatile, false, false, false);
2436
Alexis Hunt899bd442011-06-10 04:44:37 +00002437 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2438}
2439
Sebastian Redl22653ba2011-08-30 19:58:05 +00002440/// \brief Look up the moving constructor for the given class.
Richard Smith1c6461e2012-07-18 03:36:00 +00002441CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2442 unsigned Quals) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002443 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002444 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2445 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002446
2447 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2448}
2449
Douglas Gregor52b72822010-07-02 23:12:18 +00002450/// \brief Look up the constructors for the given class.
2451DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002452 // If the implicit constructors have not yet been declared, do so now.
Douglas Gregor9672f922010-07-03 00:47:00 +00002453 if (CanDeclareSpecialMemberFunction(Context, Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00002454 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002455 DeclareImplicitDefaultConstructor(Class);
2456 if (!Class->hasDeclaredCopyConstructor())
2457 DeclareImplicitCopyConstructor(Class);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002458 if (getLangOpts().CPlusPlus0x && Class->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002459 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00002460 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002461
Douglas Gregor52b72822010-07-02 23:12:18 +00002462 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2463 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2464 return Class->lookup(Name);
2465}
2466
Alexis Hunt491ec602011-06-21 23:42:56 +00002467/// \brief Look up the copying assignment operator for the given class.
2468CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2469 unsigned Quals, bool RValueThis,
Richard Smith83c478d2012-04-20 18:46:14 +00002470 unsigned ThisQuals) {
Alexis Hunt491ec602011-06-21 23:42:56 +00002471 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2472 "non-const, non-volatile qualifiers for copy assignment arg");
2473 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2474 "non-const, non-volatile qualifiers for copy assignment this");
2475 SpecialMemberOverloadResult *Result =
2476 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2477 Quals & Qualifiers::Volatile, RValueThis,
2478 ThisQuals & Qualifiers::Const,
2479 ThisQuals & Qualifiers::Volatile);
2480
Alexis Hunt491ec602011-06-21 23:42:56 +00002481 return Result->getMethod();
2482}
2483
Sebastian Redl22653ba2011-08-30 19:58:05 +00002484/// \brief Look up the moving assignment operator for the given class.
2485CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith1c6461e2012-07-18 03:36:00 +00002486 unsigned Quals,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002487 bool RValueThis,
2488 unsigned ThisQuals) {
2489 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2490 "non-const, non-volatile qualifiers for copy assignment this");
2491 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002492 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2493 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002494 ThisQuals & Qualifiers::Const,
2495 ThisQuals & Qualifiers::Volatile);
2496
2497 return Result->getMethod();
2498}
2499
Douglas Gregore71edda2010-07-01 22:47:18 +00002500/// \brief Look for the destructor of the given class.
2501///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00002502/// During semantic analysis, this routine should be used in lieu of
2503/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00002504///
2505/// \returns The destructor for this class.
2506CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002507 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2508 false, false, false,
2509 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00002510}
2511
Richard Smithbcc22fc2012-03-09 08:00:36 +00002512/// LookupLiteralOperator - Determine which literal operator should be used for
2513/// a user-defined literal, per C++11 [lex.ext].
2514///
2515/// Normal overload resolution is not used to select which literal operator to
2516/// call for a user-defined literal. Look up the provided literal operator name,
2517/// and filter the results to the appropriate set for the given argument types.
2518Sema::LiteralOperatorLookupResult
2519Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2520 ArrayRef<QualType> ArgTys,
2521 bool AllowRawAndTemplate) {
2522 LookupName(R, S);
2523 assert(R.getResultKind() != LookupResult::Ambiguous &&
2524 "literal operator lookup can't be ambiguous");
2525
2526 // Filter the lookup results appropriately.
2527 LookupResult::Filter F = R.makeFilter();
2528
2529 bool FoundTemplate = false;
2530 bool FoundRaw = false;
2531 bool FoundExactMatch = false;
2532
2533 while (F.hasNext()) {
2534 Decl *D = F.next();
2535 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2536 D = USD->getTargetDecl();
2537
2538 bool IsTemplate = isa<FunctionTemplateDecl>(D);
2539 bool IsRaw = false;
2540 bool IsExactMatch = false;
2541
2542 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2543 if (FD->getNumParams() == 1 &&
2544 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2545 IsRaw = true;
2546 else {
2547 IsExactMatch = true;
2548 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2549 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2550 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2551 IsExactMatch = false;
2552 break;
2553 }
2554 }
2555 }
2556 }
2557
2558 if (IsExactMatch) {
2559 FoundExactMatch = true;
2560 AllowRawAndTemplate = false;
2561 if (FoundRaw || FoundTemplate) {
2562 // Go through again and remove the raw and template decls we've
2563 // already found.
2564 F.restart();
2565 FoundRaw = FoundTemplate = false;
2566 }
2567 } else if (AllowRawAndTemplate && (IsTemplate || IsRaw)) {
2568 FoundTemplate |= IsTemplate;
2569 FoundRaw |= IsRaw;
2570 } else {
2571 F.erase();
2572 }
2573 }
2574
2575 F.done();
2576
2577 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2578 // parameter type, that is used in preference to a raw literal operator
2579 // or literal operator template.
2580 if (FoundExactMatch)
2581 return LOLR_Cooked;
2582
2583 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2584 // operator template, but not both.
2585 if (FoundRaw && FoundTemplate) {
2586 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
2587 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2588 Decl *D = *I;
2589 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2590 D = USD->getTargetDecl();
2591 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2592 D = FunTmpl->getTemplatedDecl();
2593 NoteOverloadCandidate(cast<FunctionDecl>(D));
2594 }
2595 return LOLR_Error;
2596 }
2597
2598 if (FoundRaw)
2599 return LOLR_Raw;
2600
2601 if (FoundTemplate)
2602 return LOLR_Template;
2603
2604 // Didn't find anything we could use.
2605 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2606 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
2607 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRawAndTemplate;
2608 return LOLR_Error;
2609}
2610
John McCall8fe68082010-01-26 07:16:45 +00002611void ADLResult::insert(NamedDecl *New) {
2612 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2613
2614 // If we haven't yet seen a decl for this key, or the last decl
2615 // was exactly this one, we're done.
2616 if (Old == 0 || Old == New) {
2617 Old = New;
2618 return;
2619 }
2620
2621 // Otherwise, decide which is a more recent redeclaration.
2622 FunctionDecl *OldFD, *NewFD;
2623 if (isa<FunctionTemplateDecl>(New)) {
2624 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2625 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2626 } else {
2627 OldFD = cast<FunctionDecl>(Old);
2628 NewFD = cast<FunctionDecl>(New);
2629 }
2630
2631 FunctionDecl *Cursor = NewFD;
2632 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002633 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00002634
2635 // If we got to the end without finding OldFD, OldFD is the newer
2636 // declaration; leave things as they are.
2637 if (!Cursor) return;
2638
2639 // If we do find OldFD, then NewFD is newer.
2640 if (Cursor == OldFD) break;
2641
2642 // Otherwise, keep looking.
2643 }
2644
2645 Old = New;
2646}
2647
Sebastian Redlc057f422009-10-23 19:23:15 +00002648void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Richard Smithe06a2c12012-02-25 06:24:24 +00002649 SourceLocation Loc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002650 llvm::ArrayRef<Expr *> Args,
Richard Smith02e85f32011-04-14 22:09:26 +00002651 ADLResult &Result,
2652 bool StdNamespaceIsAssociated) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002653 // Find all of the associated namespaces and classes based on the
2654 // arguments we have.
2655 AssociatedNamespaceSet AssociatedNamespaces;
2656 AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00002657 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCallc7e8e792009-08-07 22:18:02 +00002658 AssociatedNamespaces,
2659 AssociatedClasses);
Richard Smith02e85f32011-04-14 22:09:26 +00002660 if (StdNamespaceIsAssociated && StdNamespace)
2661 AssociatedNamespaces.insert(getStdNamespace());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002662
Sebastian Redlc057f422009-10-23 19:23:15 +00002663 QualType T1, T2;
2664 if (Operator) {
2665 T1 = Args[0]->getType();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002666 if (Args.size() >= 2)
Sebastian Redlc057f422009-10-23 19:23:15 +00002667 T2 = Args[1]->getType();
2668 }
2669
Richard Smithe06a2c12012-02-25 06:24:24 +00002670 // Try to complete all associated classes, in case they contain a
2671 // declaration of a friend function.
2672 for (AssociatedClassSet::iterator C = AssociatedClasses.begin(),
2673 CEnd = AssociatedClasses.end();
2674 C != CEnd; ++C)
2675 RequireCompleteType(Loc, Context.getRecordType(*C), 0);
2676
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002677 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002678 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2679 // and let Y be the lookup set produced by argument dependent
2680 // lookup (defined as follows). If X contains [...] then Y is
2681 // empty. Otherwise Y is the set of declarations found in the
2682 // namespaces associated with the argument types as described
2683 // below. The set of declarations found by the lookup of the name
2684 // is the union of X and Y.
2685 //
2686 // Here, we compute Y and add its members to the overloaded
2687 // candidate set.
2688 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00002689 NSEnd = AssociatedNamespaces.end();
2690 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002691 // When considering an associated namespace, the lookup is the
2692 // same as the lookup performed when the associated namespace is
2693 // used as a qualifier (3.4.3.2) except that:
2694 //
2695 // -- Any using-directives in the associated namespace are
2696 // ignored.
2697 //
John McCallc7e8e792009-08-07 22:18:02 +00002698 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002699 // associated classes are visible within their respective
2700 // namespaces even if they are not visible during an ordinary
2701 // lookup (11.4).
2702 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00002703 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00002704 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00002705 // If the only declaration here is an ordinary friend, consider
2706 // it only if it was declared in an associated classes.
2707 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00002708 DeclContext *LexDC = D->getLexicalDeclContext();
2709 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2710 continue;
2711 }
Mike Stump11289f42009-09-09 15:08:12 +00002712
John McCall91f61fc2010-01-26 06:04:06 +00002713 if (isa<UsingShadowDecl>(D))
2714 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002715
John McCall91f61fc2010-01-26 06:04:06 +00002716 if (isa<FunctionDecl>(D)) {
2717 if (Operator &&
2718 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2719 T1, T2, Context))
2720 continue;
John McCall8fe68082010-01-26 07:16:45 +00002721 } else if (!isa<FunctionTemplateDecl>(D))
2722 continue;
2723
2724 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002725 }
2726 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002727}
Douglas Gregor2d435302009-12-30 17:04:44 +00002728
2729//----------------------------------------------------------------------------
2730// Search for all visible declarations.
2731//----------------------------------------------------------------------------
2732VisibleDeclConsumer::~VisibleDeclConsumer() { }
2733
2734namespace {
2735
2736class ShadowContextRAII;
2737
2738class VisibleDeclsRecord {
2739public:
2740 /// \brief An entry in the shadow map, which is optimized to store a
2741 /// single declaration (the common case) but can also store a list
2742 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002743 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00002744
2745private:
2746 /// \brief A mapping from declaration names to the declarations that have
2747 /// this name within a particular scope.
2748 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2749
2750 /// \brief A list of shadow maps, which is used to model name hiding.
2751 std::list<ShadowMap> ShadowMaps;
2752
2753 /// \brief The declaration contexts we have already visited.
2754 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2755
2756 friend class ShadowContextRAII;
2757
2758public:
2759 /// \brief Determine whether we have already visited this context
2760 /// (and, if not, note that we are going to visit that context now).
2761 bool visitedContext(DeclContext *Ctx) {
2762 return !VisitedContexts.insert(Ctx);
2763 }
2764
Douglas Gregor39982192010-08-15 06:18:01 +00002765 bool alreadyVisitedContext(DeclContext *Ctx) {
2766 return VisitedContexts.count(Ctx);
2767 }
2768
Douglas Gregor2d435302009-12-30 17:04:44 +00002769 /// \brief Determine whether the given declaration is hidden in the
2770 /// current scope.
2771 ///
2772 /// \returns the declaration that hides the given declaration, or
2773 /// NULL if no such declaration exists.
2774 NamedDecl *checkHidden(NamedDecl *ND);
2775
2776 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002777 void add(NamedDecl *ND) {
2778 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2779 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002780};
2781
2782/// \brief RAII object that records when we've entered a shadow context.
2783class ShadowContextRAII {
2784 VisibleDeclsRecord &Visible;
2785
2786 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2787
2788public:
2789 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2790 Visible.ShadowMaps.push_back(ShadowMap());
2791 }
2792
2793 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00002794 Visible.ShadowMaps.pop_back();
2795 }
2796};
2797
2798} // end anonymous namespace
2799
Douglas Gregor2d435302009-12-30 17:04:44 +00002800NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002801 // Look through using declarations.
2802 ND = ND->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002803
Douglas Gregor2d435302009-12-30 17:04:44 +00002804 unsigned IDNS = ND->getIdentifierNamespace();
2805 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2806 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2807 SM != SMEnd; ++SM) {
2808 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2809 if (Pos == SM->end())
2810 continue;
2811
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002812 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor2d435302009-12-30 17:04:44 +00002813 IEnd = Pos->second.end();
2814 I != IEnd; ++I) {
2815 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +00002816 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002817 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00002818 Decl::IDNS_ObjCProtocol)))
2819 continue;
2820
2821 // Protocols are in distinct namespaces from everything else.
2822 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2823 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2824 (*I)->getIdentifierNamespace() != IDNS)
2825 continue;
2826
Douglas Gregor09bbc652010-01-14 15:47:35 +00002827 // Functions and function templates in the same scope overload
2828 // rather than hide. FIXME: Look for hiding based on function
2829 // signatures!
Douglas Gregor200c99d2010-01-14 03:35:48 +00002830 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002831 ND->isFunctionOrFunctionTemplate() &&
2832 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002833 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002834
Douglas Gregor2d435302009-12-30 17:04:44 +00002835 // We've found a declaration that hides this one.
2836 return *I;
2837 }
2838 }
2839
2840 return 0;
2841}
2842
2843static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2844 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002845 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002846 VisibleDeclConsumer &Consumer,
2847 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002848 if (!Ctx)
2849 return;
2850
Douglas Gregor2d435302009-12-30 17:04:44 +00002851 // Make sure we don't visit the same context twice.
2852 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2853 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002854
Douglas Gregor7454c562010-07-02 20:37:36 +00002855 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2856 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2857
Douglas Gregor2d435302009-12-30 17:04:44 +00002858 // Enumerate all of the results in this context.
Nick Lewyckyc3921482012-04-03 21:44:08 +00002859 for (DeclContext::all_lookups_iterator L = Ctx->lookups_begin(),
2860 LEnd = Ctx->lookups_end();
2861 L != LEnd; ++L) {
2862 for (DeclContext::lookup_result R = *L; R.first != R.second; ++R.first) {
2863 if (NamedDecl *ND = dyn_cast<NamedDecl>(*R.first)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00002864 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00002865 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002866 Visited.add(ND);
2867 }
Douglas Gregora3b23b02010-12-09 21:44:02 +00002868 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002869 }
2870 }
2871
2872 // Traverse using directives for qualified name lookup.
2873 if (QualifiedNameLookup) {
2874 ShadowContextRAII Shadow(Visited);
2875 DeclContext::udir_iterator I, E;
2876 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002877 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002878 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002879 }
2880 }
2881
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002882 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00002883 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00002884 if (!Record->hasDefinition())
2885 return;
2886
Douglas Gregor2d435302009-12-30 17:04:44 +00002887 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2888 BEnd = Record->bases_end();
2889 B != BEnd; ++B) {
2890 QualType BaseType = B->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002891
Douglas Gregor2d435302009-12-30 17:04:44 +00002892 // Don't look into dependent bases, because name lookup can't look
2893 // there anyway.
2894 if (BaseType->isDependentType())
2895 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002896
Douglas Gregor2d435302009-12-30 17:04:44 +00002897 const RecordType *Record = BaseType->getAs<RecordType>();
2898 if (!Record)
2899 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002900
Douglas Gregor2d435302009-12-30 17:04:44 +00002901 // FIXME: It would be nice to be able to determine whether referencing
2902 // a particular member would be ambiguous. For example, given
2903 //
2904 // struct A { int member; };
2905 // struct B { int member; };
2906 // struct C : A, B { };
2907 //
2908 // void f(C *c) { c->### }
2909 //
2910 // accessing 'member' would result in an ambiguity. However, we
2911 // could be smart enough to qualify the member with the base
2912 // class, e.g.,
2913 //
2914 // c->B::member
2915 //
2916 // or
2917 //
2918 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002919
Douglas Gregor2d435302009-12-30 17:04:44 +00002920 // Find results in this base class (and its bases).
2921 ShadowContextRAII Shadow(Visited);
2922 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002923 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002924 }
2925 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002926
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002927 // Traverse the contexts of Objective-C classes.
2928 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2929 // Traverse categories.
2930 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2931 Category; Category = Category->getNextClassCategory()) {
2932 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002933 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002934 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002935 }
2936
2937 // Traverse protocols.
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002938 for (ObjCInterfaceDecl::all_protocol_iterator
2939 I = IFace->all_referenced_protocol_begin(),
2940 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002941 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002942 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002943 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002944 }
2945
2946 // Traverse the superclass.
2947 if (IFace->getSuperClass()) {
2948 ShadowContextRAII Shadow(Visited);
2949 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002950 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002951 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002952
Douglas Gregor0b59e802010-04-19 18:02:19 +00002953 // If there is an implementation, traverse it. We do this to find
2954 // synthesized ivars.
2955 if (IFace->getImplementation()) {
2956 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002957 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky13668f22012-04-03 20:26:45 +00002958 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor0b59e802010-04-19 18:02:19 +00002959 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002960 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2961 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2962 E = Protocol->protocol_end(); I != E; ++I) {
2963 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002964 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002965 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002966 }
2967 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2968 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2969 E = Category->protocol_end(); I != E; ++I) {
2970 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002971 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002972 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002973 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002974
Douglas Gregor0b59e802010-04-19 18:02:19 +00002975 // If there is an implementation, traverse it.
2976 if (Category->getImplementation()) {
2977 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002978 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00002979 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002980 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002981 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002982}
2983
2984static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2985 UnqualUsingDirectiveSet &UDirs,
2986 VisibleDeclConsumer &Consumer,
2987 VisibleDeclsRecord &Visited) {
2988 if (!S)
2989 return;
2990
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002991 if (!S->getEntity() ||
2992 (!S->getParent() &&
Douglas Gregor39982192010-08-15 06:18:01 +00002993 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002994 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2995 // Walk through the declarations in this Scope.
2996 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2997 D != DEnd; ++D) {
John McCall48871652010-08-21 09:40:31 +00002998 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor4a814562011-12-14 16:03:29 +00002999 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003000 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003001 Visited.add(ND);
3002 }
3003 }
3004 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003005
Douglas Gregor66230062010-03-15 14:33:29 +00003006 // FIXME: C++ [temp.local]p8
Douglas Gregor2d435302009-12-30 17:04:44 +00003007 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00003008 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003009 // Look into this scope's declaration context, along with any of its
3010 // parent lookup contexts (e.g., enclosing classes), up to the point
3011 // where we hit the context stored in the next outer scope.
3012 Entity = (DeclContext *)S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00003013 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003014
Douglas Gregorea166062010-03-15 15:26:48 +00003015 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00003016 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003017 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3018 if (Method->isInstanceMethod()) {
3019 // For instance methods, look for ivars in the method's interface.
3020 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3021 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003022 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003023 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Fariborz Jahanian97d744b2011-08-31 22:24:06 +00003024 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003025 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003026 }
3027
3028 // We've already performed all of the name lookup that we need
3029 // to for Objective-C methods; the next context will be the
3030 // outer scope.
3031 break;
3032 }
3033
Douglas Gregor2d435302009-12-30 17:04:44 +00003034 if (Ctx->isFunctionOrMethod())
3035 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003036
3037 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003038 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003039 }
3040 } else if (!S->getParent()) {
3041 // Look into the translation unit scope. We walk through the translation
3042 // unit's declaration context, because the Scope itself won't have all of
3043 // the declarations if we loaded a precompiled header.
3044 // FIXME: We would like the translation unit's Scope object to point to the
3045 // translation unit, so we don't need this special "if" branch. However,
3046 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003047 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00003048 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003049 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00003050 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003051 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003052 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003053 }
3054
Douglas Gregor2d435302009-12-30 17:04:44 +00003055 if (Entity) {
3056 // Lookup visible declarations in any namespaces found by using
3057 // directives.
3058 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
3059 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
3060 for (; UI != UEnd; ++UI)
3061 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003062 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003063 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003064 }
3065
3066 // Lookup names in the parent scope.
3067 ShadowContextRAII Shadow(Visited);
3068 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3069}
3070
3071void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003072 VisibleDeclConsumer &Consumer,
3073 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003074 // Determine the set of using directives available during
3075 // unqualified name lookup.
3076 Scope *Initial = S;
3077 UnqualUsingDirectiveSet UDirs;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003078 if (getLangOpts().CPlusPlus) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003079 // Find the first namespace or translation-unit scope.
3080 while (S && !isNamespaceOrTranslationUnitScope(S))
3081 S = S->getParent();
3082
3083 UDirs.visitScopeChain(Initial, S);
3084 }
3085 UDirs.done();
3086
3087 // Look for visible declarations.
3088 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3089 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003090 if (!IncludeGlobalScope)
3091 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003092 ShadowContextRAII Shadow(Visited);
3093 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3094}
3095
3096void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003097 VisibleDeclConsumer &Consumer,
3098 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003099 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3100 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003101 if (!IncludeGlobalScope)
3102 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003103 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003104 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003105 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003106}
3107
Chris Lattner43e7f312011-02-18 02:08:43 +00003108/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003109/// If GnuLabelLoc is a valid source location, then this is a definition
3110/// of an __label__ label name, otherwise it is a normal label definition
3111/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003112LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003113 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003114 // Do a lookup to see if we have a label with this name already.
Chris Lattner43e7f312011-02-18 02:08:43 +00003115 NamedDecl *Res = 0;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003116
3117 if (GnuLabelLoc.isValid()) {
3118 // Local label definitions always shadow existing labels.
3119 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3120 Scope *S = CurScope;
3121 PushOnScopeChains(Res, S, true);
3122 return cast<LabelDecl>(Res);
3123 }
3124
3125 // Not a GNU local label.
3126 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3127 // If we found a label, check to see if it is in the same context as us.
3128 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003129 if (Res && Res->getDeclContext() != CurContext)
3130 Res = 0;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003131 if (Res == 0) {
3132 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003133 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3134 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003135 assert(S && "Not in a function?");
3136 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003137 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003138 return cast<LabelDecl>(Res);
3139}
3140
3141//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003142// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003143//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003144
3145namespace {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003146
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003147typedef llvm::SmallVector<TypoCorrection, 1> TypoResultList;
3148typedef llvm::StringMap<TypoResultList, llvm::BumpPtrAllocator> TypoResultsMap;
Benjamin Kramer73faad62012-04-14 08:26:28 +00003149typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003150
3151static const unsigned MaxTypoDistanceResultSets = 5;
3152
Douglas Gregor2d435302009-12-30 17:04:44 +00003153class TypoCorrectionConsumer : public VisibleDeclConsumer {
3154 /// \brief The name written that is a typo in the source.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003155 StringRef Typo;
Douglas Gregor2d435302009-12-30 17:04:44 +00003156
3157 /// \brief The results found that have the smallest edit distance
3158 /// found (so far) with the typo name.
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003159 ///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003160 /// The pointer value being set to the current DeclContext indicates
3161 /// whether there is a keyword with this name.
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003162 TypoEditDistanceMap CorrectionResults;
Douglas Gregor2d435302009-12-30 17:04:44 +00003163
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003164 Sema &SemaRef;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003165
Douglas Gregor2d435302009-12-30 17:04:44 +00003166public:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003167 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003168 : Typo(Typo->getName()),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003169 SemaRef(SemaRef) { }
Douglas Gregor2d435302009-12-30 17:04:44 +00003170
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003171 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3172 bool InBaseClass);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003173 void FoundName(StringRef Name);
3174 void addKeywordResult(StringRef Keyword);
3175 void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003176 NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003177 void addCorrection(TypoCorrection Correction);
Douglas Gregor2d435302009-12-30 17:04:44 +00003178
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003179 typedef TypoResultsMap::iterator result_iterator;
3180 typedef TypoEditDistanceMap::iterator distance_iterator;
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003181 distance_iterator begin() { return CorrectionResults.begin(); }
3182 distance_iterator end() { return CorrectionResults.end(); }
3183 void erase(distance_iterator I) { CorrectionResults.erase(I); }
3184 unsigned size() const { return CorrectionResults.size(); }
3185 bool empty() const { return CorrectionResults.empty(); }
Douglas Gregor2d435302009-12-30 17:04:44 +00003186
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003187 TypoResultList &operator[](StringRef Name) {
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003188 return CorrectionResults.begin()->second[Name];
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003189 }
3190
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003191 unsigned getBestEditDistance(bool Normalized) {
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003192 if (CorrectionResults.empty())
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003193 return (std::numeric_limits<unsigned>::max)();
3194
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003195 unsigned BestED = CorrectionResults.begin()->first;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003196 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003197 }
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003198
3199 TypoResultsMap &getBestResults() {
3200 return CorrectionResults.begin()->second;
3201 }
3202
Douglas Gregor2d435302009-12-30 17:04:44 +00003203};
3204
3205}
3206
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003207void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003208 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003209 // Don't consider hidden names for typo correction.
3210 if (Hiding)
3211 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003212
Douglas Gregor2d435302009-12-30 17:04:44 +00003213 // Only consider entities with identifiers for names, ignoring
3214 // special names (constructors, overloaded operators, selectors,
3215 // etc.).
3216 IdentifierInfo *Name = ND->getIdentifier();
3217 if (!Name)
3218 return;
3219
Douglas Gregor57756ea2010-10-14 22:11:03 +00003220 FoundName(Name->getName());
3221}
3222
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003223void TypoCorrectionConsumer::FoundName(StringRef Name) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003224 // Use a simple length-based heuristic to determine the minimum possible
3225 // edit distance. If the minimum isn't good enough, bail out early.
3226 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003227 if (MinED && Typo.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00003228 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003229
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003230 // Compute an upper bound on the allowable edit distance, so that the
3231 // edit-distance algorithm can short-circuit.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003232 unsigned UpperBound = (Typo.size() + 2) / 3;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003233
Douglas Gregor2d435302009-12-30 17:04:44 +00003234 // Compute the edit distance between the typo and the name of this
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003235 // entity, and add the identifier to the list of results.
3236 addName(Name, NULL, Typo.edit_distance(Name, true, UpperBound));
Douglas Gregor2d435302009-12-30 17:04:44 +00003237}
3238
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003239void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003240 // Compute the edit distance between the typo and this keyword,
3241 // and add the keyword to the list of results.
3242 addName(Keyword, NULL, Typo.edit_distance(Keyword), NULL, true);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003243}
3244
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003245void TypoCorrectionConsumer::addName(StringRef Name,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003246 NamedDecl *ND,
3247 unsigned Distance,
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003248 NestedNameSpecifier *NNS,
3249 bool isKeyword) {
3250 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
3251 if (isKeyword) TC.makeKeyword();
3252 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003253}
3254
3255void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003256 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003257 TypoResultList &CList =
3258 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003259
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003260 if (!CList.empty() && !CList.back().isResolved())
3261 CList.pop_back();
3262 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3263 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3264 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3265 RI != RIEnd; ++RI) {
3266 // If the Correction refers to a decl already in the result list,
3267 // replace the existing result if the string representation of Correction
3268 // comes before the current result alphabetically, then stop as there is
3269 // nothing more to be done to add Correction to the candidate set.
3270 if (RI->getCorrectionDecl() == NewND) {
3271 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3272 *RI = Correction;
3273 return;
3274 }
3275 }
3276 }
3277 if (CList.empty() || Correction.isResolved())
3278 CList.push_back(Correction);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003279
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003280 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
3281 erase(llvm::prior(CorrectionResults.end()));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003282}
3283
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003284// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3285// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3286// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3287static void getNestedNameSpecifierIdentifiers(
3288 NestedNameSpecifier *NNS,
3289 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3290 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3291 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3292 else
3293 Identifiers.clear();
3294
3295 const IdentifierInfo *II = NULL;
3296
3297 switch (NNS->getKind()) {
3298 case NestedNameSpecifier::Identifier:
3299 II = NNS->getAsIdentifier();
3300 break;
3301
3302 case NestedNameSpecifier::Namespace:
3303 if (NNS->getAsNamespace()->isAnonymousNamespace())
3304 return;
3305 II = NNS->getAsNamespace()->getIdentifier();
3306 break;
3307
3308 case NestedNameSpecifier::NamespaceAlias:
3309 II = NNS->getAsNamespaceAlias()->getIdentifier();
3310 break;
3311
3312 case NestedNameSpecifier::TypeSpecWithTemplate:
3313 case NestedNameSpecifier::TypeSpec:
3314 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3315 break;
3316
3317 case NestedNameSpecifier::Global:
3318 return;
3319 }
3320
3321 if (II)
3322 Identifiers.push_back(II);
3323}
3324
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003325namespace {
3326
3327class SpecifierInfo {
3328 public:
3329 DeclContext* DeclCtx;
3330 NestedNameSpecifier* NameSpecifier;
3331 unsigned EditDistance;
3332
3333 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3334 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3335};
3336
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003337typedef SmallVector<DeclContext*, 4> DeclContextList;
3338typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003339
3340class NamespaceSpecifierSet {
3341 ASTContext &Context;
3342 DeclContextList CurContextChain;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003343 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3344 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003345 bool isSorted;
3346
3347 SpecifierInfoList Specifiers;
3348 llvm::SmallSetVector<unsigned, 4> Distances;
3349 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3350
3351 /// \brief Helper for building the list of DeclContexts between the current
3352 /// context and the top of the translation unit
3353 static DeclContextList BuildContextChain(DeclContext *Start);
3354
3355 void SortNamespaces();
3356
3357 public:
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003358 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3359 CXXScopeSpec *CurScopeSpec)
Benjamin Kramerde1d6232011-07-05 09:46:31 +00003360 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003361 isSorted(true) {
3362 if (CurScopeSpec && CurScopeSpec->getScopeRep())
3363 getNestedNameSpecifierIdentifiers(CurScopeSpec->getScopeRep(),
3364 CurNameSpecifierIdentifiers);
3365 // Build the list of identifiers that would be used for an absolute
Benjamin Kramer474261a2012-06-02 10:20:41 +00003366 // (from the global context) NestedNameSpecifier referring to the current
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003367 // context.
3368 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3369 CEnd = CurContextChain.rend();
3370 C != CEnd; ++C) {
3371 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3372 CurContextIdentifiers.push_back(ND->getIdentifier());
3373 }
3374 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003375
3376 /// \brief Add the namespace to the set, computing the corresponding
3377 /// NestedNameSpecifier and its distance in the process.
3378 void AddNamespace(NamespaceDecl *ND);
3379
3380 typedef SpecifierInfoList::iterator iterator;
3381 iterator begin() {
3382 if (!isSorted) SortNamespaces();
3383 return Specifiers.begin();
3384 }
3385 iterator end() { return Specifiers.end(); }
3386};
3387
3388}
3389
3390DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003391 assert(Start && "Bulding a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003392 DeclContextList Chain;
3393 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3394 DC = DC->getLookupParent()) {
3395 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3396 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3397 !(ND && ND->isAnonymousNamespace()))
3398 Chain.push_back(DC->getPrimaryContext());
3399 }
3400 return Chain;
3401}
3402
3403void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003404 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003405 sortedDistances.append(Distances.begin(), Distances.end());
3406
3407 if (sortedDistances.size() > 1)
3408 std::sort(sortedDistances.begin(), sortedDistances.end());
3409
3410 Specifiers.clear();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003411 for (SmallVector<unsigned, 4>::iterator DI = sortedDistances.begin(),
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003412 DIEnd = sortedDistances.end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003413 DI != DIEnd; ++DI) {
3414 SpecifierInfoList &SpecList = DistanceMap[*DI];
3415 Specifiers.append(SpecList.begin(), SpecList.end());
3416 }
3417
3418 isSorted = true;
3419}
3420
3421void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003422 DeclContext *Ctx = cast<DeclContext>(ND);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003423 NestedNameSpecifier *NNS = NULL;
3424 unsigned NumSpecifiers = 0;
3425 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003426 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003427
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003428 // Eliminate common elements from the two DeclContext chains.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003429 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3430 CEnd = CurContextChain.rend();
Chandler Carruthb198e5a2011-06-28 21:43:34 +00003431 C != CEnd && !NamespaceDeclChain.empty() &&
3432 NamespaceDeclChain.back() == *C; ++C) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003433 NamespaceDeclChain.pop_back();
3434 }
3435
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003436 // Add an explicit leading '::' specifier if needed.
3437 if (NamespaceDecl *ND =
Kaelyn Uhrain618f97c2012-02-15 22:59:03 +00003438 NamespaceDeclChain.empty() ? NULL :
3439 dyn_cast_or_null<NamespaceDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003440 IdentifierInfo *Name = ND->getIdentifier();
3441 if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3442 Name) != CurContextIdentifiers.end() ||
3443 std::find(CurNameSpecifierIdentifiers.begin(),
3444 CurNameSpecifierIdentifiers.end(),
3445 Name) != CurNameSpecifierIdentifiers.end()) {
3446 NamespaceDeclChain = FullNamespaceDeclChain;
3447 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3448 }
3449 }
3450
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003451 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3452 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3453 CEnd = NamespaceDeclChain.rend();
3454 C != CEnd; ++C) {
3455 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3456 if (ND) {
3457 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3458 ++NumSpecifiers;
3459 }
3460 }
3461
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003462 // If the built NestedNameSpecifier would be replacing an existing
3463 // NestedNameSpecifier, use the number of component identifiers that
3464 // would need to be changed as the edit distance instead of the number
3465 // of components in the built NestedNameSpecifier.
3466 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3467 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3468 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3469 NumSpecifiers = llvm::ComputeEditDistance(
3470 llvm::ArrayRef<const IdentifierInfo*>(CurNameSpecifierIdentifiers),
3471 llvm::ArrayRef<const IdentifierInfo*>(NewNameSpecifierIdentifiers));
3472 }
3473
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003474 isSorted = false;
3475 Distances.insert(NumSpecifiers);
3476 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003477}
3478
Douglas Gregord507d772010-10-20 03:06:34 +00003479/// \brief Perform name lookup for a possible result for typo correction.
3480static void LookupPotentialTypoResult(Sema &SemaRef,
3481 LookupResult &Res,
3482 IdentifierInfo *Name,
3483 Scope *S, CXXScopeSpec *SS,
3484 DeclContext *MemberContext,
3485 bool EnteringContext,
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003486 bool isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00003487 Res.suppressDiagnostics();
3488 Res.clear();
3489 Res.setLookupName(Name);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003490 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00003491 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003492 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00003493 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3494 Res.addDecl(Ivar);
3495 Res.resolveKind();
3496 return;
3497 }
3498 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003499
Douglas Gregord507d772010-10-20 03:06:34 +00003500 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3501 Res.addDecl(Prop);
3502 Res.resolveKind();
3503 return;
3504 }
3505 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003506
Douglas Gregord507d772010-10-20 03:06:34 +00003507 SemaRef.LookupQualifiedName(Res, MemberContext);
3508 return;
3509 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003510
3511 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00003512 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003513
Douglas Gregord507d772010-10-20 03:06:34 +00003514 // Fake ivar lookup; this should really be part of
3515 // LookupParsedName.
3516 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3517 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003518 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00003519 (Res.isSingleResult() &&
3520 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003521 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00003522 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3523 Res.addDecl(IV);
3524 Res.resolveKind();
3525 }
3526 }
3527 }
3528}
3529
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003530/// \brief Add keywords to the consumer as possible typo corrections.
3531static void AddKeywordsToConsumer(Sema &SemaRef,
3532 TypoCorrectionConsumer &Consumer,
Richard Smithb3a1df02012-06-08 21:35:42 +00003533 Scope *S, CorrectionCandidateCallback &CCC,
3534 bool AfterNestedNameSpecifier) {
3535 if (AfterNestedNameSpecifier) {
3536 // For 'X::', we know exactly which keywords can appear next.
3537 Consumer.addKeywordResult("template");
3538 if (CCC.WantExpressionKeywords)
3539 Consumer.addKeywordResult("operator");
3540 return;
3541 }
3542
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003543 if (CCC.WantObjCSuper)
3544 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003545
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003546 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003547 // Add type-specifier keywords to the set of results.
3548 const char *CTypeSpecs[] = {
3549 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00003550 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003551 "_Complex", "_Imaginary",
3552 // storage-specifiers as well
3553 "extern", "inline", "static", "typedef"
3554 };
3555
3556 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3557 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3558 Consumer.addKeywordResult(CTypeSpecs[I]);
3559
David Blaikiebbafb8a2012-03-11 07:00:24 +00003560 if (SemaRef.getLangOpts().C99)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003561 Consumer.addKeywordResult("restrict");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003562 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003563 Consumer.addKeywordResult("bool");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003564 else if (SemaRef.getLangOpts().C99)
Douglas Gregor3b22a882011-07-01 21:27:45 +00003565 Consumer.addKeywordResult("_Bool");
3566
David Blaikiebbafb8a2012-03-11 07:00:24 +00003567 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003568 Consumer.addKeywordResult("class");
3569 Consumer.addKeywordResult("typename");
3570 Consumer.addKeywordResult("wchar_t");
3571
David Blaikiebbafb8a2012-03-11 07:00:24 +00003572 if (SemaRef.getLangOpts().CPlusPlus0x) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003573 Consumer.addKeywordResult("char16_t");
3574 Consumer.addKeywordResult("char32_t");
3575 Consumer.addKeywordResult("constexpr");
3576 Consumer.addKeywordResult("decltype");
3577 Consumer.addKeywordResult("thread_local");
3578 }
3579 }
3580
David Blaikiebbafb8a2012-03-11 07:00:24 +00003581 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003582 Consumer.addKeywordResult("typeof");
3583 }
3584
David Blaikiebbafb8a2012-03-11 07:00:24 +00003585 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003586 Consumer.addKeywordResult("const_cast");
3587 Consumer.addKeywordResult("dynamic_cast");
3588 Consumer.addKeywordResult("reinterpret_cast");
3589 Consumer.addKeywordResult("static_cast");
3590 }
3591
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003592 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003593 Consumer.addKeywordResult("sizeof");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003594 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003595 Consumer.addKeywordResult("false");
3596 Consumer.addKeywordResult("true");
3597 }
3598
David Blaikiebbafb8a2012-03-11 07:00:24 +00003599 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003600 const char *CXXExprs[] = {
3601 "delete", "new", "operator", "throw", "typeid"
3602 };
3603 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3604 for (unsigned I = 0; I != NumCXXExprs; ++I)
3605 Consumer.addKeywordResult(CXXExprs[I]);
3606
3607 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3608 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3609 Consumer.addKeywordResult("this");
3610
David Blaikiebbafb8a2012-03-11 07:00:24 +00003611 if (SemaRef.getLangOpts().CPlusPlus0x) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003612 Consumer.addKeywordResult("alignof");
3613 Consumer.addKeywordResult("nullptr");
3614 }
3615 }
Jordan Rose58d54722012-06-30 21:33:57 +00003616
3617 if (SemaRef.getLangOpts().C11) {
3618 // FIXME: We should not suggest _Alignof if the alignof macro
3619 // is present.
3620 Consumer.addKeywordResult("_Alignof");
3621 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003622 }
3623
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003624 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003625 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3626 // Statements.
3627 const char *CStmts[] = {
3628 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3629 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3630 for (unsigned I = 0; I != NumCStmts; ++I)
3631 Consumer.addKeywordResult(CStmts[I]);
3632
David Blaikiebbafb8a2012-03-11 07:00:24 +00003633 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003634 Consumer.addKeywordResult("catch");
3635 Consumer.addKeywordResult("try");
3636 }
3637
3638 if (S && S->getBreakParent())
3639 Consumer.addKeywordResult("break");
3640
3641 if (S && S->getContinueParent())
3642 Consumer.addKeywordResult("continue");
3643
3644 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3645 Consumer.addKeywordResult("case");
3646 Consumer.addKeywordResult("default");
3647 }
3648 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003649 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003650 Consumer.addKeywordResult("namespace");
3651 Consumer.addKeywordResult("template");
3652 }
3653
3654 if (S && S->isClassScope()) {
3655 Consumer.addKeywordResult("explicit");
3656 Consumer.addKeywordResult("friend");
3657 Consumer.addKeywordResult("mutable");
3658 Consumer.addKeywordResult("private");
3659 Consumer.addKeywordResult("protected");
3660 Consumer.addKeywordResult("public");
3661 Consumer.addKeywordResult("virtual");
3662 }
3663 }
3664
David Blaikiebbafb8a2012-03-11 07:00:24 +00003665 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003666 Consumer.addKeywordResult("using");
3667
David Blaikiebbafb8a2012-03-11 07:00:24 +00003668 if (SemaRef.getLangOpts().CPlusPlus0x)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003669 Consumer.addKeywordResult("static_assert");
3670 }
3671 }
3672}
3673
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003674static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3675 TypoCorrection &Candidate) {
3676 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3677 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3678}
3679
Douglas Gregor2d435302009-12-30 17:04:44 +00003680/// \brief Try to "correct" a typo in the source code by finding
3681/// visible declarations whose names are similar to the name that was
3682/// present in the source code.
3683///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003684/// \param TypoName the \c DeclarationNameInfo structure that contains
3685/// the name that was present in the source code along with its location.
3686///
3687/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00003688///
3689/// \param S the scope in which name lookup occurs.
3690///
3691/// \param SS the nested-name-specifier that precedes the name we're
3692/// looking for, if present.
3693///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003694/// \param CCC A CorrectionCandidateCallback object that provides further
3695/// validation of typo correction candidates. It also provides flags for
3696/// determining the set of keywords permitted.
3697///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003698/// \param MemberContext if non-NULL, the context in which to look for
3699/// a member access expression.
3700///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003701/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00003702/// the nested-name-specifier SS.
3703///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003704/// \param OPT when non-NULL, the search for visible declarations will
3705/// also walk the protocols in the qualified interfaces of \p OPT.
3706///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003707/// \returns a \c TypoCorrection containing the corrected name if the typo
3708/// along with information such as the \c NamedDecl where the corrected name
3709/// was declared, and any additional \c NestedNameSpecifier needed to access
3710/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3711TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3712 Sema::LookupNameKind LookupKind,
3713 Scope *S, CXXScopeSpec *SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00003714 CorrectionCandidateCallback &CCC,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003715 DeclContext *MemberContext,
3716 bool EnteringContext,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003717 const ObjCObjectPointerType *OPT) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003718 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003719 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003720
Francois Pichet9c391132011-12-03 15:55:29 +00003721 // In Microsoft mode, don't perform typo correction in a template member
3722 // function dependent context because it interferes with the "lookup into
3723 // dependent bases of class templates" feature.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003724 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichet9c391132011-12-03 15:55:29 +00003725 isa<CXXMethodDecl>(CurContext))
3726 return TypoCorrection();
3727
Douglas Gregor2d435302009-12-30 17:04:44 +00003728 // We only attempt to correct typos for identifiers.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003729 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor2d435302009-12-30 17:04:44 +00003730 if (!Typo)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003731 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00003732
3733 // If the scope specifier itself was invalid, don't try to correct
3734 // typos.
3735 if (SS && SS->isInvalid())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003736 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00003737
3738 // Never try to correct typos during template deduction or
3739 // instantiation.
3740 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003741 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003742
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003743 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003744
3745 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003746
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003747 // If a callback object considers an empty typo correction candidate to be
3748 // viable, assume it does not do any actual validation of the candidates.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003749 TypoCorrection EmptyCorrection;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003750 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003751
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003752 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor87074f12010-10-20 01:32:02 +00003753 bool IsUnqualifiedLookup = false;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003754 DeclContext *QualifiedDC = MemberContext;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003755 if (MemberContext) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003756 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003757
3758 // Look in qualified interfaces.
3759 if (OPT) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003760 for (ObjCObjectPointerType::qual_iterator
3761 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003762 I != E; ++I)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003763 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003764 }
3765 } else if (SS && SS->isSet()) {
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003766 QualifiedDC = computeDeclContext(*SS, EnteringContext);
3767 if (!QualifiedDC)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003768 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003769
Douglas Gregor87074f12010-10-20 01:32:02 +00003770 // Provide a stop gap for files that are just seriously broken. Trying
3771 // to correct all typos can turn into a HUGE performance penalty, causing
3772 // some files to take minutes to get rejected by the parser.
3773 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003774 return TypoCorrection();
Douglas Gregor87074f12010-10-20 01:32:02 +00003775 ++TyposCorrected;
3776
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003777 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
Douglas Gregor2d435302009-12-30 17:04:44 +00003778 } else {
Douglas Gregor87074f12010-10-20 01:32:02 +00003779 IsUnqualifiedLookup = true;
3780 UnqualifiedTyposCorrectedMap::iterator Cached
3781 = UnqualifiedTyposCorrected.find(Typo);
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003782 if (Cached != UnqualifiedTyposCorrected.end()) {
3783 // Add the cached value, unless it's a keyword or fails validation. In the
3784 // keyword case, we'll end up adding the keyword below.
3785 if (Cached->second) {
3786 if (!Cached->second.isKeyword() &&
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003787 isCandidateViable(CCC, Cached->second))
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003788 Consumer.addCorrection(Cached->second);
3789 } else {
3790 // Only honor no-correction cache hits when a callback that will validate
3791 // correction candidates is not being used.
3792 if (!ValidatingCallback)
3793 return TypoCorrection();
3794 }
3795 }
3796 if (Cached == UnqualifiedTyposCorrected.end()) {
Douglas Gregor87074f12010-10-20 01:32:02 +00003797 // Provide a stop gap for files that are just seriously broken. Trying
3798 // to correct all typos can turn into a HUGE performance penalty, causing
3799 // some files to take minutes to get rejected by the parser.
3800 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003801 return TypoCorrection();
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003802 }
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003803 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003804
Douglas Gregorb11f9452012-03-26 16:54:18 +00003805 // Determine whether we are going to search in the various namespaces for
3806 // corrections.
3807 bool SearchNamespaces
Kaelyn Uhrainf4657d52012-04-03 18:20:11 +00003808 = getLangOpts().CPlusPlus &&
Douglas Gregorb11f9452012-03-26 16:54:18 +00003809 (IsUnqualifiedLookup || (QualifiedDC && QualifiedDC->isNamespace()));
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00003810 // In a few cases we *only* want to search for corrections bases on just
3811 // adding or changing the nested name specifier.
3812 bool AllowOnlyNNSChanges = Typo->getName().size() < 3;
Douglas Gregorb11f9452012-03-26 16:54:18 +00003813
3814 if (IsUnqualifiedLookup || SearchNamespaces) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003815 // For unqualified lookup, look through all of the names that we have
3816 // seen in this translation unit.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003817 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003818 for (IdentifierTable::iterator I = Context.Idents.begin(),
3819 IEnd = Context.Idents.end();
3820 I != IEnd; ++I)
3821 Consumer.FoundName(I->getKey());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003822
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003823 // Walk through identifiers in external identifier sources.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003824 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003825 if (IdentifierInfoLookup *External
3826 = Context.Idents.getExternalIdentifierLookup()) {
Dylan Noblesmithe2778992012-02-05 02:12:40 +00003827 OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003828 do {
3829 StringRef Name = Iter->Next();
3830 if (Name.empty())
3831 break;
Douglas Gregor57756ea2010-10-14 22:11:03 +00003832
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003833 Consumer.FoundName(Name);
3834 } while (true);
Douglas Gregor57756ea2010-10-14 22:11:03 +00003835 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003836 }
3837
Richard Smithb3a1df02012-06-08 21:35:42 +00003838 AddKeywordsToConsumer(*this, Consumer, S, CCC, SS && SS->isNotEmpty());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003839
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003840 // If we haven't found anything, we're done.
Douglas Gregor87074f12010-10-20 01:32:02 +00003841 if (Consumer.empty()) {
3842 // If this was an unqualified lookup, note that no correction was found.
3843 if (IsUnqualifiedLookup)
3844 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003845
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003846 return TypoCorrection();
Douglas Gregor87074f12010-10-20 01:32:02 +00003847 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003848
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00003849 // Make sure the best edit distance (prior to adding any namespace qualifiers)
3850 // is not more that about a third of the length of the typo's identifier.
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003851 unsigned ED = Consumer.getBestEditDistance(true);
Douglas Gregor87074f12010-10-20 01:32:02 +00003852 if (ED > 0 && Typo->getName().size() / ED < 3) {
3853 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregoraf1daa92010-10-27 14:20:34 +00003854 if (IsUnqualifiedLookup)
Douglas Gregor87074f12010-10-20 01:32:02 +00003855 (void)UnqualifiedTyposCorrected[Typo];
3856
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003857 return TypoCorrection();
3858 }
3859
Douglas Gregorb11f9452012-03-26 16:54:18 +00003860 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
3861 // to search those namespaces.
3862 if (SearchNamespaces) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003863 // Load any externally-known namespaces.
3864 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003865 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003866 LoadedExternalKnownNamespaces = true;
3867 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
3868 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
3869 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
3870 }
3871
3872 for (llvm::DenseMap<NamespaceDecl*, bool>::iterator
3873 KNI = KnownNamespaces.begin(),
3874 KNIEnd = KnownNamespaces.end();
3875 KNI != KNIEnd; ++KNI)
3876 Namespaces.AddNamespace(KNI->first);
Douglas Gregor87074f12010-10-20 01:32:02 +00003877 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003878
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003879 // Weed out any names that could not be found by name lookup or, if a
3880 // CorrectionCandidateCallback object was provided, failed validation.
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003881 llvm::SmallVector<TypoCorrection, 16> QualifiedResults;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003882 LookupResult TmpRes(*this, TypoName, LookupKind);
3883 TmpRes.suppressDiagnostics();
3884 while (!Consumer.empty()) {
3885 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3886 unsigned ED = DI->first;
Benjamin Kramer73faad62012-04-14 08:26:28 +00003887 for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(),
3888 IEnd = DI->second.end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003889 I != IEnd; /* Increment in loop. */) {
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00003890 // If we only want nested name specifier corrections, ignore potential
3891 // corrections that have a different base identifier from the typo.
3892 if (AllowOnlyNNSChanges &&
3893 I->second.front().getCorrectionAsIdentifierInfo() != Typo) {
3894 TypoCorrectionConsumer::result_iterator Prev = I;
3895 ++I;
3896 DI->second.erase(Prev);
3897 continue;
3898 }
3899
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003900 // If the item already has been looked up or is a keyword, keep it.
3901 // If a validator callback object was given, drop the correction
3902 // unless it passes validation.
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003903 bool Viable = false;
Benjamin Kramera2dcac12012-07-27 10:21:08 +00003904 for (TypoResultList::iterator RI = I->second.begin();
3905 RI != I->second.end(); /* Increment in loop. */) {
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003906 TypoResultList::iterator Prev = RI;
3907 ++RI;
3908 if (Prev->isResolved()) {
3909 if (!isCandidateViable(CCC, *Prev))
Benjamin Kramera2dcac12012-07-27 10:21:08 +00003910 RI = I->second.erase(Prev);
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003911 else
3912 Viable = true;
3913 }
3914 }
3915 if (Viable || I->second.empty()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003916 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003917 ++I;
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003918 if (!Viable)
Benjamin Kramer73faad62012-04-14 08:26:28 +00003919 DI->second.erase(Prev);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003920 continue;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003921 }
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003922 assert(I->second.size() == 1 && "Expected a single unresolved candidate");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003923
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003924 // Perform name lookup on this name.
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003925 TypoCorrection &Candidate = I->second.front();
3926 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003927 LookupPotentialTypoResult(*this, TmpRes, Name, S, SS, MemberContext,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00003928 EnteringContext, CCC.IsObjCIvarLookup);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003929
3930 switch (TmpRes.getResultKind()) {
3931 case LookupResult::NotFound:
3932 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain5a43b462011-09-07 20:25:59 +00003933 case LookupResult::FoundUnresolvedValue:
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003934 QualifiedResults.push_back(Candidate);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003935 // We didn't find this name in our scope, or didn't like what we found;
3936 // ignore it.
3937 {
3938 TypoCorrectionConsumer::result_iterator Next = I;
3939 ++Next;
Benjamin Kramer73faad62012-04-14 08:26:28 +00003940 DI->second.erase(I);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003941 I = Next;
3942 }
3943 break;
3944
3945 case LookupResult::Ambiguous:
3946 // We don't deal with ambiguities.
3947 return TypoCorrection();
3948
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003949 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003950 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003951 // Store all of the Decls for overloaded symbols
3952 for (LookupResult::iterator TRD = TmpRes.begin(),
3953 TRDEnd = TmpRes.end();
3954 TRD != TRDEnd; ++TRD)
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003955 Candidate.addCorrectionDecl(*TRD);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003956 ++I;
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003957 if (!isCandidateViable(CCC, Candidate))
Benjamin Kramer73faad62012-04-14 08:26:28 +00003958 DI->second.erase(Prev);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003959 break;
3960 }
3961
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003962 case LookupResult::Found: {
3963 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003964 Candidate.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003965 ++I;
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003966 if (!isCandidateViable(CCC, Candidate))
Benjamin Kramer73faad62012-04-14 08:26:28 +00003967 DI->second.erase(Prev);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003968 break;
3969 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003970
3971 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003972 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003973
Benjamin Kramer73faad62012-04-14 08:26:28 +00003974 if (DI->second.empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003975 Consumer.erase(DI);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003976 else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !ED)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003977 // If there are results in the closest possible bucket, stop
3978 break;
3979
3980 // Only perform the qualified lookups for C++
Douglas Gregorb11f9452012-03-26 16:54:18 +00003981 if (SearchNamespaces) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003982 TmpRes.suppressDiagnostics();
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003983 for (llvm::SmallVector<TypoCorrection,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003984 16>::iterator QRI = QualifiedResults.begin(),
3985 QRIEnd = QualifiedResults.end();
3986 QRI != QRIEnd; ++QRI) {
3987 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
3988 NIEnd = Namespaces.end();
3989 NI != NIEnd; ++NI) {
3990 DeclContext *Ctx = NI->DeclCtx;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003991
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003992 // FIXME: Stop searching once the namespaces are too far away to create
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003993 // acceptable corrections for this identifier (since the namespaces
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003994 // are sorted in ascending order by edit distance).
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003995
3996 TmpRes.clear();
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003997 TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003998 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
3999
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004000 // Any corrections added below will be validated in subsequent
4001 // iterations of the main while() loop over the Consumer's contents.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004002 switch (TmpRes.getResultKind()) {
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004003 case LookupResult::Found: {
4004 TypoCorrection TC(*QRI);
4005 TC.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
4006 TC.setCorrectionSpecifier(NI->NameSpecifier);
4007 TC.setQualifierDistance(NI->EditDistance);
4008 Consumer.addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004009 break;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004010 }
4011 case LookupResult::FoundOverloaded: {
4012 TypoCorrection TC(*QRI);
4013 TC.setCorrectionSpecifier(NI->NameSpecifier);
4014 TC.setQualifierDistance(NI->EditDistance);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004015 for (LookupResult::iterator TRD = TmpRes.begin(),
4016 TRDEnd = TmpRes.end();
4017 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004018 TC.addCorrectionDecl(*TRD);
4019 Consumer.addCorrection(TC);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004020 break;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004021 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004022 case LookupResult::NotFound:
4023 case LookupResult::NotFoundInCurrentInstantiation:
4024 case LookupResult::Ambiguous:
Kaelyn Uhrain5a43b462011-09-07 20:25:59 +00004025 case LookupResult::FoundUnresolvedValue:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004026 break;
4027 }
4028 }
4029 }
4030 }
4031
4032 QualifiedResults.clear();
4033 }
4034
4035 // No corrections remain...
4036 if (Consumer.empty()) return TypoCorrection();
4037
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00004038 TypoResultsMap &BestResults = Consumer.getBestResults();
4039 ED = Consumer.getBestEditDistance(true);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004040
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004041 if (!AllowOnlyNNSChanges && ED > 0 && Typo->getName().size() / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004042 // If this was an unqualified lookup and we believe the callback
4043 // object wouldn't have filtered out possible corrections, note
4044 // that no correction was found.
4045 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004046 (void)UnqualifiedTyposCorrected[Typo];
4047
4048 return TypoCorrection();
4049 }
4050
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004051 // If only a single name remains, return that result.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004052 if (BestResults.size() == 1) {
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004053 const TypoResultList &CorrectionList = BestResults.begin()->second;
4054 const TypoCorrection &Result = CorrectionList.front();
4055 if (CorrectionList.size() != 1) return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004056
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00004057 // Don't correct to a keyword that's the same as the typo; the keyword
4058 // wasn't actually in scope.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004059 if (ED == 0 && Result.isKeyword()) return TypoCorrection();
4060
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004061 // Record the correction for unqualified lookup.
4062 if (IsUnqualifiedLookup)
4063 UnqualifiedTyposCorrected[Typo] = Result;
4064
4065 return Result;
4066 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004067 else if (BestResults.size() > 1
4068 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4069 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4070 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4071 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00004072 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004073 && BestResults["super"].front().isKeyword()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004074 // Prefer 'super' when we're completing in a message-receiver
4075 // context.
4076
4077 // Don't correct to a keyword that's the same as the typo; the keyword
4078 // wasn't actually in scope.
4079 if (ED == 0) return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004080
Douglas Gregor87074f12010-10-20 01:32:02 +00004081 // Record the correction for unqualified lookup.
4082 if (IsUnqualifiedLookup)
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004083 UnqualifiedTyposCorrected[Typo] = BestResults["super"].front();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004084
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004085 return BestResults["super"].front();
Douglas Gregoraf9eb592010-10-15 13:35:25 +00004086 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004087
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004088 // If this was an unqualified lookup and we believe the callback object did
4089 // not filter out possible corrections, note that no correction was found.
4090 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregor87074f12010-10-20 01:32:02 +00004091 (void)UnqualifiedTyposCorrected[Typo];
4092
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004093 return TypoCorrection();
4094}
4095
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004096void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4097 if (!CDecl) return;
4098
4099 if (isKeyword())
4100 CorrectionDecls.clear();
4101
4102 CorrectionDecls.push_back(CDecl);
4103
4104 if (!CorrectionName)
4105 CorrectionName = CDecl->getDeclName();
4106}
4107
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004108std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4109 if (CorrectionNameSpec) {
4110 std::string tmpBuffer;
4111 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4112 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
Benjamin Kramer73faad62012-04-14 08:26:28 +00004113 CorrectionName.printName(PrefixOStream);
4114 return PrefixOStream.str();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004115 }
4116
4117 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00004118}