blob: ad5b89a43abc3b725eb3a4f041d7e121042ce762 [file] [log] [blame]
Douglas Gregoreb11cd02009-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 Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Lookup.h"
Douglas Gregor7176fff2009-01-15 00:26:24 +000015#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000017#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
Nick Lewycky173a37a2012-04-03 21:44:08 +000019#include "clang/AST/DeclLookups.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregor42af25f2009-05-11 19:58:34 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000022#include "clang/AST/Expr.h"
Douglas Gregordaa439a2009-07-08 10:57:20 +000023#include "clang/AST/ExprCXX.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000025#include "clang/Basic/LangOptions.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000026#include "clang/Sema/DeclSpec.h"
27#include "clang/Sema/ExternalSemaSource.h"
28#include "clang/Sema/Overload.h"
29#include "clang/Sema/Scope.h"
30#include "clang/Sema/ScopeInfo.h"
31#include "clang/Sema/Sema.h"
32#include "clang/Sema/SemaInternal.h"
33#include "clang/Sema/TemplateDeduction.h"
34#include "clang/Sema/TypoCorrection.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000035#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000036#include "llvm/ADT/SetVector.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000037#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregore24b5752010-10-14 20:34:08 +000038#include "llvm/ADT/StringMap.h"
Chris Lattnerb5f65472011-07-18 01:54:02 +000039#include "llvm/ADT/TinyPtrVector.h"
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +000040#include "llvm/ADT/edit_distance.h"
John McCall6e247262009-10-10 05:48:19 +000041#include "llvm/Support/ErrorHandling.h"
Nick Lewycky893a6ea2012-04-03 20:26:45 +000042#include <algorithm>
43#include <iterator>
Douglas Gregore24b5752010-10-14 20:34:08 +000044#include <limits>
Douglas Gregor546be3c2009-12-30 17:04:44 +000045#include <list>
Douglas Gregord8bba9c2011-06-28 16:20:02 +000046#include <map>
Nick Lewycky893a6ea2012-04-03 20:26:45 +000047#include <set>
48#include <utility>
49#include <vector>
Douglas Gregoreb11cd02009-01-14 22:20:51 +000050
51using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000052using namespace sema;
Douglas Gregoreb11cd02009-01-14 22:20:51 +000053
John McCalld7be78a2009-11-10 07:01:13 +000054namespace {
55 class UnqualUsingEntry {
56 const DeclContext *Nominated;
57 const DeclContext *CommonAncestor;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000058
John McCalld7be78a2009-11-10 07:01:13 +000059 public:
60 UnqualUsingEntry(const DeclContext *Nominated,
61 const DeclContext *CommonAncestor)
62 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
63 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000064
John McCalld7be78a2009-11-10 07:01:13 +000065 const DeclContext *getCommonAncestor() const {
66 return CommonAncestor;
67 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000068
John McCalld7be78a2009-11-10 07:01:13 +000069 const DeclContext *getNominatedNamespace() const {
70 return Nominated;
71 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000072
John McCalld7be78a2009-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 Gregor2a3009a2009-02-03 19:21:40 +000078
John McCalld7be78a2009-11-10 07:01:13 +000079 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
80 return E.getCommonAncestor() < DC;
81 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000082
John McCalld7be78a2009-11-10 07:01:13 +000083 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
84 return DC < E.getCommonAncestor();
85 }
86 };
87 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +000088
John McCalld7be78a2009-11-10 07:01:13 +000089 /// A collection of using directives, as used by C++ unqualified
90 /// lookup.
91 class UnqualUsingDirectiveSet {
Chris Lattner5f9e2722011-07-23 10:55:15 +000092 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000093
John McCalld7be78a2009-11-10 07:01:13 +000094 ListTy list;
95 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000096
John McCalld7be78a2009-11-10 07:01:13 +000097 public:
98 UnqualUsingDirectiveSet() {}
Douglas Gregor2a3009a2009-02-03 19:21:40 +000099
John McCalld7be78a2009-11-10 07:01:13 +0000100 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000101 // C++ [namespace.udir]p1:
John McCalld7be78a2009-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 Gregor2a3009a2009-02-03 19:21:40 +0000108
John McCalld7be78a2009-11-10 07:01:13 +0000109 for (; S; S = S->getParent()) {
Nick Lewycky65daef12012-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 Smith1b7f9cb2012-03-13 03:12:56 +0000113 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
Nick Lewycky65daef12012-03-13 04:12:34 +0000114 if (Ctx && Ctx->isFileContext()) {
115 visit(Ctx, Ctx);
116 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
John McCalld7be78a2009-11-10 07:01:13 +0000117 Scope::udir_iterator I = S->using_directives_begin(),
118 End = S->using_directives_end();
John McCalld7be78a2009-11-10 07:01:13 +0000119 for (; I != End; ++I)
John McCalld226f652010-08-21 09:40:31 +0000120 visit(*I, InnermostFileDC);
John McCalld7be78a2009-11-10 07:01:13 +0000121 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000122 }
123 }
John McCalld7be78a2009-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 Lattner5f9e2722011-07-23 10:55:15 +0000155 SmallVector<DeclContext*,4> queue;
John McCalld7be78a2009-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 McCall12ea5782009-11-10 09:20:04 +0000188 Common = Common->getPrimaryContext();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000189
John McCalld7be78a2009-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 McCalld7be78a2009-11-10 07:01:13 +0000197 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000198
John McCalld7be78a2009-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 McCall12ea5782009-11-10 09:20:04 +0000204 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCalld7be78a2009-11-10 07:01:13 +0000205 UnqualUsingEntry::Comparator());
206 }
207 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000208}
209
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000210// Retrieve the set of identifier namespaces that correspond to a
211// specific kind of name lookup.
John McCall1d7c5282009-12-18 10:40:03 +0000212static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
213 bool CPlusPlus,
214 bool Redeclaration) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000215 unsigned IDNS = 0;
216 switch (NameKind) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +0000217 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000218 case Sema::LookupOrdinaryName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000219 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000220 IDNS = Decl::IDNS_Ordinary;
John McCall1d7c5282009-12-18 10:40:03 +0000221 if (CPlusPlus) {
John McCall0d6b1642010-04-23 18:46:30 +0000222 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattner337e5502011-02-18 01:27:55 +0000223 if (Redeclaration)
224 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCall1d7c5282009-12-18 10:40:03 +0000225 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000226 break;
227
John McCall76d32642010-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 Gregor2a3009a2009-02-03 19:21:40 +0000235 case Sema::LookupTagName:
John McCall0d6b1642010-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 Gregor2a3009a2009-02-03 19:21:40 +0000249 break;
Chris Lattner337e5502011-02-18 01:27:55 +0000250 case Sema::LookupLabel:
251 IDNS = Decl::IDNS_Label;
252 break;
253
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000254 case Sema::LookupMemberName:
255 IDNS = Decl::IDNS_Member;
256 if (CPlusPlus)
Mike Stump1eb44332009-09-09 15:08:12 +0000257 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000258 break;
259
260 case Sema::LookupNestedNameSpecifierName:
John McCall0d6b1642010-04-23 18:46:30 +0000261 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
262 break;
263
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000264 case Sema::LookupNamespaceName:
John McCall0d6b1642010-04-23 18:46:30 +0000265 IDNS = Decl::IDNS_Namespace;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000266 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000267
John McCall9f54ad42009-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 Gregor8fc463a2009-04-24 00:11:27 +0000273 case Sema::LookupObjCProtocolName:
274 IDNS = Decl::IDNS_ObjCProtocol;
275 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000276
Douglas Gregor8071e422010-08-15 06:18:01 +0000277 case Sema::LookupAnyName:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000278 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor8071e422010-08-15 06:18:01 +0000279 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
280 | Decl::IDNS_Type;
281 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000282 }
283 return IDNS;
284}
285
John McCall1d7c5282009-12-18 10:40:03 +0000286void LookupResult::configure() {
David Blaikie4e4d0842012-03-11 07:00:24 +0000287 IDNS = getIDNS(LookupKind, SemaRef.getLangOpts().CPlusPlus,
John McCall1d7c5282009-12-18 10:40:03 +0000288 isForRedeclaration());
Douglas Gregorb5b2ccb2010-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 Bagnara25777432010-08-11 22:01:17 +0000294 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorb5b2ccb2010-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 McCall1d7c5282009-12-18 10:40:03 +0000306}
307
Daniel Dunbarc2bd73b2012-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 McCall2a7fb272010-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 Gregorf17b58c2010-10-22 22:08:47 +0000318 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
319 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall2a7fb272010-08-25 05:32:35 +0000320 assert((Paths != NULL) == (ResultKind == Ambiguous &&
321 (Ambiguity == AmbiguousBaseSubobjectTypes ||
322 Ambiguity == AmbiguousBaseSubobjects)));
323}
John McCall2a7fb272010-08-25 05:32:35 +0000324
John McCallf36e02d2009-10-09 21:13:30 +0000325// Necessary because CXXBasePaths is not complete in Sema.h
John McCall7d384dd2009-11-18 07:57:50 +0000326void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCallf36e02d2009-10-09 21:13:30 +0000327 delete Paths;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000328}
329
Douglas Gregor55368912011-12-14 16:03:29 +0000330static NamedDecl *getVisibleDecl(NamedDecl *D);
331
332NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
333 return getVisibleDecl(D);
334}
335
John McCall7453ed42009-11-22 00:44:51 +0000336/// Resolves the result kind of this lookup.
John McCall7d384dd2009-11-18 07:57:50 +0000337void LookupResult::resolveKind() {
John McCallf36e02d2009-10-09 21:13:30 +0000338 unsigned N = Decls.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000339
John McCallf36e02d2009-10-09 21:13:30 +0000340 // Fast case: no possible ambiguity.
John McCall68263142009-11-18 22:49:29 +0000341 if (N == 0) {
John McCalldc5c7862010-01-15 21:27:01 +0000342 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall68263142009-11-18 22:49:29 +0000343 return;
344 }
345
John McCall7453ed42009-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 McCall7ba107a2009-11-18 02:36:19 +0000348 if (N == 1) {
Douglas Gregor2b147f02010-04-25 21:15:30 +0000349 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
350 if (isa<FunctionTemplateDecl>(D))
John McCall7453ed42009-11-22 00:44:51 +0000351 ResultKind = FoundOverloaded;
Douglas Gregor2b147f02010-04-25 21:15:30 +0000352 else if (isa<UnresolvedUsingValueDecl>(D))
John McCall7ba107a2009-11-18 02:36:19 +0000353 ResultKind = FoundUnresolvedValue;
354 return;
355 }
John McCallf36e02d2009-10-09 21:13:30 +0000356
John McCall6e247262009-10-10 05:48:19 +0000357 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000358 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000359
John McCallf36e02d2009-10-09 21:13:30 +0000360 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000361 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000362
John McCallf36e02d2009-10-09 21:13:30 +0000363 bool Ambiguous = false;
364 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000365 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000366
367 unsigned UniqueTagIndex = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000368
John McCallf36e02d2009-10-09 21:13:30 +0000369 unsigned I = 0;
370 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000371 NamedDecl *D = Decls[I]->getUnderlyingDecl();
372 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000373
Argyrios Kyrtzidis745af1c2013-02-22 06:58:37 +0000374 // Ignore an invalid declaration unless it's the only one left.
375 if (D->isInvalidDecl() && I < N-1) {
376 Decls[I] = Decls[--N];
377 continue;
378 }
379
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000380 // Redeclarations of types via typedef can occur both within a scope
381 // and, through using declarations and directives, across scopes. There is
382 // no ambiguity if they all refer to the same type, so unique based on the
383 // canonical type.
384 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
385 if (!TD->getDeclContext()->isRecord()) {
386 QualType T = SemaRef.Context.getTypeDeclType(TD);
387 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
388 // The type is not unique; pull something off the back and continue
389 // at this index.
390 Decls[I] = Decls[--N];
391 continue;
392 }
393 }
394 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000395
John McCall314be4e2009-11-17 07:50:12 +0000396 if (!Unique.insert(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000397 // If it's not unique, pull something off the back (and
398 // continue at this index).
399 Decls[I] = Decls[--N];
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000400 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000401 }
402
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000403 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000404
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000405 if (isa<UnresolvedUsingValueDecl>(D)) {
406 HasUnresolved = true;
407 } else if (isa<TagDecl>(D)) {
408 if (HasTag)
409 Ambiguous = true;
410 UniqueTagIndex = I;
411 HasTag = true;
412 } else if (isa<FunctionTemplateDecl>(D)) {
413 HasFunction = true;
414 HasFunctionTemplate = true;
415 } else if (isa<FunctionDecl>(D)) {
416 HasFunction = true;
417 } else {
418 if (HasNonFunction)
419 Ambiguous = true;
420 HasNonFunction = true;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000421 }
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000422 I++;
Mike Stump1eb44332009-09-09 15:08:12 +0000423 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000424
John McCallf36e02d2009-10-09 21:13:30 +0000425 // C++ [basic.scope.hiding]p2:
426 // A class name or enumeration name can be hidden by the name of
427 // an object, function, or enumerator declared in the same
428 // scope. If a class or enumeration name and an object, function,
429 // or enumerator are declared in the same scope (in any order)
430 // with the same name, the class or enumeration name is hidden
431 // wherever the object, function, or enumerator name is visible.
432 // But it's still an error if there are distinct tag types found,
433 // even if they're not visible. (ref?)
John McCallfda8e122009-12-03 00:58:24 +0000434 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregor77a1a882010-10-23 16:06:17 +0000435 (HasFunction || HasNonFunction || HasUnresolved)) {
436 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
437 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
438 Decls[UniqueTagIndex] = Decls[--N];
439 else
440 Ambiguous = true;
441 }
Anders Carlsson8b50d012009-06-26 03:37:05 +0000442
John McCallf36e02d2009-10-09 21:13:30 +0000443 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000444
John McCallfda8e122009-12-03 00:58:24 +0000445 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000446 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000447
John McCallf36e02d2009-10-09 21:13:30 +0000448 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000449 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000450 else if (HasUnresolved)
451 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000452 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000453 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000454 else
John McCalla24dc2e2009-11-17 02:14:36 +0000455 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000456}
457
John McCall7d384dd2009-11-18 07:57:50 +0000458void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall6b2accb2010-02-10 09:31:12 +0000459 CXXBasePaths::const_paths_iterator I, E;
John McCallf36e02d2009-10-09 21:13:30 +0000460 for (I = P.begin(), E = P.end(); I != E; ++I)
David Blaikie3bc93e32012-12-19 00:45:41 +0000461 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
462 DE = I->Decls.end(); DI != DE; ++DI)
John McCallf36e02d2009-10-09 21:13:30 +0000463 addDecl(*DI);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000464}
465
John McCall7d384dd2009-11-18 07:57:50 +0000466void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000467 Paths = new CXXBasePaths;
468 Paths->swap(P);
469 addDeclsFromBasePaths(*Paths);
470 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000471 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000472}
473
John McCall7d384dd2009-11-18 07:57:50 +0000474void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000475 Paths = new CXXBasePaths;
476 Paths->swap(P);
477 addDeclsFromBasePaths(*Paths);
478 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000479 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000480}
481
Chris Lattner5f9e2722011-07-23 10:55:15 +0000482void LookupResult::print(raw_ostream &Out) {
John McCallf36e02d2009-10-09 21:13:30 +0000483 Out << Decls.size() << " result(s)";
484 if (isAmbiguous()) Out << ", ambiguous";
485 if (Paths) Out << ", base paths present";
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000486
John McCallf36e02d2009-10-09 21:13:30 +0000487 for (iterator I = begin(), E = end(); I != E; ++I) {
488 Out << "\n";
489 (*I)->print(Out, 2);
490 }
491}
492
Douglas Gregor85910982010-02-12 05:48:04 +0000493/// \brief Lookup a builtin function, when name lookup would otherwise
494/// fail.
495static bool LookupBuiltin(Sema &S, LookupResult &R) {
496 Sema::LookupNameKind NameKind = R.getLookupKind();
497
498 // If we didn't find a use of this identifier, and if the identifier
499 // corresponds to a compiler builtin, create the decl object for the builtin
500 // now, injecting it into translation unit scope, and return it.
501 if (NameKind == Sema::LookupOrdinaryName ||
502 NameKind == Sema::LookupRedeclarationWithLinkage) {
503 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
504 if (II) {
505 // If this is a builtin on this (or all) targets, create the decl.
506 if (unsigned BuiltinID = II->getBuiltinID()) {
507 // In C++, we don't have any predefined library functions like
508 // 'malloc'. Instead, we'll just error.
David Blaikie4e4d0842012-03-11 07:00:24 +0000509 if (S.getLangOpts().CPlusPlus &&
Douglas Gregor85910982010-02-12 05:48:04 +0000510 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
511 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000512
513 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
514 BuiltinID, S.TUScope,
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000515 R.isForRedeclaration(),
516 R.getNameLoc())) {
Douglas Gregor85910982010-02-12 05:48:04 +0000517 R.addDecl(D);
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000518 return true;
519 }
520
521 if (R.isForRedeclaration()) {
522 // If we're redeclaring this function anyway, forget that
523 // this was a builtin at all.
524 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
525 }
526
527 return false;
Douglas Gregor85910982010-02-12 05:48:04 +0000528 }
529 }
530 }
531
532 return false;
533}
534
Douglas Gregor4923aa22010-07-02 20:37:36 +0000535/// \brief Determine whether we can declare a special member function within
536/// the class at this point.
Richard Smithd0adeb62012-11-27 21:20:31 +0000537static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor4923aa22010-07-02 20:37:36 +0000538 // We need to have a definition for the class.
539 if (!Class->getDefinition() || Class->isDependentContext())
540 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000541
Douglas Gregor4923aa22010-07-02 20:37:36 +0000542 // We can't be in the middle of defining the class.
Richard Smithd0adeb62012-11-27 21:20:31 +0000543 return !Class->isBeingDefined();
Douglas Gregor4923aa22010-07-02 20:37:36 +0000544}
545
546void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smithd0adeb62012-11-27 21:20:31 +0000547 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregor22584312010-07-02 23:41:54 +0000548 return;
Douglas Gregor18274032010-07-03 00:47:00 +0000549
550 // If the default constructor has not yet been declared, do so now.
Sean Huntcdee3fe2011-05-11 22:34:38 +0000551 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +0000552 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000553
Douglas Gregor22584312010-07-02 23:41:54 +0000554 // If the copy constructor has not yet been declared, do so now.
Richard Smithe5411b72012-12-01 02:35:44 +0000555 if (Class->needsImplicitCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +0000556 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000557
Douglas Gregora376d102010-07-02 21:50:04 +0000558 // If the copy assignment operator has not yet been declared, do so now.
Richard Smithe5411b72012-12-01 02:35:44 +0000559 if (Class->needsImplicitCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +0000560 DeclareImplicitCopyAssignment(Class);
561
Richard Smith80ad52f2013-01-02 11:42:31 +0000562 if (getLangOpts().CPlusPlus11) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000563 // If the move constructor has not yet been declared, do so now.
564 if (Class->needsImplicitMoveConstructor())
565 DeclareImplicitMoveConstructor(Class); // might not actually do it
566
567 // If the move assignment operator has not yet been declared, do so now.
568 if (Class->needsImplicitMoveAssignment())
569 DeclareImplicitMoveAssignment(Class); // might not actually do it
570 }
571
Douglas Gregor4923aa22010-07-02 20:37:36 +0000572 // If the destructor has not yet been declared, do so now.
Richard Smithe5411b72012-12-01 02:35:44 +0000573 if (Class->needsImplicitDestructor())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000574 DeclareImplicitDestructor(Class);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000575}
576
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000577/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregora376d102010-07-02 21:50:04 +0000578/// special member function.
579static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
580 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000581 case DeclarationName::CXXConstructorName:
Douglas Gregora376d102010-07-02 21:50:04 +0000582 case DeclarationName::CXXDestructorName:
583 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000584
Douglas Gregora376d102010-07-02 21:50:04 +0000585 case DeclarationName::CXXOperatorName:
586 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000587
Douglas Gregora376d102010-07-02 21:50:04 +0000588 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000589 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000590 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000591
Douglas Gregora376d102010-07-02 21:50:04 +0000592 return false;
593}
594
595/// \brief If there are any implicit member functions with the given name
596/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000597static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregora376d102010-07-02 21:50:04 +0000598 DeclarationName Name,
599 const DeclContext *DC) {
600 if (!DC)
601 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000602
Douglas Gregora376d102010-07-02 21:50:04 +0000603 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000604 case DeclarationName::CXXConstructorName:
605 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smithd0adeb62012-11-27 21:20:31 +0000606 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000607 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Sean Huntcdee3fe2011-05-11 22:34:38 +0000608 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000609 S.DeclareImplicitDefaultConstructor(Class);
Richard Smithe5411b72012-12-01 02:35:44 +0000610 if (Record->needsImplicitCopyConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000611 S.DeclareImplicitCopyConstructor(Class);
Richard Smith80ad52f2013-01-02 11:42:31 +0000612 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000613 Record->needsImplicitMoveConstructor())
614 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +0000615 }
Douglas Gregor22584312010-07-02 23:41:54 +0000616 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000617
Douglas Gregora376d102010-07-02 21:50:04 +0000618 case DeclarationName::CXXDestructorName:
619 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smithe5411b72012-12-01 02:35:44 +0000620 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smithd0adeb62012-11-27 21:20:31 +0000621 CanDeclareSpecialMemberFunction(Record))
Douglas Gregora376d102010-07-02 21:50:04 +0000622 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregora376d102010-07-02 21:50:04 +0000623 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000624
Douglas Gregora376d102010-07-02 21:50:04 +0000625 case DeclarationName::CXXOperatorName:
626 if (Name.getCXXOverloadedOperator() != OO_Equal)
627 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000628
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000629 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smithd0adeb62012-11-27 21:20:31 +0000630 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000631 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smithe5411b72012-12-01 02:35:44 +0000632 if (Record->needsImplicitCopyAssignment())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000633 S.DeclareImplicitCopyAssignment(Class);
Richard Smith80ad52f2013-01-02 11:42:31 +0000634 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000635 Record->needsImplicitMoveAssignment())
636 S.DeclareImplicitMoveAssignment(Class);
637 }
638 }
Douglas Gregora376d102010-07-02 21:50:04 +0000639 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000640
Douglas Gregora376d102010-07-02 21:50:04 +0000641 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000642 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000643 }
644}
Douglas Gregor4923aa22010-07-02 20:37:36 +0000645
John McCallf36e02d2009-10-09 21:13:30 +0000646// Adds all qualifying matches for a name within a decl context to the
647// given lookup result. Returns true if any matches were found.
Douglas Gregor85910982010-02-12 05:48:04 +0000648static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000649 bool Found = false;
650
Douglas Gregor4923aa22010-07-02 20:37:36 +0000651 // Lazily declare C++ special member functions.
David Blaikie4e4d0842012-03-11 07:00:24 +0000652 if (S.getLangOpts().CPlusPlus)
Douglas Gregora376d102010-07-02 21:50:04 +0000653 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000654
Douglas Gregor4923aa22010-07-02 20:37:36 +0000655 // Perform lookup into this declaration context.
David Blaikie3bc93e32012-12-19 00:45:41 +0000656 DeclContext::lookup_const_result DR = DC->lookup(R.getLookupName());
657 for (DeclContext::lookup_const_iterator I = DR.begin(), E = DR.end(); I != E;
658 ++I) {
John McCall46460a62010-01-20 21:53:11 +0000659 NamedDecl *D = *I;
Douglas Gregor55368912011-12-14 16:03:29 +0000660 if ((D = R.getAcceptableDecl(D))) {
John McCall46460a62010-01-20 21:53:11 +0000661 R.addDecl(D);
Douglas Gregor48026d22010-01-11 18:40:55 +0000662 Found = true;
663 }
664 }
John McCallf36e02d2009-10-09 21:13:30 +0000665
Douglas Gregor85910982010-02-12 05:48:04 +0000666 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
667 return true;
668
Douglas Gregor48026d22010-01-11 18:40:55 +0000669 if (R.getLookupName().getNameKind()
Chandler Carruthaaa1a892010-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 Takumidfbb02a2011-01-27 07:10:08 +0000676 // A specialization of a conversion function template is not found by
Chandler Carruthaaa1a892010-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 McCall5e1cdac2011-10-07 06:10:15 +0000680 if (!Record->isCompleteDefinition())
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000681 return Found;
682
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +0000683 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
684 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000685 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
686 if (!ConvTemplate)
687 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000688
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000689 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000690 // add the conversion function template. When we deduce template
691 // arguments for specializations, we'll end up unifying the return
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000692 // type of the new declaration with the type of the function template.
693 if (R.isForRedeclaration()) {
694 R.addDecl(ConvTemplate);
695 Found = true;
696 continue;
697 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000698
Douglas Gregor48026d22010-01-11 18:40:55 +0000699 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000700 // [...] For each such operator, if argument deduction succeeds
701 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000702 // name lookup.
703 //
704 // When referencing a conversion function for any purpose other than
705 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000706 // result), perform template argument deduction and place the
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000707 // specialization into the result set. We do this to avoid forcing all
708 // callers to perform special deduction for conversion functions.
Craig Topper93e45992012-09-19 02:26:47 +0000709 TemplateDeductionInfo Info(R.getNameLoc());
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000710 FunctionDecl *Specialization = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000711
712 const FunctionProtoType *ConvProto
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000713 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
714 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3f477a12010-01-12 01:17:50 +0000715
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000716 // Compute the type of the function that we would expect the conversion
717 // function to have, if it were to match the name given.
718 // FIXME: Calling convention!
John McCalle23cf432010-12-14 08:05:40 +0000719 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
720 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
Sebastian Redl8b5b4092011-03-06 10:52:04 +0000721 EPI.ExceptionSpecType = EST_None;
John McCalle23cf432010-12-14 08:05:40 +0000722 EPI.NumExceptions = 0;
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000723 QualType ExpectedType
724 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
Jordan Rosebea522f2013-03-08 21:51:21 +0000725 ArrayRef<QualType>(), EPI);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000726
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000727 // Perform template argument deduction against the type that we would
728 // expect the function to have.
729 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
730 Specialization, Info)
731 == Sema::TDK_Success) {
732 R.addDecl(Specialization);
733 Found = true;
Douglas Gregor48026d22010-01-11 18:40:55 +0000734 }
735 }
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000736
John McCallf36e02d2009-10-09 21:13:30 +0000737 return Found;
738}
739
John McCalld7be78a2009-11-10 07:01:13 +0000740// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000741static bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000742CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregor85910982010-02-12 05:48:04 +0000743 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000744
745 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
746
John McCalld7be78a2009-11-10 07:01:13 +0000747 // Perform direct name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +0000748 bool Found = LookupDirect(S, R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000749
John McCalld7be78a2009-11-10 07:01:13 +0000750 // Perform direct name lookup into the namespaces nominated by the
751 // using directives whose common ancestor is this namespace.
752 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
753 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000754
John McCalld7be78a2009-11-10 07:01:13 +0000755 for (; UI != UEnd; ++UI)
Douglas Gregor85910982010-02-12 05:48:04 +0000756 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000757 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000758
759 R.resolveKind();
760
761 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000762}
763
764static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000765 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000766 return Ctx->isFileContext();
767 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000768}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000769
Douglas Gregor711be1e2010-03-15 14:33:29 +0000770// Find the next outer declaration context from this scope. This
771// routine actually returns the semantic outer context, which may
772// differ from the lexical context (encoded directly in the Scope
773// stack) when we are parsing a member of a class template. In this
774// case, the second element of the pair will be true, to indicate that
775// name lookup should continue searching in this semantic context when
776// it leaves the current template parameter scope.
777static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
778 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
779 DeclContext *Lexical = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000780 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor711be1e2010-03-15 14:33:29 +0000781 OuterS = OuterS->getParent()) {
782 if (OuterS->getEntity()) {
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000783 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor711be1e2010-03-15 14:33:29 +0000784 break;
785 }
786 }
787
788 // C++ [temp.local]p8:
789 // In the definition of a member of a class template that appears
790 // outside of the namespace containing the class template
791 // definition, the name of a template-parameter hides the name of
792 // a member of this namespace.
793 //
794 // Example:
795 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000796 // namespace N {
797 // class C { };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000798 //
799 // template<class T> class B {
800 // void f(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000801 // };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000802 // }
803 //
804 // template<class C> void N::B<C>::f(C) {
805 // C b; // C is the template parameter, not N::C
806 // }
807 //
808 // In this example, the lexical context we return is the
809 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000810 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor711be1e2010-03-15 14:33:29 +0000811 !S->getParent()->isTemplateParamScope())
812 return std::make_pair(Lexical, false);
813
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000814 // Find the outermost template parameter scope.
Douglas Gregor711be1e2010-03-15 14:33:29 +0000815 // For the example, this is the scope for the template parameters of
816 // template<class C>.
817 Scope *OutermostTemplateScope = S->getParent();
818 while (OutermostTemplateScope->getParent() &&
819 OutermostTemplateScope->getParent()->isTemplateParamScope())
820 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000821
Douglas Gregor711be1e2010-03-15 14:33:29 +0000822 // Find the namespace context in which the original scope occurs. In
823 // the example, this is namespace N.
824 DeclContext *Semantic = DC;
825 while (!Semantic->isFileContext())
826 Semantic = Semantic->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000827
Douglas Gregor711be1e2010-03-15 14:33:29 +0000828 // Find the declaration context just outside of the template
829 // parameter scope. This is the context in which the template is
830 // being lexically declaration (a namespace context). In the
831 // example, this is the global scope.
832 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
833 Lexical->Encloses(Semantic))
834 return std::make_pair(Semantic, true);
835
836 return std::make_pair(Lexical, false);
Douglas Gregore942bbe2009-09-10 16:57:35 +0000837}
838
John McCalla24dc2e2009-11-17 02:14:36 +0000839bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000840 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000841
842 DeclarationName Name = R.getLookupName();
843
Douglas Gregora376d102010-07-02 21:50:04 +0000844 // If this is the name of an implicitly-declared special member function,
845 // go through the scope stack to implicitly declare
846 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
847 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
848 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
849 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
850 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000851
Douglas Gregora376d102010-07-02 21:50:04 +0000852 // Implicitly declare member functions with the name we're looking for, if in
853 // fact we are in a scope where it matters.
854
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000855 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000856 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000857 I = IdResolver.begin(Name),
858 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000859
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000860 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000861 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000862 // ...During unqualified name lookup (3.4.1), the names appear as if
863 // they were declared in the nearest enclosing namespace which contains
864 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000865 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000866 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000867 //
868 // For example:
869 // namespace A { int i; }
870 // void foo() {
871 // int i;
872 // {
873 // using namespace A;
874 // ++i; // finds local 'i', A::i appears at global scope
875 // }
876 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000877 //
Douglas Gregor711be1e2010-03-15 14:33:29 +0000878 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000879 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregord2235f62010-05-20 20:58:56 +0000880 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
881
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000882 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000883 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000884 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor55368912011-12-14 16:03:29 +0000885 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
John McCallf36e02d2009-10-09 21:13:30 +0000886 Found = true;
Douglas Gregor55368912011-12-14 16:03:29 +0000887 R.addDecl(ND);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000888 }
889 }
John McCallf36e02d2009-10-09 21:13:30 +0000890 if (Found) {
891 R.resolveKind();
Douglas Gregord2235f62010-05-20 20:58:56 +0000892 if (S->isClassScope())
893 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
894 R.setNamingClass(Record);
John McCallf36e02d2009-10-09 21:13:30 +0000895 return true;
896 }
897
Douglas Gregor711be1e2010-03-15 14:33:29 +0000898 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
899 S->getParent() && !S->getParent()->isTemplateParamScope()) {
900 // We've just searched the last template parameter scope and
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +0000901 // found nothing, so look into the contexts between the
Douglas Gregor711be1e2010-03-15 14:33:29 +0000902 // lexical and semantic declaration contexts returned by
903 // findOuterContext(). This implements the name lookup behavior
904 // of C++ [temp.local]p8.
905 Ctx = OutsideOfTemplateParamDC;
906 OutsideOfTemplateParamDC = 0;
907 }
908
909 if (Ctx) {
910 DeclContext *OuterCtx;
911 bool SearchAfterTemplateScope;
912 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
913 if (SearchAfterTemplateScope)
914 OutsideOfTemplateParamDC = OuterCtx;
915
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000916 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-02-19 16:08:35 +0000917 // We do not directly look into transparent contexts, since
918 // those entities will be found in the nearest enclosing
919 // non-transparent context.
920 if (Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000921 continue;
Douglas Gregor36262b82010-02-19 16:08:35 +0000922
923 // We do not look directly into function or method contexts,
924 // since all of the local variables and parameters of the
925 // function/method are present within the Scope.
926 if (Ctx->isFunctionOrMethod()) {
927 // If we have an Objective-C instance method, look for ivars
928 // in the corresponding interface.
929 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
930 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
931 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
932 ObjCInterfaceDecl *ClassDeclared;
933 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000934 Name.getAsIdentifierInfo(),
Douglas Gregor36262b82010-02-19 16:08:35 +0000935 ClassDeclared)) {
Douglas Gregor55368912011-12-14 16:03:29 +0000936 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
937 R.addDecl(ND);
Douglas Gregor36262b82010-02-19 16:08:35 +0000938 R.resolveKind();
939 return true;
940 }
941 }
942 }
943 }
944
945 continue;
946 }
947
Douglas Gregore942bbe2009-09-10 16:57:35 +0000948 // Perform qualified name lookup into this context.
949 // FIXME: In some cases, we know that every name that could be found by
950 // this qualified name lookup will also be on the identifier chain. For
951 // example, inside a class without any base classes, we never need to
952 // perform qualified lookup because all of the members are on top of the
953 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000954 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +0000955 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +0000956 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000957 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000958 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000959
John McCalld7be78a2009-11-10 07:01:13 +0000960 // Stop if we ran out of scopes.
961 // FIXME: This really, really shouldn't be happening.
962 if (!S) return false;
963
Argyrios Kyrtzidis78f59112010-10-29 16:12:50 +0000964 // If we are looking for members, no need to look into global/namespace scope.
965 if (R.getLookupKind() == LookupMemberName)
966 return false;
967
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000968 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000969 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +0000970 //
Mike Stump390b4cc2009-05-16 07:39:55 +0000971 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
972 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000973
John McCalld7be78a2009-11-10 07:01:13 +0000974 UnqualUsingDirectiveSet UDirs;
975 UDirs.visitScopeChain(Initial, S);
976 UDirs.done();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000977
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000978 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000979 // Unqualified name lookup in C++ requires looking into scopes
980 // that aren't strictly lexical, and therefore we walk through the
981 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000982
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000983 for (; S; S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000984 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000985 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000986 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor55368912011-12-14 16:03:29 +0000987 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000988 // We found something. Look for anything else in our scope
989 // with this same name and in an acceptable identifier
990 // namespace, so that we can construct an overload set if we
991 // need to.
John McCallf36e02d2009-10-09 21:13:30 +0000992 Found = true;
Douglas Gregor55368912011-12-14 16:03:29 +0000993 R.addDecl(ND);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000994 }
995 }
996
Douglas Gregor00b4b032010-05-14 04:53:42 +0000997 if (Found && S->isTemplateParamScope()) {
John McCallf36e02d2009-10-09 21:13:30 +0000998 R.resolveKind();
999 return true;
1000 }
1001
Douglas Gregor00b4b032010-05-14 04:53:42 +00001002 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1003 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1004 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1005 // We've just searched the last template parameter scope and
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00001006 // found nothing, so look into the contexts between the
Douglas Gregor00b4b032010-05-14 04:53:42 +00001007 // lexical and semantic declaration contexts returned by
1008 // findOuterContext(). This implements the name lookup behavior
1009 // of C++ [temp.local]p8.
1010 Ctx = OutsideOfTemplateParamDC;
1011 OutsideOfTemplateParamDC = 0;
1012 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001013
Douglas Gregor00b4b032010-05-14 04:53:42 +00001014 if (Ctx) {
1015 DeclContext *OuterCtx;
1016 bool SearchAfterTemplateScope;
1017 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1018 if (SearchAfterTemplateScope)
1019 OutsideOfTemplateParamDC = OuterCtx;
1020
1021 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1022 // We do not directly look into transparent contexts, since
1023 // those entities will be found in the nearest enclosing
1024 // non-transparent context.
1025 if (Ctx->isTransparentContext())
1026 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001027
Douglas Gregor00b4b032010-05-14 04:53:42 +00001028 // If we have a context, and it's not a context stashed in the
1029 // template parameter scope for an out-of-line definition, also
1030 // look into that context.
1031 if (!(Found && S && S->isTemplateParamScope())) {
1032 assert(Ctx->isFileContext() &&
1033 "We should have been looking only at file context here already.");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001034
Douglas Gregor00b4b032010-05-14 04:53:42 +00001035 // Look into context considering using-directives.
1036 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1037 Found = true;
1038 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001039
Douglas Gregor00b4b032010-05-14 04:53:42 +00001040 if (Found) {
1041 R.resolveKind();
1042 return true;
1043 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001044
Douglas Gregor00b4b032010-05-14 04:53:42 +00001045 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1046 return false;
1047 }
1048 }
1049
Douglas Gregor1df0ee92010-02-05 07:07:10 +00001050 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +00001051 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001052 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001053
John McCallf36e02d2009-10-09 21:13:30 +00001054 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001055}
1056
Douglas Gregor55368912011-12-14 16:03:29 +00001057/// \brief Retrieve the visible declaration corresponding to D, if any.
1058///
1059/// This routine determines whether the declaration D is visible in the current
1060/// module, with the current imports. If not, it checks whether any
1061/// redeclaration of D is visible, and if so, returns that declaration.
1062///
1063/// \returns D, or a visible previous declaration of D, whichever is more recent
1064/// and visible. If no declaration of D is visible, returns null.
1065static NamedDecl *getVisibleDecl(NamedDecl *D) {
1066 if (LookupResult::isVisible(D))
1067 return D;
1068
Douglas Gregor0782ef22012-01-06 22:05:37 +00001069 for (Decl::redecl_iterator RD = D->redecls_begin(), RDEnd = D->redecls_end();
1070 RD != RDEnd; ++RD) {
David Blaikie581deb32012-06-06 20:45:41 +00001071 if (NamedDecl *ND = dyn_cast<NamedDecl>(*RD)) {
Douglas Gregor0782ef22012-01-06 22:05:37 +00001072 if (LookupResult::isVisible(ND))
1073 return ND;
1074 }
Douglas Gregor55368912011-12-14 16:03:29 +00001075 }
1076
1077 return 0;
1078}
1079
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001080/// @brief Perform unqualified name lookup starting from a given
1081/// scope.
1082///
1083/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1084/// used to find names within the current scope. For example, 'x' in
1085/// @code
1086/// int x;
1087/// int f() {
1088/// return x; // unqualified name look finds 'x' in the global scope
1089/// }
1090/// @endcode
1091///
1092/// Different lookup criteria can find different names. For example, a
1093/// particular scope can have both a struct and a function of the same
1094/// name, and each can be found by certain lookup criteria. For more
1095/// information about lookup criteria, see the documentation for the
1096/// class LookupCriteria.
1097///
1098/// @param S The scope from which unqualified name lookup will
1099/// begin. If the lookup criteria permits, name lookup may also search
1100/// in the parent scopes.
1101///
James Dennett8da16872012-06-22 10:32:46 +00001102/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1103/// look up and the lookup kind), and is updated with the results of lookup
1104/// including zero or more declarations and possibly additional information
1105/// used to diagnose ambiguities.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001106///
James Dennett8da16872012-06-22 10:32:46 +00001107/// @returns \c true if lookup succeeded and false otherwise.
John McCalla24dc2e2009-11-17 02:14:36 +00001108bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1109 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +00001110 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001111
John McCalla24dc2e2009-11-17 02:14:36 +00001112 LookupNameKind NameKind = R.getLookupKind();
1113
David Blaikie4e4d0842012-03-11 07:00:24 +00001114 if (!getLangOpts().CPlusPlus) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001115 // Unqualified name lookup in C/Objective-C is purely lexical, so
1116 // search in the declarations attached to the name.
John McCall1d7c5282009-12-18 10:40:03 +00001117 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001118 // Find the nearest non-transparent declaration scope.
1119 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001120 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001121 static_cast<DeclContext *>(S->getEntity())
1122 ->isTransparentContext()))
1123 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001124 }
1125
John McCall1d7c5282009-12-18 10:40:03 +00001126 unsigned IDNS = R.getIdentifierNamespace();
1127
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001128 // Scan up the scope chain looking for a decl that matches this
1129 // identifier that is in the appropriate namespace. This search
1130 // should not take long, as shadowing of names is uncommon, and
1131 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001132 bool LeftStartingScope = false;
1133
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001134 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +00001135 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001136 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001137 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001138 if (NameKind == LookupRedeclarationWithLinkage) {
1139 // Determine whether this (or a previous) declaration is
1140 // out-of-scope.
John McCalld226f652010-08-21 09:40:31 +00001141 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001142 LeftStartingScope = true;
1143
1144 // If we found something outside of our starting scope that
1145 // does not have linkage, skip it.
1146 if (LeftStartingScope && !((*I)->hasLinkage()))
1147 continue;
1148 }
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001149 else if (NameKind == LookupObjCImplicitSelfParam &&
1150 !isa<ImplicitParamDecl>(*I))
1151 continue;
1152
Douglas Gregor10ce9322011-12-02 20:08:44 +00001153 // If this declaration is module-private and it came from an AST
1154 // file, we can't see it.
Douglas Gregor447af242012-01-05 01:11:47 +00001155 NamedDecl *D = R.isHiddenDeclarationVisible()? *I : getVisibleDecl(*I);
Douglas Gregor55368912011-12-14 16:03:29 +00001156 if (!D)
Douglas Gregor10ce9322011-12-02 20:08:44 +00001157 continue;
Douglas Gregor55368912011-12-14 16:03:29 +00001158
1159 R.addDecl(D);
John McCallf36e02d2009-10-09 21:13:30 +00001160
Douglas Gregor7a537402012-01-03 23:26:26 +00001161 // Check whether there are any other declarations with the same name
1162 // and in the same scope.
Douglas Gregorda795b42012-01-04 16:44:10 +00001163 if (I != IEnd) {
Douglas Gregor117c4562012-01-13 23:06:53 +00001164 // Find the scope in which this declaration was declared (if it
1165 // actually exists in a Scope).
1166 while (S && !S->isDeclScope(D))
1167 S = S->getParent();
1168
1169 // If the scope containing the declaration is the translation unit,
1170 // then we'll need to perform our checks based on the matching
1171 // DeclContexts rather than matching scopes.
1172 if (S && isNamespaceOrTranslationUnitScope(S))
1173 S = 0;
1174
1175 // Compute the DeclContext, if we need it.
1176 DeclContext *DC = 0;
1177 if (!S)
1178 DC = (*I)->getDeclContext()->getRedeclContext();
1179
Douglas Gregorda795b42012-01-04 16:44:10 +00001180 IdentifierResolver::iterator LastI = I;
1181 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor117c4562012-01-13 23:06:53 +00001182 if (S) {
1183 // Match based on scope.
1184 if (!S->isDeclScope(*LastI))
1185 break;
1186 } else {
1187 // Match based on DeclContext.
1188 DeclContext *LastDC
1189 = (*LastI)->getDeclContext()->getRedeclContext();
1190 if (!LastDC->Equals(DC))
1191 break;
1192 }
1193
1194 // If the declaration isn't in the right namespace, skip it.
Douglas Gregorda795b42012-01-04 16:44:10 +00001195 if (!(*LastI)->isInIdentifierNamespace(IDNS))
1196 continue;
Douglas Gregor117c4562012-01-13 23:06:53 +00001197
Douglas Gregor447af242012-01-05 01:11:47 +00001198 D = R.isHiddenDeclarationVisible()? *LastI : getVisibleDecl(*LastI);
Douglas Gregorda795b42012-01-04 16:44:10 +00001199 if (D)
1200 R.addDecl(D);
1201 }
Douglas Gregorf9201e02009-02-11 23:02:49 +00001202
Douglas Gregorda795b42012-01-04 16:44:10 +00001203 R.resolveKind();
Douglas Gregorf9201e02009-02-11 23:02:49 +00001204 }
John McCallf36e02d2009-10-09 21:13:30 +00001205 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +00001206 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001207 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001208 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +00001209 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +00001210 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001211 }
1212
1213 // If we didn't find a use of this identifier, and if the identifier
1214 // corresponds to a compiler builtin, create the decl object for the builtin
1215 // now, injecting it into translation unit scope, and return it.
Axel Naumann42151d52011-04-13 13:19:46 +00001216 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1217 return true;
Douglas Gregor3e41d602009-02-13 23:20:09 +00001218
Axel Naumannf8291a12011-02-24 16:47:47 +00001219 // If we didn't find a use of this identifier, the ExternalSource
1220 // may be able to handle the situation.
1221 // Note: some lookup failures are expected!
1222 // See e.g. R.isForRedeclaration().
1223 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001224}
1225
John McCall6e247262009-10-10 05:48:19 +00001226/// @brief Perform qualified name lookup in the namespaces nominated by
1227/// using directives by the given context.
1228///
1229/// C++98 [namespace.qual]p2:
James Dennett7ba75922012-06-19 21:05:49 +00001230/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6e247262009-10-10 05:48:19 +00001231/// (where X is the global namespace), let S be the set of all
1232/// declarations of m in X and in the transitive closure of all
1233/// namespaces nominated by using-directives in X and its used
1234/// namespaces, except that using-directives are ignored in any
1235/// namespace, including X, directly containing one or more
1236/// declarations of m. No namespace is searched more than once in
1237/// the lookup of a name. If S is the empty set, the program is
1238/// ill-formed. Otherwise, if S has exactly one member, or if the
1239/// context of the reference is a using-declaration
1240/// (namespace.udecl), S is the required set of declarations of
1241/// m. Otherwise if the use of m is not one that allows a unique
1242/// declaration to be chosen from S, the program is ill-formed.
James Dennett7ba75922012-06-19 21:05:49 +00001243///
John McCall6e247262009-10-10 05:48:19 +00001244/// C++98 [namespace.qual]p5:
1245/// During the lookup of a qualified namespace member name, if the
1246/// lookup finds more than one declaration of the member, and if one
1247/// declaration introduces a class name or enumeration name and the
1248/// other declarations either introduce the same object, the same
1249/// enumerator or a set of functions, the non-type name hides the
1250/// class or enumeration name if and only if the declarations are
1251/// from the same namespace; otherwise (the declarations are from
1252/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +00001253static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +00001254 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +00001255 assert(StartDC->isFileContext() && "start context is not a file context");
1256
1257 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1258 DeclContext::udir_iterator E = StartDC->using_directives_end();
1259
1260 if (I == E) return false;
1261
1262 // We have at least added all these contexts to the queue.
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001263 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6e247262009-10-10 05:48:19 +00001264 Visited.insert(StartDC);
1265
1266 // We have not yet looked into these namespaces, much less added
1267 // their "using-children" to the queue.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001268 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6e247262009-10-10 05:48:19 +00001269
1270 // We have already looked into the initial namespace; seed the queue
1271 // with its using-children.
1272 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001273 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001274 if (Visited.insert(ND))
John McCall6e247262009-10-10 05:48:19 +00001275 Queue.push_back(ND);
1276 }
1277
1278 // The easiest way to implement the restriction in [namespace.qual]p5
1279 // is to check whether any of the individual results found a tag
1280 // and, if so, to declare an ambiguity if the final result is not
1281 // a tag.
1282 bool FoundTag = false;
1283 bool FoundNonTag = false;
1284
John McCall7d384dd2009-11-18 07:57:50 +00001285 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001286
1287 bool Found = false;
1288 while (!Queue.empty()) {
1289 NamespaceDecl *ND = Queue.back();
1290 Queue.pop_back();
1291
1292 // We go through some convolutions here to avoid copying results
1293 // between LookupResults.
1294 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001295 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001296 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001297
1298 if (FoundDirect) {
1299 // First do any local hiding.
1300 DirectR.resolveKind();
1301
1302 // If the local result is a tag, remember that.
1303 if (DirectR.isSingleTagDecl())
1304 FoundTag = true;
1305 else
1306 FoundNonTag = true;
1307
1308 // Append the local results to the total results if necessary.
1309 if (UseLocal) {
1310 R.addAllDecls(LocalR);
1311 LocalR.clear();
1312 }
1313 }
1314
1315 // If we find names in this namespace, ignore its using directives.
1316 if (FoundDirect) {
1317 Found = true;
1318 continue;
1319 }
1320
1321 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1322 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001323 if (Visited.insert(Nom))
John McCall6e247262009-10-10 05:48:19 +00001324 Queue.push_back(Nom);
1325 }
1326 }
1327
1328 if (Found) {
1329 if (FoundTag && FoundNonTag)
1330 R.setAmbiguousQualifiedTagHiding();
1331 else
1332 R.resolveKind();
1333 }
1334
1335 return Found;
1336}
1337
Douglas Gregor8071e422010-08-15 06:18:01 +00001338/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001339static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor8071e422010-08-15 06:18:01 +00001340 CXXBasePath &Path,
1341 void *Name) {
1342 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001343
Douglas Gregor8071e422010-08-15 06:18:01 +00001344 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1345 Path.Decls = BaseRecord->lookup(N);
David Blaikie3bc93e32012-12-19 00:45:41 +00001346 return !Path.Decls.empty();
Douglas Gregor8071e422010-08-15 06:18:01 +00001347}
1348
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001349/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001350/// static members, nested types, and enumerators.
1351template<typename InputIterator>
1352static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1353 Decl *D = (*First)->getUnderlyingDecl();
1354 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1355 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001356
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001357 if (isa<CXXMethodDecl>(D)) {
1358 // Determine whether all of the methods are static.
1359 bool AllMethodsAreStatic = true;
1360 for(; First != Last; ++First) {
1361 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001362
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001363 if (!isa<CXXMethodDecl>(D)) {
1364 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1365 break;
1366 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001367
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001368 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1369 AllMethodsAreStatic = false;
1370 break;
1371 }
1372 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001373
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001374 if (AllMethodsAreStatic)
1375 return true;
1376 }
1377
1378 return false;
1379}
1380
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001381/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001382///
1383/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1384/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001385/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001386///
1387/// Different lookup criteria can find different names. For example, a
1388/// particular scope can have both a struct and a function of the same
1389/// name, and each can be found by certain lookup criteria. For more
1390/// information about lookup criteria, see the documentation for the
1391/// class LookupCriteria.
1392///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001393/// \param R captures both the lookup criteria and any lookup results found.
1394///
1395/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001396/// search. If the lookup criteria permits, name lookup may also search
1397/// in the parent contexts or (for C++ classes) base classes.
1398///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001399/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001400/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001401///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001402/// \returns true if lookup succeeded, false if it failed.
1403bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1404 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001405 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001406
John McCalla24dc2e2009-11-17 02:14:36 +00001407 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001408 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001409
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001410 // Make sure that the declaration context is complete.
1411 assert((!isa<TagDecl>(LookupCtx) ||
1412 LookupCtx->isDependentContext() ||
John McCall5e1cdac2011-10-07 06:10:15 +00001413 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith1af83c42012-03-23 03:33:32 +00001414 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001415 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001416
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001417 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001418 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001419 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001420 if (isa<CXXRecordDecl>(LookupCtx))
1421 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001422 return true;
1423 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001424
John McCall6e247262009-10-10 05:48:19 +00001425 // Don't descend into implied contexts for redeclarations.
1426 // C++98 [namespace.qual]p6:
1427 // In a declaration for a namespace member in which the
1428 // declarator-id is a qualified-id, given that the qualified-id
1429 // for the namespace member has the form
1430 // nested-name-specifier unqualified-id
1431 // the unqualified-id shall name a member of the namespace
1432 // designated by the nested-name-specifier.
1433 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001434 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001435 return false;
1436
John McCalla24dc2e2009-11-17 02:14:36 +00001437 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001438 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001439 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001440
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001441 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001442 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001443 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor025291b2010-07-01 00:21:21 +00001444 if (!LookupRec || !LookupRec->getDefinition())
John McCallf36e02d2009-10-09 21:13:30 +00001445 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001446
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001447 // If we're performing qualified name lookup into a dependent class,
1448 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001449 // dependent base classes, then we either have to delay lookup until
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001450 // template instantiation time (at which point all bases will be available)
1451 // or we have to fail.
1452 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1453 LookupRec->hasAnyDependentBases()) {
1454 R.setNotFoundInCurrentInstantiation();
1455 return false;
1456 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001457
Douglas Gregor7176fff2009-01-15 00:26:24 +00001458 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001459 CXXBasePaths Paths;
1460 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001461
1462 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001463 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001464 switch (R.getLookupKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001465 case LookupObjCImplicitSelfParam:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001466 case LookupOrdinaryName:
1467 case LookupMemberName:
1468 case LookupRedeclarationWithLinkage:
1469 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1470 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001471
Douglas Gregora8f32e02009-10-06 17:59:45 +00001472 case LookupTagName:
1473 BaseCallback = &CXXRecordDecl::FindTagMember;
1474 break;
John McCall9f54ad42009-12-10 09:41:52 +00001475
Douglas Gregor8071e422010-08-15 06:18:01 +00001476 case LookupAnyName:
1477 BaseCallback = &LookupAnyMember;
1478 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001479
John McCall9f54ad42009-12-10 09:41:52 +00001480 case LookupUsingDeclName:
1481 // This lookup is for redeclarations only.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001482
Douglas Gregora8f32e02009-10-06 17:59:45 +00001483 case LookupOperatorName:
1484 case LookupNamespaceName:
1485 case LookupObjCProtocolName:
Chris Lattner337e5502011-02-18 01:27:55 +00001486 case LookupLabel:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001487 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001488 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001489
Douglas Gregora8f32e02009-10-06 17:59:45 +00001490 case LookupNestedNameSpecifierName:
1491 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1492 break;
1493 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001494
John McCalla24dc2e2009-11-17 02:14:36 +00001495 if (!LookupRec->lookupInBases(BaseCallback,
1496 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001497 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001498
John McCall92f88312010-01-23 00:46:32 +00001499 R.setNamingClass(LookupRec);
1500
Douglas Gregor7176fff2009-01-15 00:26:24 +00001501 // C++ [class.member.lookup]p2:
1502 // [...] If the resulting set of declarations are not all from
1503 // sub-objects of the same type, or the set has a nonstatic member
1504 // and includes members from distinct sub-objects, there is an
1505 // ambiguity and the program is ill-formed. Otherwise that set is
1506 // the result of the lookup.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001507 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001508 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001509 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001510
Douglas Gregora8f32e02009-10-06 17:59:45 +00001511 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001512 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001513 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001514
John McCall46460a62010-01-20 21:53:11 +00001515 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1516 // across all paths.
1517 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001518
Douglas Gregor7176fff2009-01-15 00:26:24 +00001519 // Determine whether we're looking at a distinct sub-object or not.
1520 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001521 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001522 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1523 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001524 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001525 }
1526
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001527 if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001528 != Context.getCanonicalType(PathElement.Base->getType())) {
1529 // We found members of the given name in two subobjects of
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001530 // different types. If the declaration sets aren't the same, this
1531 // this lookup is ambiguous.
David Blaikie3bc93e32012-12-19 00:45:41 +00001532 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001533 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikie3bc93e32012-12-19 00:45:41 +00001534 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
1535 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001536
David Blaikie3bc93e32012-12-19 00:45:41 +00001537 while (FirstD != FirstPath->Decls.end() &&
1538 CurrentD != Path->Decls.end()) {
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001539 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1540 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1541 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001542
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001543 ++FirstD;
1544 ++CurrentD;
1545 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001546
David Blaikie3bc93e32012-12-19 00:45:41 +00001547 if (FirstD == FirstPath->Decls.end() &&
1548 CurrentD == Path->Decls.end())
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001549 continue;
1550 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001551
John McCallf36e02d2009-10-09 21:13:30 +00001552 R.setAmbiguousBaseSubobjectTypes(Paths);
1553 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001554 }
1555
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001556 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001557 // We have a different subobject of the same type.
1558
1559 // C++ [class.member.lookup]p5:
1560 // A static member, a nested type or an enumerator defined in
1561 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001562 // has more than one base class subobject of type T.
David Blaikie3bc93e32012-12-19 00:45:41 +00001563 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor7176fff2009-01-15 00:26:24 +00001564 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001565
Douglas Gregor7176fff2009-01-15 00:26:24 +00001566 // We have found a nonstatic member name in multiple, distinct
1567 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001568 R.setAmbiguousBaseSubobjects(Paths);
1569 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001570 }
1571 }
1572
1573 // Lookup in a base class succeeded; return these results.
1574
David Blaikie3bc93e32012-12-19 00:45:41 +00001575 DeclContext::lookup_result DR = Paths.front().Decls;
1576 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E; ++I) {
John McCall92f88312010-01-23 00:46:32 +00001577 NamedDecl *D = *I;
1578 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1579 D->getAccess());
1580 R.addDecl(D, AS);
1581 }
John McCallf36e02d2009-10-09 21:13:30 +00001582 R.resolveKind();
1583 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001584}
1585
1586/// @brief Performs name lookup for a name that was parsed in the
1587/// source code, and may contain a C++ scope specifier.
1588///
1589/// This routine is a convenience routine meant to be called from
1590/// contexts that receive a name and an optional C++ scope specifier
1591/// (e.g., "N::M::x"). It will then perform either qualified or
1592/// unqualified name lookup (with LookupQualifiedName or LookupName,
1593/// respectively) on the given name and return those results.
1594///
1595/// @param S The scope from which unqualified name lookup will
1596/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001597///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001598/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001599///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001600/// @param EnteringContext Indicates whether we are going to enter the
1601/// context of the scope-specifier SS (if present).
1602///
John McCallf36e02d2009-10-09 21:13:30 +00001603/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001604bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001605 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001606 if (SS && SS->isInvalid()) {
1607 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001608 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001609 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001610 }
Mike Stump1eb44332009-09-09 15:08:12 +00001611
Douglas Gregor495c35d2009-08-25 22:51:20 +00001612 if (SS && SS->isSet()) {
1613 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001614 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001615 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001616 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001617 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001618
John McCalla24dc2e2009-11-17 02:14:36 +00001619 R.setContextRange(SS->getRange());
John McCalla24dc2e2009-11-17 02:14:36 +00001620 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001621 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001622
Douglas Gregor495c35d2009-08-25 22:51:20 +00001623 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001624 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001625 // Name lookup can't find anything in this case.
Douglas Gregor3eafbb82011-10-24 22:24:50 +00001626 R.setNotFoundInCurrentInstantiation();
1627 R.setContextRange(SS->getRange());
John McCallf36e02d2009-10-09 21:13:30 +00001628 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001629 }
1630
Mike Stump1eb44332009-09-09 15:08:12 +00001631 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001632 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001633}
1634
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001635
James Dennett16ae9de2012-06-22 10:16:05 +00001636/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor7176fff2009-01-15 00:26:24 +00001637/// from name lookup.
1638///
James Dennett16ae9de2012-06-22 10:16:05 +00001639/// \param Result The result of the ambiguous lookup to be diagnosed.
Mike Stump1eb44332009-09-09 15:08:12 +00001640///
James Dennett16ae9de2012-06-22 10:16:05 +00001641/// \returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001642bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001643 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1644
John McCalla24dc2e2009-11-17 02:14:36 +00001645 DeclarationName Name = Result.getLookupName();
1646 SourceLocation NameLoc = Result.getNameLoc();
1647 SourceRange LookupRange = Result.getContextRange();
1648
John McCall6e247262009-10-10 05:48:19 +00001649 switch (Result.getAmbiguityKind()) {
1650 case LookupResult::AmbiguousBaseSubobjects: {
1651 CXXBasePaths *Paths = Result.getBasePaths();
1652 QualType SubobjectType = Paths->front().back().Base->getType();
1653 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1654 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1655 << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001656
David Blaikie3bc93e32012-12-19 00:45:41 +00001657 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6e247262009-10-10 05:48:19 +00001658 while (isa<CXXMethodDecl>(*Found) &&
1659 cast<CXXMethodDecl>(*Found)->isStatic())
1660 ++Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001661
John McCall6e247262009-10-10 05:48:19 +00001662 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001663
John McCall6e247262009-10-10 05:48:19 +00001664 return true;
1665 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001666
John McCall6e247262009-10-10 05:48:19 +00001667 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001668 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1669 << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001670
John McCall6e247262009-10-10 05:48:19 +00001671 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001672 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001673 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1674 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001675 Path != PathEnd; ++Path) {
David Blaikie3bc93e32012-12-19 00:45:41 +00001676 Decl *D = Path->Decls.front();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001677 if (DeclsPrinted.insert(D).second)
1678 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1679 }
1680
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001681 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001682 }
1683
John McCall6e247262009-10-10 05:48:19 +00001684 case LookupResult::AmbiguousTagHiding: {
1685 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001686
John McCall6e247262009-10-10 05:48:19 +00001687 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1688
1689 LookupResult::iterator DI, DE = Result.end();
1690 for (DI = Result.begin(); DI != DE; ++DI)
1691 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1692 TagDecls.insert(TD);
1693 Diag(TD->getLocation(), diag::note_hidden_tag);
1694 }
1695
1696 for (DI = Result.begin(); DI != DE; ++DI)
1697 if (!isa<TagDecl>(*DI))
1698 Diag((*DI)->getLocation(), diag::note_hiding_object);
1699
1700 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001701 LookupResult::Filter F = Result.makeFilter();
1702 while (F.hasNext()) {
1703 if (TagDecls.count(F.next()))
1704 F.erase();
1705 }
1706 F.done();
John McCall6e247262009-10-10 05:48:19 +00001707
1708 return true;
1709 }
1710
1711 case LookupResult::AmbiguousReference: {
1712 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001713
John McCall6e247262009-10-10 05:48:19 +00001714 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1715 for (; DI != DE; ++DI)
1716 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001717
John McCall6e247262009-10-10 05:48:19 +00001718 return true;
1719 }
1720 }
1721
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001722 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001723}
Douglas Gregorfa047642009-02-04 00:32:51 +00001724
John McCallc7e04da2010-05-28 18:45:08 +00001725namespace {
1726 struct AssociatedLookup {
John McCall42f48fb2012-08-24 20:38:34 +00001727 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallc7e04da2010-05-28 18:45:08 +00001728 Sema::AssociatedNamespaceSet &Namespaces,
1729 Sema::AssociatedClassSet &Classes)
John McCall42f48fb2012-08-24 20:38:34 +00001730 : S(S), Namespaces(Namespaces), Classes(Classes),
1731 InstantiationLoc(InstantiationLoc) {
John McCallc7e04da2010-05-28 18:45:08 +00001732 }
1733
1734 Sema &S;
1735 Sema::AssociatedNamespaceSet &Namespaces;
1736 Sema::AssociatedClassSet &Classes;
John McCall42f48fb2012-08-24 20:38:34 +00001737 SourceLocation InstantiationLoc;
John McCallc7e04da2010-05-28 18:45:08 +00001738 };
1739}
1740
Mike Stump1eb44332009-09-09 15:08:12 +00001741static void
John McCallc7e04da2010-05-28 18:45:08 +00001742addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCall6ff07852009-08-07 22:18:02 +00001743
Douglas Gregor54022952010-04-30 07:08:38 +00001744static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1745 DeclContext *Ctx) {
1746 // Add the associated namespace for this class.
1747
1748 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1749 // be a locally scoped record.
1750
Sebastian Redl410c4f22010-08-31 20:53:31 +00001751 // We skip out of inline namespaces. The innermost non-inline namespace
1752 // contains all names of all its nested inline namespaces anyway, so we can
1753 // replace the entire inline namespace tree with its root.
1754 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1755 Ctx->isInlineNamespace())
Douglas Gregor54022952010-04-30 07:08:38 +00001756 Ctx = Ctx->getParent();
1757
John McCall6ff07852009-08-07 22:18:02 +00001758 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001759 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001760}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001761
Mike Stump1eb44332009-09-09 15:08:12 +00001762// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001763// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001764static void
John McCallc7e04da2010-05-28 18:45:08 +00001765addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1766 const TemplateArgument &Arg) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001767 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001768 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001769 switch (Arg.getKind()) {
1770 case TemplateArgument::Null:
1771 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001772
Douglas Gregor69be8d62009-07-08 07:51:57 +00001773 case TemplateArgument::Type:
1774 // [...] the namespaces and classes associated with the types of the
1775 // template arguments provided for template type parameters (excluding
1776 // template template parameters)
John McCallc7e04da2010-05-28 18:45:08 +00001777 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor69be8d62009-07-08 07:51:57 +00001778 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001779
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001780 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001781 case TemplateArgument::TemplateExpansion: {
Mike Stump1eb44332009-09-09 15:08:12 +00001782 // [...] the namespaces in which any template template arguments are
1783 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001784 // template template arguments are defined.
Douglas Gregora7fc9012011-01-05 18:58:31 +00001785 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump1eb44332009-09-09 15:08:12 +00001786 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001787 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001788 DeclContext *Ctx = ClassTemplate->getDeclContext();
1789 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001790 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001791 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001792 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001793 }
1794 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001795 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001796
Douglas Gregor788cd062009-11-11 01:00:40 +00001797 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001798 case TemplateArgument::Integral:
1799 case TemplateArgument::Expression:
Eli Friedmand7a6b162012-09-26 02:36:12 +00001800 case TemplateArgument::NullPtr:
Mike Stump1eb44332009-09-09 15:08:12 +00001801 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001802 // associated namespaces. ]
1803 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001804
Douglas Gregor69be8d62009-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 McCallc7e04da2010-05-28 18:45:08 +00001809 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001810 break;
1811 }
1812}
1813
Douglas Gregorfa047642009-02-04 00:32:51 +00001814// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001815// argument-dependent lookup with an argument of class type
1816// (C++ [basic.lookup.koenig]p2).
1817static void
John McCallc7e04da2010-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 Gregorfa047642009-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 Stump1eb44332009-09-09 15:08:12 +00001831 // which its associated classes are defined.
Douglas Gregorfa047642009-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 McCallc7e04da2010-05-28 18:45:08 +00001836 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001837 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001838 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001839
Douglas Gregorfa047642009-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 McCallc7e04da2010-05-28 18:45:08 +00001842 if (!Result.Classes.insert(Class))
Douglas Gregorfa047642009-02-04 00:32:51 +00001843 return;
1844
Mike Stump1eb44332009-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 Takumi00995302011-01-27 07:09:49 +00001847 // templates, the member template's class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001848 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001849 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-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 Gregor69be8d62009-07-08 07:51:57 +00001853 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001854 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-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 McCallc7e04da2010-05-28 18:45:08 +00001858 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001859 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001860 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001861
Douglas Gregor69be8d62009-07-08 07:51:57 +00001862 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1863 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallc7e04da2010-05-28 18:45:08 +00001864 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001865 }
Mike Stump1eb44332009-09-09 15:08:12 +00001866
John McCall86ff3082010-02-04 22:26:26 +00001867 // Only recurse into base classes for complete types.
1868 if (!Class->hasDefinition()) {
John McCall42f48fb2012-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 McCall86ff3082010-02-04 22:26:26 +00001873 }
1874
Douglas Gregorfa047642009-02-04 00:32:51 +00001875 // Add direct and indirect base classes along with their associated
1876 // namespaces.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001877 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregorfa047642009-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 Kremenek6217b802009-07-29 21:53:49 +00001888 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-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 Gregorfa047642009-02-04 00:32:51 +00001897 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001898 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001899 // Find the associated namespace for this base class.
1900 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallc7e04da2010-05-28 18:45:08 +00001901 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregorfa047642009-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 Stump1eb44332009-09-09 15:08:12 +00001913// (C++ [basic.lookup.koenig]p2).
1914static void
John McCallc7e04da2010-05-28 18:45:08 +00001915addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregorfa047642009-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 Gregorfa047642009-02-04 00:32:51 +00001926
Chris Lattner5f9e2722011-07-23 10:55:15 +00001927 SmallVector<const Type *, 16> Queue;
John McCallfa4edcf2010-05-28 06:08:54 +00001928 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1929
Douglas Gregorfa047642009-02-04 00:32:51 +00001930 while (true) {
John McCallfa4edcf2010-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 Gregorfa047642009-02-04 00:32:51 +00001944 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00001945
John McCallfa4edcf2010-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 Gregorfa047642009-02-04 00:32:51 +00001956
John McCallfa4edcf2010-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 McCallc7e04da2010-05-28 18:45:08 +00001970 addAssociatedClassesAndNamespaces(Result, Class);
John McCallfa4edcf2010-05-28 06:08:54 +00001971 break;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001972 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00001973
John McCallfa4edcf2010-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 Takumi00995302011-01-27 07:09:49 +00001976 // member, its associated class is the member's class; else
John McCallfa4edcf2010-05-28 06:08:54 +00001977 // it has no associated class.
1978 case Type::Enum: {
1979 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001980
John McCallfa4edcf2010-05-28 06:08:54 +00001981 DeclContext *Ctx = Enum->getDeclContext();
1982 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001983 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001984
John McCallfa4edcf2010-05-28 06:08:54 +00001985 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001986 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001987
John McCallfa4edcf2010-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 Gregorf25760e2011-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 McCallfa4edcf2010-05-28 06:08:54 +00002049 case Type::ObjCObject:
2050 case Type::ObjCInterface:
2051 case Type::ObjCObjectPointer:
Douglas Gregorf25760e2011-04-12 01:02:45 +00002052 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCallfa4edcf2010-05-28 06:08:54 +00002053 break;
Eli Friedmanb001de72011-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 McCallfa4edcf2010-05-28 06:08:54 +00002060 }
2061
2062 if (Queue.empty()) break;
2063 T = Queue.back();
2064 Queue.pop_back();
Douglas Gregorfa047642009-02-04 00:32:51 +00002065 }
Douglas Gregorfa047642009-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 Stump1eb44332009-09-09 15:08:12 +00002073/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00002074/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00002075void
John McCall42f48fb2012-08-24 20:38:34 +00002076Sema::FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
2077 llvm::ArrayRef<Expr *> Args,
Douglas Gregorfa047642009-02-04 00:32:51 +00002078 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00002079 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002080 AssociatedNamespaces.clear();
2081 AssociatedClasses.clear();
2082
John McCall42f48fb2012-08-24 20:38:34 +00002083 AssociatedLookup Result(*this, InstantiationLoc,
2084 AssociatedNamespaces, AssociatedClasses);
John McCallc7e04da2010-05-28 18:45:08 +00002085
Douglas Gregorfa047642009-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 Stump1eb44332009-09-09 15:08:12 +00002092 // argument).
Ahmed Charles13a140c2012-02-25 11:00:22 +00002093 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002094 Expr *Arg = Args[ArgIdx];
2095
2096 if (Arg->getType() != Context.OverloadTy) {
John McCallc7e04da2010-05-28 18:45:08 +00002097 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregorfa047642009-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 Gregordaa439a2009-07-08 10:57:20 +00002108 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00002109 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCall2de56d12010-08-25 11:45:40 +00002110 if (unaryOp->getOpcode() == UO_AddrOf)
John McCallba135432009-11-21 08:51:07 +00002111 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002112
John McCallc7e04da2010-05-28 18:45:08 +00002113 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2114 if (!ULE) continue;
John McCallba135432009-11-21 08:51:07 +00002115
John McCallc7e04da2010-05-28 18:45:08 +00002116 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2117 I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00002118 // Look through any using declarations to find the underlying function.
2119 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002120
Chandler Carruthbd647292009-12-29 06:17:27 +00002121 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2122 if (!FDecl)
2123 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-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 McCallc7e04da2010-05-28 18:45:08 +00002127 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002128 }
2129 }
2130}
Douglas Gregor3fd95ce2009-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 Stump1eb44332009-09-09 15:08:12 +00002137static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002138IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2139 QualType T1, QualType T2,
2140 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00002141 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2142 return true;
2143
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002144 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2145 return true;
2146
John McCall183700f2009-09-21 23:43:11 +00002147 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-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 Gregora4923eb2009-11-16 21:35:15 +00002153 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-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 Gregora4923eb2009-11-16 21:35:15 +00002162 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002163 return true;
2164 }
2165
2166 return false;
2167}
2168
John McCall7d384dd2009-11-18 07:57:50 +00002169NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002170 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00002171 LookupNameKind NameKind,
2172 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002173 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00002174 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00002175 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00002176}
2177
Douglas Gregor6e378de2009-04-23 23:18:26 +00002178/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002179ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002180 SourceLocation IdLoc,
2181 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002182 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002183 LookupObjCProtocolName, Redecl);
Douglas Gregor6e378de2009-04-23 23:18:26 +00002184 return cast_or_null<ObjCProtocolDecl>(D);
2185}
2186
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002187void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00002188 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00002189 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-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 Friedman33a31382009-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 Gregor3fd95ce2009-03-13 00:33:25 +00002199 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00002200 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002201 // when T2 is an enumeration type, are candidate functions.
2202 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00002203 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2204 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002205
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002206 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2207
John McCallf36e02d2009-10-09 21:13:30 +00002208 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002209 return;
2210
2211 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2212 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002213 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2214 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002215 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002216 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00002217 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002218 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00002219 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00002220 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00002221 // later?
2222 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002223 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00002224 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002225 }
2226}
2227
Sean Huntc39b6bc2011-06-24 02:11:39 +00002228Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Sean Hunt308742c2011-06-04 04:32:43 +00002229 CXXSpecialMember SM,
2230 bool ConstArg,
2231 bool VolatileArg,
2232 bool RValueThis,
2233 bool ConstThis,
2234 bool VolatileThis) {
Richard Smithd0adeb62012-11-27 21:20:31 +00002235 assert(CanDeclareSpecialMemberFunction(RD) &&
Sean Hunt308742c2011-06-04 04:32:43 +00002236 "doing special member lookup into record that isn't fully complete");
Richard Smithd0adeb62012-11-27 21:20:31 +00002237 RD = RD->getDefinition();
Sean Hunt308742c2011-06-04 04:32:43 +00002238 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;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002246 ID.AddPointer(RD);
Sean Hunt308742c2011-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
Sean Hunt30543582011-06-07 00:11:58 +00002262 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2263 Result = new (Result) SpecialMemberOverloadResult(ID);
Sean Hunt308742c2011-06-04 04:32:43 +00002264 SpecialMemberCache.InsertNode(Result, InsertPoint);
2265
2266 if (SM == CXXDestructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00002267 if (RD->needsImplicitDestructor())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002268 DeclareImplicitDestructor(RD);
2269 CXXDestructorDecl *DD = RD->getDestructor();
Sean Hunt308742c2011-06-04 04:32:43 +00002270 assert(DD && "record without a destructor");
2271 Result->setMethod(DD);
Richard Smith6c4c36c2012-03-30 20:53:28 +00002272 Result->setKind(DD->isDeleted() ?
2273 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith704c8f72012-04-20 18:46:14 +00002274 SpecialMemberOverloadResult::Success);
Sean Hunt308742c2011-06-04 04:32:43 +00002275 return Result;
2276 }
2277
Sean Huntb320e0c2011-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.
Sean Huntc39b6bc2011-06-24 02:11:39 +00002280 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Sean Huntb320e0c2011-06-10 03:50:41 +00002281 DeclarationName Name;
2282 Expr *Arg = 0;
2283 unsigned NumArgs;
2284
Richard Smith704c8f72012-04-20 18:46:14 +00002285 QualType ArgType = CanTy;
2286 ExprValueKind VK = VK_LValue;
2287
Sean Huntb320e0c2011-06-10 03:50:41 +00002288 if (SM == CXXDefaultConstructor) {
2289 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2290 NumArgs = 0;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002291 if (RD->needsImplicitDefaultConstructor())
2292 DeclareImplicitDefaultConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002293 } else {
2294 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2295 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smithe5411b72012-12-01 02:35:44 +00002296 if (RD->needsImplicitCopyConstructor())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002297 DeclareImplicitCopyConstructor(RD);
Richard Smith80ad52f2013-01-02 11:42:31 +00002298 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002299 DeclareImplicitMoveConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002300 } else {
2301 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smithe5411b72012-12-01 02:35:44 +00002302 if (RD->needsImplicitCopyAssignment())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002303 DeclareImplicitCopyAssignment(RD);
Richard Smith80ad52f2013-01-02 11:42:31 +00002304 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002305 DeclareImplicitMoveAssignment(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002306 }
2307
Sean Huntb320e0c2011-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.
Sean Huntab183df2011-06-22 22:13:13 +00002320 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Sean Huntb320e0c2011-06-10 03:50:41 +00002321 VK = VK_LValue;
2322 else
2323 VK = VK_RValue;
Richard Smith704c8f72012-04-20 18:46:14 +00002324 }
Sean Huntb320e0c2011-06-10 03:50:41 +00002325
Richard Smith704c8f72012-04-20 18:46:14 +00002326 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2327
2328 if (SM != CXXDefaultConstructor) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002329 NumArgs = 1;
Richard Smith704c8f72012-04-20 18:46:14 +00002330 Arg = &FakeArg;
Sean Huntb320e0c2011-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();
Sean Hunt4cc12c62011-06-23 00:26:20 +00002339 Expr::Classification Classification =
Richard Smith704c8f72012-04-20 18:46:14 +00002340 OpaqueValueExpr(SourceLocation(), ThisTy,
2341 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Sean Huntb320e0c2011-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()));
David Blaikie3bc93e32012-12-19 00:45:41 +00002347 DeclContext::lookup_result R = RD->lookup(Name);
Sean Huntb320e0c2011-06-10 03:50:41 +00002348
David Blaikie3bc93e32012-12-19 00:45:41 +00002349 assert(!R.empty() &&
Sean Huntb320e0c2011-06-10 03:50:41 +00002350 "lookup for a constructor or assignment operator was empty");
David Blaikie3bc93e32012-12-19 00:45:41 +00002351 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002352 Decl *Cand = *I;
Sean Hunt4cc12c62011-06-23 00:26:20 +00002353
Sean Huntc39b6bc2011-06-24 02:11:39 +00002354 if (Cand->isInvalidDecl())
Sean Huntb320e0c2011-06-10 03:50:41 +00002355 continue;
2356
Sean Huntc39b6bc2011-06-24 02:11:39 +00002357 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2358 // FIXME: [namespace.udecl]p15 says that we should only consider a
2359 // using declaration here if it does not match a declaration in the
2360 // derived class. We do not implement this correctly in other cases
2361 // either.
2362 Cand = U->getTargetDecl();
2363
2364 if (Cand->isInvalidDecl())
2365 continue;
2366 }
2367
2368 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002369 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Sean Huntc39b6bc2011-06-24 02:11:39 +00002370 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002371 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2372 OCS, true);
Sean Hunt4cc12c62011-06-23 00:26:20 +00002373 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00002374 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2375 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Sean Hunt431a1cb2011-06-22 02:58:46 +00002376 } else if (FunctionTemplateDecl *Tmpl =
Sean Huntc39b6bc2011-06-24 02:11:39 +00002377 dyn_cast<FunctionTemplateDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002378 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2379 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charles13a140c2012-02-25 11:00:22 +00002380 RD, 0, ThisTy, Classification,
2381 llvm::makeArrayRef(&Arg, NumArgs),
Sean Hunt4cc12c62011-06-23 00:26:20 +00002382 OCS, true);
2383 else
2384 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charles13a140c2012-02-25 11:00:22 +00002385 0, llvm::makeArrayRef(&Arg, NumArgs),
2386 OCS, true);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002387 } else {
2388 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Sean Huntb320e0c2011-06-10 03:50:41 +00002389 }
2390 }
2391
2392 OverloadCandidateSet::iterator Best;
2393 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2394 case OR_Success:
2395 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith704c8f72012-04-20 18:46:14 +00002396 Result->setKind(SpecialMemberOverloadResult::Success);
Sean Huntb320e0c2011-06-10 03:50:41 +00002397 break;
2398
2399 case OR_Deleted:
2400 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith6c4c36c2012-03-30 20:53:28 +00002401 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Sean Huntb320e0c2011-06-10 03:50:41 +00002402 break;
2403
2404 case OR_Ambiguous:
Richard Smith6c4c36c2012-03-30 20:53:28 +00002405 Result->setMethod(0);
2406 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2407 break;
2408
Sean Huntb320e0c2011-06-10 03:50:41 +00002409 case OR_No_Viable_Function:
2410 Result->setMethod(0);
Richard Smith6c4c36c2012-03-30 20:53:28 +00002411 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Sean Huntb320e0c2011-06-10 03:50:41 +00002412 break;
2413 }
2414
2415 return Result;
2416}
2417
2418/// \brief Look up the default constructor for the given class.
2419CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Sean Huntc530d172011-06-10 04:44:37 +00002420 SpecialMemberOverloadResult *Result =
Sean Huntb320e0c2011-06-10 03:50:41 +00002421 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2422 false, false);
2423
2424 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Sean Hunt308742c2011-06-04 04:32:43 +00002425}
2426
Sean Hunt661c67a2011-06-21 23:42:56 +00002427/// \brief Look up the copying constructor for the given class.
2428CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith704c8f72012-04-20 18:46:14 +00002429 unsigned Quals) {
Sean Huntc530d172011-06-10 04:44:37 +00002430 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2431 "non-const, non-volatile qualifiers for copy ctor arg");
2432 SpecialMemberOverloadResult *Result =
2433 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2434 Quals & Qualifiers::Volatile, false, false, false);
2435
Sean Huntc530d172011-06-10 04:44:37 +00002436 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2437}
2438
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002439/// \brief Look up the moving constructor for the given class.
Richard Smith6a06e5f2012-07-18 03:36:00 +00002440CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2441 unsigned Quals) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002442 SpecialMemberOverloadResult *Result =
Richard Smith6a06e5f2012-07-18 03:36:00 +00002443 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2444 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002445
2446 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2447}
2448
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002449/// \brief Look up the constructors for the given class.
2450DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002451 // If the implicit constructors have not yet been declared, do so now.
Richard Smithd0adeb62012-11-27 21:20:31 +00002452 if (CanDeclareSpecialMemberFunction(Class)) {
Sean Huntcdee3fe2011-05-11 22:34:38 +00002453 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002454 DeclareImplicitDefaultConstructor(Class);
Richard Smithe5411b72012-12-01 02:35:44 +00002455 if (Class->needsImplicitCopyConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002456 DeclareImplicitCopyConstructor(Class);
Richard Smith80ad52f2013-01-02 11:42:31 +00002457 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002458 DeclareImplicitMoveConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +00002459 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002460
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002461 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2462 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2463 return Class->lookup(Name);
2464}
2465
Sean Hunt661c67a2011-06-21 23:42:56 +00002466/// \brief Look up the copying assignment operator for the given class.
2467CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2468 unsigned Quals, bool RValueThis,
Richard Smith704c8f72012-04-20 18:46:14 +00002469 unsigned ThisQuals) {
Sean Hunt661c67a2011-06-21 23:42:56 +00002470 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2471 "non-const, non-volatile qualifiers for copy assignment arg");
2472 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2473 "non-const, non-volatile qualifiers for copy assignment this");
2474 SpecialMemberOverloadResult *Result =
2475 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2476 Quals & Qualifiers::Volatile, RValueThis,
2477 ThisQuals & Qualifiers::Const,
2478 ThisQuals & Qualifiers::Volatile);
2479
Sean Hunt661c67a2011-06-21 23:42:56 +00002480 return Result->getMethod();
2481}
2482
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002483/// \brief Look up the moving assignment operator for the given class.
2484CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith6a06e5f2012-07-18 03:36:00 +00002485 unsigned Quals,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002486 bool RValueThis,
2487 unsigned ThisQuals) {
2488 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2489 "non-const, non-volatile qualifiers for copy assignment this");
2490 SpecialMemberOverloadResult *Result =
Richard Smith6a06e5f2012-07-18 03:36:00 +00002491 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2492 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002493 ThisQuals & Qualifiers::Const,
2494 ThisQuals & Qualifiers::Volatile);
2495
2496 return Result->getMethod();
2497}
2498
Douglas Gregordb89f282010-07-01 22:47:18 +00002499/// \brief Look for the destructor of the given class.
2500///
Sean Huntc5c9b532011-06-03 21:10:40 +00002501/// During semantic analysis, this routine should be used in lieu of
2502/// CXXRecordDecl::getDestructor().
Douglas Gregordb89f282010-07-01 22:47:18 +00002503///
2504/// \returns The destructor for this class.
2505CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Sean Hunt308742c2011-06-04 04:32:43 +00002506 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2507 false, false, false,
2508 false, false)->getMethod());
Douglas Gregordb89f282010-07-01 22:47:18 +00002509}
2510
Richard Smith36f5cfe2012-03-09 08:00:36 +00002511/// LookupLiteralOperator - Determine which literal operator should be used for
2512/// a user-defined literal, per C++11 [lex.ext].
2513///
2514/// Normal overload resolution is not used to select which literal operator to
2515/// call for a user-defined literal. Look up the provided literal operator name,
2516/// and filter the results to the appropriate set for the given argument types.
2517Sema::LiteralOperatorLookupResult
2518Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2519 ArrayRef<QualType> ArgTys,
2520 bool AllowRawAndTemplate) {
2521 LookupName(R, S);
2522 assert(R.getResultKind() != LookupResult::Ambiguous &&
2523 "literal operator lookup can't be ambiguous");
2524
2525 // Filter the lookup results appropriately.
2526 LookupResult::Filter F = R.makeFilter();
2527
2528 bool FoundTemplate = false;
2529 bool FoundRaw = false;
2530 bool FoundExactMatch = false;
2531
2532 while (F.hasNext()) {
2533 Decl *D = F.next();
2534 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2535 D = USD->getTargetDecl();
2536
2537 bool IsTemplate = isa<FunctionTemplateDecl>(D);
2538 bool IsRaw = false;
2539 bool IsExactMatch = false;
2540
2541 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2542 if (FD->getNumParams() == 1 &&
2543 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2544 IsRaw = true;
Richard Smitha121eb32013-01-15 07:12:59 +00002545 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smith36f5cfe2012-03-09 08:00:36 +00002546 IsExactMatch = true;
2547 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2548 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2549 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2550 IsExactMatch = false;
2551 break;
2552 }
2553 }
2554 }
2555 }
2556
2557 if (IsExactMatch) {
2558 FoundExactMatch = true;
2559 AllowRawAndTemplate = false;
2560 if (FoundRaw || FoundTemplate) {
2561 // Go through again and remove the raw and template decls we've
2562 // already found.
2563 F.restart();
2564 FoundRaw = FoundTemplate = false;
2565 }
2566 } else if (AllowRawAndTemplate && (IsTemplate || IsRaw)) {
2567 FoundTemplate |= IsTemplate;
2568 FoundRaw |= IsRaw;
2569 } else {
2570 F.erase();
2571 }
2572 }
2573
2574 F.done();
2575
2576 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2577 // parameter type, that is used in preference to a raw literal operator
2578 // or literal operator template.
2579 if (FoundExactMatch)
2580 return LOLR_Cooked;
2581
2582 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2583 // operator template, but not both.
2584 if (FoundRaw && FoundTemplate) {
2585 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
2586 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2587 Decl *D = *I;
2588 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2589 D = USD->getTargetDecl();
2590 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2591 D = FunTmpl->getTemplatedDecl();
2592 NoteOverloadCandidate(cast<FunctionDecl>(D));
2593 }
2594 return LOLR_Error;
2595 }
2596
2597 if (FoundRaw)
2598 return LOLR_Raw;
2599
2600 if (FoundTemplate)
2601 return LOLR_Template;
2602
2603 // Didn't find anything we could use.
2604 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2605 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
2606 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRawAndTemplate;
2607 return LOLR_Error;
2608}
2609
John McCall7edb5fd2010-01-26 07:16:45 +00002610void ADLResult::insert(NamedDecl *New) {
2611 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2612
2613 // If we haven't yet seen a decl for this key, or the last decl
2614 // was exactly this one, we're done.
2615 if (Old == 0 || Old == New) {
2616 Old = New;
2617 return;
2618 }
2619
2620 // Otherwise, decide which is a more recent redeclaration.
2621 FunctionDecl *OldFD, *NewFD;
2622 if (isa<FunctionTemplateDecl>(New)) {
2623 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2624 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2625 } else {
2626 OldFD = cast<FunctionDecl>(Old);
2627 NewFD = cast<FunctionDecl>(New);
2628 }
2629
2630 FunctionDecl *Cursor = NewFD;
2631 while (true) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002632 Cursor = Cursor->getPreviousDecl();
John McCall7edb5fd2010-01-26 07:16:45 +00002633
2634 // If we got to the end without finding OldFD, OldFD is the newer
2635 // declaration; leave things as they are.
2636 if (!Cursor) return;
2637
2638 // If we do find OldFD, then NewFD is newer.
2639 if (Cursor == OldFD) break;
2640
2641 // Otherwise, keep looking.
2642 }
2643
2644 Old = New;
2645}
2646
Sebastian Redl644be852009-10-23 19:23:15 +00002647void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00002648 SourceLocation Loc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002649 llvm::ArrayRef<Expr *> Args,
Richard Smithb1502bc2012-10-18 17:56:02 +00002650 ADLResult &Result) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002651 // Find all of the associated namespaces and classes based on the
2652 // arguments we have.
2653 AssociatedNamespaceSet AssociatedNamespaces;
2654 AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00002655 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCall6ff07852009-08-07 22:18:02 +00002656 AssociatedNamespaces,
2657 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002658
Sebastian Redl644be852009-10-23 19:23:15 +00002659 QualType T1, T2;
2660 if (Operator) {
2661 T1 = Args[0]->getType();
Ahmed Charles13a140c2012-02-25 11:00:22 +00002662 if (Args.size() >= 2)
Sebastian Redl644be852009-10-23 19:23:15 +00002663 T2 = Args[1]->getType();
2664 }
2665
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002666 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002667 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2668 // and let Y be the lookup set produced by argument dependent
2669 // lookup (defined as follows). If X contains [...] then Y is
2670 // empty. Otherwise Y is the set of declarations found in the
2671 // namespaces associated with the argument types as described
2672 // below. The set of declarations found by the lookup of the name
2673 // is the union of X and Y.
2674 //
2675 // Here, we compute Y and add its members to the overloaded
2676 // candidate set.
2677 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002678 NSEnd = AssociatedNamespaces.end();
2679 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002680 // When considering an associated namespace, the lookup is the
2681 // same as the lookup performed when the associated namespace is
2682 // used as a qualifier (3.4.3.2) except that:
2683 //
2684 // -- Any using-directives in the associated namespace are
2685 // ignored.
2686 //
John McCall6ff07852009-08-07 22:18:02 +00002687 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002688 // associated classes are visible within their respective
2689 // namespaces even if they are not visible during an ordinary
2690 // lookup (11.4).
David Blaikie3bc93e32012-12-19 00:45:41 +00002691 DeclContext::lookup_result R = (*NS)->lookup(Name);
2692 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
2693 ++I) {
John McCall6e266892010-01-26 03:27:55 +00002694 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00002695 // If the only declaration here is an ordinary friend, consider
2696 // it only if it was declared in an associated classes.
2697 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00002698 DeclContext *LexDC = D->getLexicalDeclContext();
2699 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2700 continue;
2701 }
Mike Stump1eb44332009-09-09 15:08:12 +00002702
John McCalla113e722010-01-26 06:04:06 +00002703 if (isa<UsingShadowDecl>(D))
2704 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00002705
John McCalla113e722010-01-26 06:04:06 +00002706 if (isa<FunctionDecl>(D)) {
2707 if (Operator &&
2708 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2709 T1, T2, Context))
2710 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00002711 } else if (!isa<FunctionTemplateDecl>(D))
2712 continue;
2713
2714 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00002715 }
2716 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002717}
Douglas Gregor546be3c2009-12-30 17:04:44 +00002718
2719//----------------------------------------------------------------------------
2720// Search for all visible declarations.
2721//----------------------------------------------------------------------------
2722VisibleDeclConsumer::~VisibleDeclConsumer() { }
2723
2724namespace {
2725
2726class ShadowContextRAII;
2727
2728class VisibleDeclsRecord {
2729public:
2730 /// \brief An entry in the shadow map, which is optimized to store a
2731 /// single declaration (the common case) but can also store a list
2732 /// of declarations.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002733 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002734
2735private:
2736 /// \brief A mapping from declaration names to the declarations that have
2737 /// this name within a particular scope.
2738 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2739
2740 /// \brief A list of shadow maps, which is used to model name hiding.
2741 std::list<ShadowMap> ShadowMaps;
2742
2743 /// \brief The declaration contexts we have already visited.
2744 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2745
2746 friend class ShadowContextRAII;
2747
2748public:
2749 /// \brief Determine whether we have already visited this context
2750 /// (and, if not, note that we are going to visit that context now).
2751 bool visitedContext(DeclContext *Ctx) {
2752 return !VisitedContexts.insert(Ctx);
2753 }
2754
Douglas Gregor8071e422010-08-15 06:18:01 +00002755 bool alreadyVisitedContext(DeclContext *Ctx) {
2756 return VisitedContexts.count(Ctx);
2757 }
2758
Douglas Gregor546be3c2009-12-30 17:04:44 +00002759 /// \brief Determine whether the given declaration is hidden in the
2760 /// current scope.
2761 ///
2762 /// \returns the declaration that hides the given declaration, or
2763 /// NULL if no such declaration exists.
2764 NamedDecl *checkHidden(NamedDecl *ND);
2765
2766 /// \brief Add a declaration to the current shadow map.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002767 void add(NamedDecl *ND) {
2768 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2769 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002770};
2771
2772/// \brief RAII object that records when we've entered a shadow context.
2773class ShadowContextRAII {
2774 VisibleDeclsRecord &Visible;
2775
2776 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2777
2778public:
2779 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2780 Visible.ShadowMaps.push_back(ShadowMap());
2781 }
2782
2783 ~ShadowContextRAII() {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002784 Visible.ShadowMaps.pop_back();
2785 }
2786};
2787
2788} // end anonymous namespace
2789
Douglas Gregor546be3c2009-12-30 17:04:44 +00002790NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002791 // Look through using declarations.
2792 ND = ND->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002793
Douglas Gregor546be3c2009-12-30 17:04:44 +00002794 unsigned IDNS = ND->getIdentifierNamespace();
2795 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2796 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2797 SM != SMEnd; ++SM) {
2798 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2799 if (Pos == SM->end())
2800 continue;
2801
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002802 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00002803 IEnd = Pos->second.end();
2804 I != IEnd; ++I) {
2805 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002806 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002807 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor546be3c2009-12-30 17:04:44 +00002808 Decl::IDNS_ObjCProtocol)))
2809 continue;
2810
2811 // Protocols are in distinct namespaces from everything else.
2812 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2813 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2814 (*I)->getIdentifierNamespace() != IDNS)
2815 continue;
2816
Douglas Gregor0cc84042010-01-14 15:47:35 +00002817 // Functions and function templates in the same scope overload
2818 // rather than hide. FIXME: Look for hiding based on function
2819 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002820 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002821 ND->isFunctionOrFunctionTemplate() &&
2822 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002823 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002824
Douglas Gregor546be3c2009-12-30 17:04:44 +00002825 // We've found a declaration that hides this one.
2826 return *I;
2827 }
2828 }
2829
2830 return 0;
2831}
2832
2833static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2834 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002835 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002836 VisibleDeclConsumer &Consumer,
2837 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00002838 if (!Ctx)
2839 return;
2840
Douglas Gregor546be3c2009-12-30 17:04:44 +00002841 // Make sure we don't visit the same context twice.
2842 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2843 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002844
Douglas Gregor4923aa22010-07-02 20:37:36 +00002845 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2846 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2847
Douglas Gregor546be3c2009-12-30 17:04:44 +00002848 // Enumerate all of the results in this context.
Nick Lewycky173a37a2012-04-03 21:44:08 +00002849 for (DeclContext::all_lookups_iterator L = Ctx->lookups_begin(),
2850 LEnd = Ctx->lookups_end();
2851 L != LEnd; ++L) {
David Blaikie3bc93e32012-12-19 00:45:41 +00002852 DeclContext::lookup_result R = *L;
2853 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
2854 ++I) {
2855 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) {
Douglas Gregor55368912011-12-14 16:03:29 +00002856 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00002857 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002858 Visited.add(ND);
2859 }
Douglas Gregor70c23352010-12-09 21:44:02 +00002860 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002861 }
2862 }
2863
2864 // Traverse using directives for qualified name lookup.
2865 if (QualifiedNameLookup) {
2866 ShadowContextRAII Shadow(Visited);
2867 DeclContext::udir_iterator I, E;
2868 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002869 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002870 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002871 }
2872 }
2873
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002874 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002875 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00002876 if (!Record->hasDefinition())
2877 return;
2878
Douglas Gregor546be3c2009-12-30 17:04:44 +00002879 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2880 BEnd = Record->bases_end();
2881 B != BEnd; ++B) {
2882 QualType BaseType = B->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002883
Douglas Gregor546be3c2009-12-30 17:04:44 +00002884 // Don't look into dependent bases, because name lookup can't look
2885 // there anyway.
2886 if (BaseType->isDependentType())
2887 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002888
Douglas Gregor546be3c2009-12-30 17:04:44 +00002889 const RecordType *Record = BaseType->getAs<RecordType>();
2890 if (!Record)
2891 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002892
Douglas Gregor546be3c2009-12-30 17:04:44 +00002893 // FIXME: It would be nice to be able to determine whether referencing
2894 // a particular member would be ambiguous. For example, given
2895 //
2896 // struct A { int member; };
2897 // struct B { int member; };
2898 // struct C : A, B { };
2899 //
2900 // void f(C *c) { c->### }
2901 //
2902 // accessing 'member' would result in an ambiguity. However, we
2903 // could be smart enough to qualify the member with the base
2904 // class, e.g.,
2905 //
2906 // c->B::member
2907 //
2908 // or
2909 //
2910 // c->A::member
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002911
Douglas Gregor546be3c2009-12-30 17:04:44 +00002912 // Find results in this base class (and its bases).
2913 ShadowContextRAII Shadow(Visited);
2914 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002915 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002916 }
2917 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002918
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002919 // Traverse the contexts of Objective-C classes.
2920 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2921 // Traverse categories.
Douglas Gregord3297242013-01-16 23:00:23 +00002922 for (ObjCInterfaceDecl::visible_categories_iterator
2923 Cat = IFace->visible_categories_begin(),
2924 CatEnd = IFace->visible_categories_end();
2925 Cat != CatEnd; ++Cat) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002926 ShadowContextRAII Shadow(Visited);
Douglas Gregord3297242013-01-16 23:00:23 +00002927 LookupVisibleDecls(*Cat, Result, QualifiedNameLookup, false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002928 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002929 }
2930
2931 // Traverse protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00002932 for (ObjCInterfaceDecl::all_protocol_iterator
2933 I = IFace->all_referenced_protocol_begin(),
2934 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002935 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002936 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002937 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002938 }
2939
2940 // Traverse the superclass.
2941 if (IFace->getSuperClass()) {
2942 ShadowContextRAII Shadow(Visited);
2943 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002944 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002945 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002946
Douglas Gregorc220a182010-04-19 18:02:19 +00002947 // If there is an implementation, traverse it. We do this to find
2948 // synthesized ivars.
2949 if (IFace->getImplementation()) {
2950 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002951 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky893a6ea2012-04-03 20:26:45 +00002952 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregorc220a182010-04-19 18:02:19 +00002953 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002954 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2955 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2956 E = Protocol->protocol_end(); I != E; ++I) {
2957 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002958 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002959 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002960 }
2961 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2962 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2963 E = Category->protocol_end(); I != E; ++I) {
2964 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002965 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002966 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002967 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002968
Douglas Gregorc220a182010-04-19 18:02:19 +00002969 // If there is an implementation, traverse it.
2970 if (Category->getImplementation()) {
2971 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002972 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00002973 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002974 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002975 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002976}
2977
2978static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2979 UnqualUsingDirectiveSet &UDirs,
2980 VisibleDeclConsumer &Consumer,
2981 VisibleDeclsRecord &Visited) {
2982 if (!S)
2983 return;
2984
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002985 if (!S->getEntity() ||
2986 (!S->getParent() &&
Douglas Gregor8071e422010-08-15 06:18:01 +00002987 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor539c5c32010-01-07 00:31:29 +00002988 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2989 // Walk through the declarations in this Scope.
2990 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2991 D != DEnd; ++D) {
John McCalld226f652010-08-21 09:40:31 +00002992 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor55368912011-12-14 16:03:29 +00002993 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00002994 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002995 Visited.add(ND);
2996 }
2997 }
2998 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002999
Douglas Gregor711be1e2010-03-15 14:33:29 +00003000 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00003001 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00003002 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003003 // Look into this scope's declaration context, along with any of its
3004 // parent lookup contexts (e.g., enclosing classes), up to the point
3005 // where we hit the context stored in the next outer scope.
3006 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00003007 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003008
Douglas Gregordbdf5e72010-03-15 15:26:48 +00003009 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003010 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003011 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3012 if (Method->isInstanceMethod()) {
3013 // For instance methods, look for ivars in the method's interface.
3014 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3015 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregorca45da02010-11-02 20:36:02 +00003016 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003017 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Fariborz Jahanian8697d302011-08-31 22:24:06 +00003018 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorca45da02010-11-02 20:36:02 +00003019 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003020 }
3021
3022 // We've already performed all of the name lookup that we need
3023 // to for Objective-C methods; the next context will be the
3024 // outer scope.
3025 break;
3026 }
3027
Douglas Gregor546be3c2009-12-30 17:04:44 +00003028 if (Ctx->isFunctionOrMethod())
3029 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003030
3031 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003032 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003033 }
3034 } else if (!S->getParent()) {
3035 // Look into the translation unit scope. We walk through the translation
3036 // unit's declaration context, because the Scope itself won't have all of
3037 // the declarations if we loaded a precompiled header.
3038 // FIXME: We would like the translation unit's Scope object to point to the
3039 // translation unit, so we don't need this special "if" branch. However,
3040 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003041 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003042 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00003043 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003044 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003045 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003046 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003047 }
3048
Douglas Gregor546be3c2009-12-30 17:04:44 +00003049 if (Entity) {
3050 // Lookup visible declarations in any namespaces found by using
3051 // directives.
3052 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
3053 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
3054 for (; UI != UEnd; ++UI)
3055 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003056 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003057 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003058 }
3059
3060 // Lookup names in the parent scope.
3061 ShadowContextRAII Shadow(Visited);
3062 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3063}
3064
3065void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00003066 VisibleDeclConsumer &Consumer,
3067 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003068 // Determine the set of using directives available during
3069 // unqualified name lookup.
3070 Scope *Initial = S;
3071 UnqualUsingDirectiveSet UDirs;
David Blaikie4e4d0842012-03-11 07:00:24 +00003072 if (getLangOpts().CPlusPlus) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003073 // Find the first namespace or translation-unit scope.
3074 while (S && !isNamespaceOrTranslationUnitScope(S))
3075 S = S->getParent();
3076
3077 UDirs.visitScopeChain(Initial, S);
3078 }
3079 UDirs.done();
3080
3081 // Look for visible declarations.
3082 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3083 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003084 if (!IncludeGlobalScope)
3085 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003086 ShadowContextRAII Shadow(Visited);
3087 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3088}
3089
3090void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00003091 VisibleDeclConsumer &Consumer,
3092 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003093 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3094 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003095 if (!IncludeGlobalScope)
3096 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003097 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003098 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003099 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003100}
3101
Chris Lattner4ae493c2011-02-18 02:08:43 +00003102/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara67843042011-03-05 18:21:20 +00003103/// If GnuLabelLoc is a valid source location, then this is a definition
3104/// of an __label__ label name, otherwise it is a normal label definition
3105/// or use.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003106LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara67843042011-03-05 18:21:20 +00003107 SourceLocation GnuLabelLoc) {
Chris Lattner337e5502011-02-18 01:27:55 +00003108 // Do a lookup to see if we have a label with this name already.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003109 NamedDecl *Res = 0;
Abramo Bagnara67843042011-03-05 18:21:20 +00003110
3111 if (GnuLabelLoc.isValid()) {
3112 // Local label definitions always shadow existing labels.
3113 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3114 Scope *S = CurScope;
3115 PushOnScopeChains(Res, S, true);
3116 return cast<LabelDecl>(Res);
3117 }
3118
3119 // Not a GNU local label.
3120 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3121 // If we found a label, check to see if it is in the same context as us.
3122 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattner337e5502011-02-18 01:27:55 +00003123 if (Res && Res->getDeclContext() != CurContext)
3124 Res = 0;
Chris Lattner337e5502011-02-18 01:27:55 +00003125 if (Res == 0) {
3126 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara67843042011-03-05 18:21:20 +00003127 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3128 Scope *S = CurScope->getFnParent();
Chris Lattnerfebb5b82011-02-18 21:16:39 +00003129 assert(S && "Not in a function?");
3130 PushOnScopeChains(Res, S, true);
Chris Lattner337e5502011-02-18 01:27:55 +00003131 }
Chris Lattner337e5502011-02-18 01:27:55 +00003132 return cast<LabelDecl>(Res);
3133}
3134
3135//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003136// Typo correction
Chris Lattner337e5502011-02-18 01:27:55 +00003137//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003138
3139namespace {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003140
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003141typedef SmallVector<TypoCorrection, 1> TypoResultList;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003142typedef llvm::StringMap<TypoResultList, llvm::BumpPtrAllocator> TypoResultsMap;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003143typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003144
3145static const unsigned MaxTypoDistanceResultSets = 5;
3146
Douglas Gregor546be3c2009-12-30 17:04:44 +00003147class TypoCorrectionConsumer : public VisibleDeclConsumer {
3148 /// \brief The name written that is a typo in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003149 StringRef Typo;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003150
3151 /// \brief The results found that have the smallest edit distance
3152 /// found (so far) with the typo name.
Douglas Gregore24b5752010-10-14 20:34:08 +00003153 ///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003154 /// The pointer value being set to the current DeclContext indicates
3155 /// whether there is a keyword with this name.
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003156 TypoEditDistanceMap CorrectionResults;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003157
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003158 Sema &SemaRef;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003159
Douglas Gregor546be3c2009-12-30 17:04:44 +00003160public:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003161 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003162 : Typo(Typo->getName()),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003163 SemaRef(SemaRef) { }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003164
Erik Verbruggend1205962011-10-06 07:27:49 +00003165 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3166 bool InBaseClass);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003167 void FoundName(StringRef Name);
3168 void addKeywordResult(StringRef Keyword);
3169 void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003170 NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003171 void addCorrection(TypoCorrection Correction);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003172
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003173 typedef TypoResultsMap::iterator result_iterator;
3174 typedef TypoEditDistanceMap::iterator distance_iterator;
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003175 distance_iterator begin() { return CorrectionResults.begin(); }
3176 distance_iterator end() { return CorrectionResults.end(); }
3177 void erase(distance_iterator I) { CorrectionResults.erase(I); }
3178 unsigned size() const { return CorrectionResults.size(); }
3179 bool empty() const { return CorrectionResults.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003180
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003181 TypoResultList &operator[](StringRef Name) {
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003182 return CorrectionResults.begin()->second[Name];
Douglas Gregor7b824e82010-10-15 13:35:25 +00003183 }
3184
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003185 unsigned getBestEditDistance(bool Normalized) {
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003186 if (CorrectionResults.empty())
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003187 return (std::numeric_limits<unsigned>::max)();
3188
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003189 unsigned BestED = CorrectionResults.begin()->first;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003190 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003191 }
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003192
3193 TypoResultsMap &getBestResults() {
3194 return CorrectionResults.begin()->second;
3195 }
3196
Douglas Gregor546be3c2009-12-30 17:04:44 +00003197};
3198
3199}
3200
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003201void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggend1205962011-10-06 07:27:49 +00003202 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003203 // Don't consider hidden names for typo correction.
3204 if (Hiding)
3205 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003206
Douglas Gregor546be3c2009-12-30 17:04:44 +00003207 // Only consider entities with identifiers for names, ignoring
3208 // special names (constructors, overloaded operators, selectors,
3209 // etc.).
3210 IdentifierInfo *Name = ND->getIdentifier();
3211 if (!Name)
3212 return;
3213
Douglas Gregor95f42922010-10-14 22:11:03 +00003214 FoundName(Name->getName());
3215}
3216
Chris Lattner5f9e2722011-07-23 10:55:15 +00003217void TypoCorrectionConsumer::FoundName(StringRef Name) {
Douglas Gregor362a8f22010-10-19 19:39:10 +00003218 // Use a simple length-based heuristic to determine the minimum possible
3219 // edit distance. If the minimum isn't good enough, bail out early.
3220 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003221 if (MinED && Typo.size() / MinED < 3)
Douglas Gregor362a8f22010-10-19 19:39:10 +00003222 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003223
Douglas Gregora1194772010-10-19 22:14:33 +00003224 // Compute an upper bound on the allowable edit distance, so that the
3225 // edit-distance algorithm can short-circuit.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003226 unsigned UpperBound = (Typo.size() + 2) / 3;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003227
Douglas Gregor546be3c2009-12-30 17:04:44 +00003228 // Compute the edit distance between the typo and the name of this
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003229 // entity, and add the identifier to the list of results.
3230 addName(Name, NULL, Typo.edit_distance(Name, true, UpperBound));
Douglas Gregor546be3c2009-12-30 17:04:44 +00003231}
3232
Chris Lattner5f9e2722011-07-23 10:55:15 +00003233void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003234 // Compute the edit distance between the typo and this keyword,
3235 // and add the keyword to the list of results.
3236 addName(Keyword, NULL, Typo.edit_distance(Keyword), NULL, true);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003237}
3238
Chris Lattner5f9e2722011-07-23 10:55:15 +00003239void TypoCorrectionConsumer::addName(StringRef Name,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003240 NamedDecl *ND,
3241 unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003242 NestedNameSpecifier *NNS,
3243 bool isKeyword) {
3244 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
3245 if (isKeyword) TC.makeKeyword();
3246 addCorrection(TC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003247}
3248
3249void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003250 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003251 TypoResultList &CList =
3252 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth55620532011-06-28 22:48:40 +00003253
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003254 if (!CList.empty() && !CList.back().isResolved())
3255 CList.pop_back();
3256 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3257 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3258 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3259 RI != RIEnd; ++RI) {
3260 // If the Correction refers to a decl already in the result list,
3261 // replace the existing result if the string representation of Correction
3262 // comes before the current result alphabetically, then stop as there is
3263 // nothing more to be done to add Correction to the candidate set.
3264 if (RI->getCorrectionDecl() == NewND) {
3265 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3266 *RI = Correction;
3267 return;
3268 }
3269 }
3270 }
3271 if (CList.empty() || Correction.isResolved())
3272 CList.push_back(Correction);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003273
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003274 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
3275 erase(llvm::prior(CorrectionResults.end()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003276}
3277
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003278// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3279// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3280// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3281static void getNestedNameSpecifierIdentifiers(
3282 NestedNameSpecifier *NNS,
3283 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3284 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3285 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3286 else
3287 Identifiers.clear();
3288
3289 const IdentifierInfo *II = NULL;
3290
3291 switch (NNS->getKind()) {
3292 case NestedNameSpecifier::Identifier:
3293 II = NNS->getAsIdentifier();
3294 break;
3295
3296 case NestedNameSpecifier::Namespace:
3297 if (NNS->getAsNamespace()->isAnonymousNamespace())
3298 return;
3299 II = NNS->getAsNamespace()->getIdentifier();
3300 break;
3301
3302 case NestedNameSpecifier::NamespaceAlias:
3303 II = NNS->getAsNamespaceAlias()->getIdentifier();
3304 break;
3305
3306 case NestedNameSpecifier::TypeSpecWithTemplate:
3307 case NestedNameSpecifier::TypeSpec:
3308 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3309 break;
3310
3311 case NestedNameSpecifier::Global:
3312 return;
3313 }
3314
3315 if (II)
3316 Identifiers.push_back(II);
3317}
3318
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003319namespace {
3320
3321class SpecifierInfo {
3322 public:
3323 DeclContext* DeclCtx;
3324 NestedNameSpecifier* NameSpecifier;
3325 unsigned EditDistance;
3326
3327 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3328 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3329};
3330
Chris Lattner5f9e2722011-07-23 10:55:15 +00003331typedef SmallVector<DeclContext*, 4> DeclContextList;
3332typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003333
3334class NamespaceSpecifierSet {
3335 ASTContext &Context;
3336 DeclContextList CurContextChain;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003337 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3338 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003339 bool isSorted;
3340
3341 SpecifierInfoList Specifiers;
3342 llvm::SmallSetVector<unsigned, 4> Distances;
3343 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3344
3345 /// \brief Helper for building the list of DeclContexts between the current
3346 /// context and the top of the translation unit
3347 static DeclContextList BuildContextChain(DeclContext *Start);
3348
3349 void SortNamespaces();
3350
3351 public:
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003352 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3353 CXXScopeSpec *CurScopeSpec)
Benjamin Kramerc5bb9d42011-07-05 09:46:31 +00003354 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003355 isSorted(true) {
3356 if (CurScopeSpec && CurScopeSpec->getScopeRep())
3357 getNestedNameSpecifierIdentifiers(CurScopeSpec->getScopeRep(),
3358 CurNameSpecifierIdentifiers);
3359 // Build the list of identifiers that would be used for an absolute
Benjamin Kramer48d798c2012-06-02 10:20:41 +00003360 // (from the global context) NestedNameSpecifier referring to the current
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003361 // context.
3362 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3363 CEnd = CurContextChain.rend();
3364 C != CEnd; ++C) {
3365 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3366 CurContextIdentifiers.push_back(ND->getIdentifier());
3367 }
3368 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003369
3370 /// \brief Add the namespace to the set, computing the corresponding
3371 /// NestedNameSpecifier and its distance in the process.
3372 void AddNamespace(NamespaceDecl *ND);
3373
3374 typedef SpecifierInfoList::iterator iterator;
3375 iterator begin() {
3376 if (!isSorted) SortNamespaces();
3377 return Specifiers.begin();
3378 }
3379 iterator end() { return Specifiers.end(); }
3380};
3381
3382}
3383
3384DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003385 assert(Start && "Bulding a context chain from a null context");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003386 DeclContextList Chain;
3387 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3388 DC = DC->getLookupParent()) {
3389 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3390 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3391 !(ND && ND->isAnonymousNamespace()))
3392 Chain.push_back(DC->getPrimaryContext());
3393 }
3394 return Chain;
3395}
3396
3397void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003398 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003399 sortedDistances.append(Distances.begin(), Distances.end());
3400
3401 if (sortedDistances.size() > 1)
3402 std::sort(sortedDistances.begin(), sortedDistances.end());
3403
3404 Specifiers.clear();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003405 for (SmallVector<unsigned, 4>::iterator DI = sortedDistances.begin(),
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003406 DIEnd = sortedDistances.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003407 DI != DIEnd; ++DI) {
3408 SpecifierInfoList &SpecList = DistanceMap[*DI];
3409 Specifiers.append(SpecList.begin(), SpecList.end());
3410 }
3411
3412 isSorted = true;
3413}
3414
3415void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003416 DeclContext *Ctx = cast<DeclContext>(ND);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003417 NestedNameSpecifier *NNS = NULL;
3418 unsigned NumSpecifiers = 0;
3419 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003420 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003421
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003422 // Eliminate common elements from the two DeclContext chains.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003423 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3424 CEnd = CurContextChain.rend();
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003425 C != CEnd && !NamespaceDeclChain.empty() &&
3426 NamespaceDeclChain.back() == *C; ++C) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003427 NamespaceDeclChain.pop_back();
3428 }
3429
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003430 // Add an explicit leading '::' specifier if needed.
3431 if (NamespaceDecl *ND =
Kaelyn Uhrain3ad02aa2012-02-15 22:59:03 +00003432 NamespaceDeclChain.empty() ? NULL :
3433 dyn_cast_or_null<NamespaceDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003434 IdentifierInfo *Name = ND->getIdentifier();
3435 if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3436 Name) != CurContextIdentifiers.end() ||
3437 std::find(CurNameSpecifierIdentifiers.begin(),
3438 CurNameSpecifierIdentifiers.end(),
3439 Name) != CurNameSpecifierIdentifiers.end()) {
3440 NamespaceDeclChain = FullNamespaceDeclChain;
3441 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3442 }
3443 }
3444
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003445 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3446 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3447 CEnd = NamespaceDeclChain.rend();
3448 C != CEnd; ++C) {
3449 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3450 if (ND) {
3451 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3452 ++NumSpecifiers;
3453 }
3454 }
3455
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003456 // If the built NestedNameSpecifier would be replacing an existing
3457 // NestedNameSpecifier, use the number of component identifiers that
3458 // would need to be changed as the edit distance instead of the number
3459 // of components in the built NestedNameSpecifier.
3460 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3461 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3462 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3463 NumSpecifiers = llvm::ComputeEditDistance(
3464 llvm::ArrayRef<const IdentifierInfo*>(CurNameSpecifierIdentifiers),
3465 llvm::ArrayRef<const IdentifierInfo*>(NewNameSpecifierIdentifiers));
3466 }
3467
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003468 isSorted = false;
3469 Distances.insert(NumSpecifiers);
3470 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
Douglas Gregoraaf87162010-04-14 20:04:41 +00003471}
3472
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003473/// \brief Perform name lookup for a possible result for typo correction.
3474static void LookupPotentialTypoResult(Sema &SemaRef,
3475 LookupResult &Res,
3476 IdentifierInfo *Name,
3477 Scope *S, CXXScopeSpec *SS,
3478 DeclContext *MemberContext,
3479 bool EnteringContext,
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003480 bool isObjCIvarLookup) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003481 Res.suppressDiagnostics();
3482 Res.clear();
3483 Res.setLookupName(Name);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003484 if (MemberContext) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003485 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003486 if (isObjCIvarLookup) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003487 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3488 Res.addDecl(Ivar);
3489 Res.resolveKind();
3490 return;
3491 }
3492 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003493
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003494 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3495 Res.addDecl(Prop);
3496 Res.resolveKind();
3497 return;
3498 }
3499 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003500
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003501 SemaRef.LookupQualifiedName(Res, MemberContext);
3502 return;
3503 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003504
3505 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003506 EnteringContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003507
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003508 // Fake ivar lookup; this should really be part of
3509 // LookupParsedName.
3510 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3511 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003512 (Res.empty() ||
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003513 (Res.isSingleResult() &&
3514 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003515 if (ObjCIvarDecl *IV
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003516 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3517 Res.addDecl(IV);
3518 Res.resolveKind();
3519 }
3520 }
3521 }
3522}
3523
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003524/// \brief Add keywords to the consumer as possible typo corrections.
3525static void AddKeywordsToConsumer(Sema &SemaRef,
3526 TypoCorrectionConsumer &Consumer,
Richard Smith0f4b5be2012-06-08 21:35:42 +00003527 Scope *S, CorrectionCandidateCallback &CCC,
3528 bool AfterNestedNameSpecifier) {
3529 if (AfterNestedNameSpecifier) {
3530 // For 'X::', we know exactly which keywords can appear next.
3531 Consumer.addKeywordResult("template");
3532 if (CCC.WantExpressionKeywords)
3533 Consumer.addKeywordResult("operator");
3534 return;
3535 }
3536
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003537 if (CCC.WantObjCSuper)
3538 Consumer.addKeywordResult("super");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003539
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003540 if (CCC.WantTypeSpecifiers) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003541 // Add type-specifier keywords to the set of results.
3542 const char *CTypeSpecs[] = {
3543 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor07f4a062011-07-01 21:27:45 +00003544 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003545 "_Complex", "_Imaginary",
3546 // storage-specifiers as well
3547 "extern", "inline", "static", "typedef"
3548 };
3549
3550 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3551 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3552 Consumer.addKeywordResult(CTypeSpecs[I]);
3553
David Blaikie4e4d0842012-03-11 07:00:24 +00003554 if (SemaRef.getLangOpts().C99)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003555 Consumer.addKeywordResult("restrict");
David Blaikie4e4d0842012-03-11 07:00:24 +00003556 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003557 Consumer.addKeywordResult("bool");
David Blaikie4e4d0842012-03-11 07:00:24 +00003558 else if (SemaRef.getLangOpts().C99)
Douglas Gregor07f4a062011-07-01 21:27:45 +00003559 Consumer.addKeywordResult("_Bool");
3560
David Blaikie4e4d0842012-03-11 07:00:24 +00003561 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003562 Consumer.addKeywordResult("class");
3563 Consumer.addKeywordResult("typename");
3564 Consumer.addKeywordResult("wchar_t");
3565
Richard Smith80ad52f2013-01-02 11:42:31 +00003566 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003567 Consumer.addKeywordResult("char16_t");
3568 Consumer.addKeywordResult("char32_t");
3569 Consumer.addKeywordResult("constexpr");
3570 Consumer.addKeywordResult("decltype");
3571 Consumer.addKeywordResult("thread_local");
3572 }
3573 }
3574
David Blaikie4e4d0842012-03-11 07:00:24 +00003575 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003576 Consumer.addKeywordResult("typeof");
3577 }
3578
David Blaikie4e4d0842012-03-11 07:00:24 +00003579 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003580 Consumer.addKeywordResult("const_cast");
3581 Consumer.addKeywordResult("dynamic_cast");
3582 Consumer.addKeywordResult("reinterpret_cast");
3583 Consumer.addKeywordResult("static_cast");
3584 }
3585
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003586 if (CCC.WantExpressionKeywords) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003587 Consumer.addKeywordResult("sizeof");
David Blaikie4e4d0842012-03-11 07:00:24 +00003588 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003589 Consumer.addKeywordResult("false");
3590 Consumer.addKeywordResult("true");
3591 }
3592
David Blaikie4e4d0842012-03-11 07:00:24 +00003593 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003594 const char *CXXExprs[] = {
3595 "delete", "new", "operator", "throw", "typeid"
3596 };
3597 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3598 for (unsigned I = 0; I != NumCXXExprs; ++I)
3599 Consumer.addKeywordResult(CXXExprs[I]);
3600
3601 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3602 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3603 Consumer.addKeywordResult("this");
3604
Richard Smith80ad52f2013-01-02 11:42:31 +00003605 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003606 Consumer.addKeywordResult("alignof");
3607 Consumer.addKeywordResult("nullptr");
3608 }
3609 }
Jordan Rosef70a8862012-06-30 21:33:57 +00003610
3611 if (SemaRef.getLangOpts().C11) {
3612 // FIXME: We should not suggest _Alignof if the alignof macro
3613 // is present.
3614 Consumer.addKeywordResult("_Alignof");
3615 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003616 }
3617
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003618 if (CCC.WantRemainingKeywords) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003619 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3620 // Statements.
3621 const char *CStmts[] = {
3622 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3623 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3624 for (unsigned I = 0; I != NumCStmts; ++I)
3625 Consumer.addKeywordResult(CStmts[I]);
3626
David Blaikie4e4d0842012-03-11 07:00:24 +00003627 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003628 Consumer.addKeywordResult("catch");
3629 Consumer.addKeywordResult("try");
3630 }
3631
3632 if (S && S->getBreakParent())
3633 Consumer.addKeywordResult("break");
3634
3635 if (S && S->getContinueParent())
3636 Consumer.addKeywordResult("continue");
3637
3638 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3639 Consumer.addKeywordResult("case");
3640 Consumer.addKeywordResult("default");
3641 }
3642 } else {
David Blaikie4e4d0842012-03-11 07:00:24 +00003643 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003644 Consumer.addKeywordResult("namespace");
3645 Consumer.addKeywordResult("template");
3646 }
3647
3648 if (S && S->isClassScope()) {
3649 Consumer.addKeywordResult("explicit");
3650 Consumer.addKeywordResult("friend");
3651 Consumer.addKeywordResult("mutable");
3652 Consumer.addKeywordResult("private");
3653 Consumer.addKeywordResult("protected");
3654 Consumer.addKeywordResult("public");
3655 Consumer.addKeywordResult("virtual");
3656 }
3657 }
3658
David Blaikie4e4d0842012-03-11 07:00:24 +00003659 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003660 Consumer.addKeywordResult("using");
3661
Richard Smith80ad52f2013-01-02 11:42:31 +00003662 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003663 Consumer.addKeywordResult("static_assert");
3664 }
3665 }
3666}
3667
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003668static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3669 TypoCorrection &Candidate) {
3670 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3671 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3672}
3673
Douglas Gregor546be3c2009-12-30 17:04:44 +00003674/// \brief Try to "correct" a typo in the source code by finding
3675/// visible declarations whose names are similar to the name that was
3676/// present in the source code.
3677///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003678/// \param TypoName the \c DeclarationNameInfo structure that contains
3679/// the name that was present in the source code along with its location.
3680///
3681/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003682///
3683/// \param S the scope in which name lookup occurs.
3684///
3685/// \param SS the nested-name-specifier that precedes the name we're
3686/// looking for, if present.
3687///
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003688/// \param CCC A CorrectionCandidateCallback object that provides further
3689/// validation of typo correction candidates. It also provides flags for
3690/// determining the set of keywords permitted.
3691///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003692/// \param MemberContext if non-NULL, the context in which to look for
3693/// a member access expression.
3694///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003695/// \param EnteringContext whether we're entering the context described by
Douglas Gregorbb092ba2009-12-31 05:20:13 +00003696/// the nested-name-specifier SS.
3697///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003698/// \param OPT when non-NULL, the search for visible declarations will
3699/// also walk the protocols in the qualified interfaces of \p OPT.
3700///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003701/// \returns a \c TypoCorrection containing the corrected name if the typo
3702/// along with information such as the \c NamedDecl where the corrected name
3703/// was declared, and any additional \c NestedNameSpecifier needed to access
3704/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3705TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3706 Sema::LookupNameKind LookupKind,
3707 Scope *S, CXXScopeSpec *SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00003708 CorrectionCandidateCallback &CCC,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003709 DeclContext *MemberContext,
3710 bool EnteringContext,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003711 const ObjCObjectPointerType *OPT) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003712 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003713 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003714
Francois Pichet4d604d62011-12-03 15:55:29 +00003715 // In Microsoft mode, don't perform typo correction in a template member
3716 // function dependent context because it interferes with the "lookup into
3717 // dependent bases of class templates" feature.
David Blaikie4e4d0842012-03-11 07:00:24 +00003718 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichet4d604d62011-12-03 15:55:29 +00003719 isa<CXXMethodDecl>(CurContext))
3720 return TypoCorrection();
3721
Douglas Gregor546be3c2009-12-30 17:04:44 +00003722 // We only attempt to correct typos for identifiers.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003723 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003724 if (!Typo)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003725 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003726
3727 // If the scope specifier itself was invalid, don't try to correct
3728 // typos.
3729 if (SS && SS->isInvalid())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003730 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003731
3732 // Never try to correct typos during template deduction or
3733 // instantiation.
3734 if (!ActiveTemplateInstantiations.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003735 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003736
Argyrios Kyrtzidis57f8da52013-03-14 22:56:43 +00003737 // Don't try to correct 'super'.
3738 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
3739 return TypoCorrection();
3740
Argyrios Kyrtzidis6aa240c2013-03-16 01:40:35 +00003741 // This is for testing.
3742 if (Diags.getWarnOnSpellCheck()) {
3743 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
3744 "spell-checking initiated for %0");
3745 Diag(TypoName.getLoc(), DiagID) << TypoName.getName();
3746 }
Argyrios Kyrtzidis57f8da52013-03-14 22:56:43 +00003747
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003748 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003749
3750 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003751
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003752 // If a callback object considers an empty typo correction candidate to be
3753 // viable, assume it does not do any actual validation of the candidates.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003754 TypoCorrection EmptyCorrection;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003755 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003756
Douglas Gregoraaf87162010-04-14 20:04:41 +00003757 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003758 bool IsUnqualifiedLookup = false;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003759 DeclContext *QualifiedDC = MemberContext;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003760 if (MemberContext) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003761 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003762
3763 // Look in qualified interfaces.
3764 if (OPT) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003765 for (ObjCObjectPointerType::qual_iterator
3766 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003767 I != E; ++I)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003768 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003769 }
3770 } else if (SS && SS->isSet()) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003771 QualifiedDC = computeDeclContext(*SS, EnteringContext);
3772 if (!QualifiedDC)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003773 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003774
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003775 // Provide a stop gap for files that are just seriously broken. Trying
3776 // to correct all typos can turn into a HUGE performance penalty, causing
3777 // some files to take minutes to get rejected by the parser.
3778 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003779 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003780 ++TyposCorrected;
3781
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003782 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003783 } else {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003784 IsUnqualifiedLookup = true;
3785 UnqualifiedTyposCorrectedMap::iterator Cached
3786 = UnqualifiedTyposCorrected.find(Typo);
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003787 if (Cached != UnqualifiedTyposCorrected.end()) {
3788 // Add the cached value, unless it's a keyword or fails validation. In the
3789 // keyword case, we'll end up adding the keyword below.
3790 if (Cached->second) {
3791 if (!Cached->second.isKeyword() &&
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003792 isCandidateViable(CCC, Cached->second))
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003793 Consumer.addCorrection(Cached->second);
3794 } else {
3795 // Only honor no-correction cache hits when a callback that will validate
3796 // correction candidates is not being used.
3797 if (!ValidatingCallback)
3798 return TypoCorrection();
3799 }
3800 }
3801 if (Cached == UnqualifiedTyposCorrected.end()) {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003802 // Provide a stop gap for files that are just seriously broken. Trying
3803 // to correct all typos can turn into a HUGE performance penalty, causing
3804 // some files to take minutes to get rejected by the parser.
3805 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003806 return TypoCorrection();
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003807 }
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003808 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003809
Douglas Gregor01798682012-03-26 16:54:18 +00003810 // Determine whether we are going to search in the various namespaces for
3811 // corrections.
3812 bool SearchNamespaces
Kaelyn Uhrain6d858d92012-04-03 18:20:11 +00003813 = getLangOpts().CPlusPlus &&
Douglas Gregor01798682012-03-26 16:54:18 +00003814 (IsUnqualifiedLookup || (QualifiedDC && QualifiedDC->isNamespace()));
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00003815 // In a few cases we *only* want to search for corrections bases on just
3816 // adding or changing the nested name specifier.
3817 bool AllowOnlyNNSChanges = Typo->getName().size() < 3;
Douglas Gregor01798682012-03-26 16:54:18 +00003818
3819 if (IsUnqualifiedLookup || SearchNamespaces) {
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003820 // For unqualified lookup, look through all of the names that we have
3821 // seen in this translation unit.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003822 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003823 for (IdentifierTable::iterator I = Context.Idents.begin(),
3824 IEnd = Context.Idents.end();
3825 I != IEnd; ++I)
3826 Consumer.FoundName(I->getKey());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003827
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003828 // Walk through identifiers in external identifier sources.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003829 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003830 if (IdentifierInfoLookup *External
3831 = Context.Idents.getExternalIdentifierLookup()) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00003832 OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003833 do {
3834 StringRef Name = Iter->Next();
3835 if (Name.empty())
3836 break;
Douglas Gregor95f42922010-10-14 22:11:03 +00003837
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003838 Consumer.FoundName(Name);
3839 } while (true);
Douglas Gregor95f42922010-10-14 22:11:03 +00003840 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003841 }
3842
Richard Smith0f4b5be2012-06-08 21:35:42 +00003843 AddKeywordsToConsumer(*this, Consumer, S, CCC, SS && SS->isNotEmpty());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003844
Douglas Gregoraaf87162010-04-14 20:04:41 +00003845 // If we haven't found anything, we're done.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003846 if (Consumer.empty()) {
3847 // If this was an unqualified lookup, note that no correction was found.
3848 if (IsUnqualifiedLookup)
3849 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003850
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003851 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003852 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003853
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00003854 // Make sure the best edit distance (prior to adding any namespace qualifiers)
3855 // is not more that about a third of the length of the typo's identifier.
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003856 unsigned ED = Consumer.getBestEditDistance(true);
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003857 if (ED > 0 && Typo->getName().size() / ED < 3) {
3858 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregor157a3ff2010-10-27 14:20:34 +00003859 if (IsUnqualifiedLookup)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003860 (void)UnqualifiedTyposCorrected[Typo];
3861
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003862 return TypoCorrection();
3863 }
3864
Douglas Gregor01798682012-03-26 16:54:18 +00003865 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
3866 // to search those namespaces.
3867 if (SearchNamespaces) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003868 // Load any externally-known namespaces.
3869 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003870 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003871 LoadedExternalKnownNamespaces = true;
3872 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
3873 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
3874 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
3875 }
3876
Nick Lewycky01a41142013-01-26 00:35:08 +00003877 for (llvm::MapVector<NamespaceDecl*, bool>::iterator
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003878 KNI = KnownNamespaces.begin(),
3879 KNIEnd = KnownNamespaces.end();
3880 KNI != KNIEnd; ++KNI)
3881 Namespaces.AddNamespace(KNI->first);
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003882 }
Douglas Gregore24b5752010-10-14 20:34:08 +00003883
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003884 // Weed out any names that could not be found by name lookup or, if a
3885 // CorrectionCandidateCallback object was provided, failed validation.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003886 SmallVector<TypoCorrection, 16> QualifiedResults;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003887 LookupResult TmpRes(*this, TypoName, LookupKind);
3888 TmpRes.suppressDiagnostics();
3889 while (!Consumer.empty()) {
3890 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3891 unsigned ED = DI->first;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003892 for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(),
3893 IEnd = DI->second.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003894 I != IEnd; /* Increment in loop. */) {
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00003895 // If we only want nested name specifier corrections, ignore potential
3896 // corrections that have a different base identifier from the typo.
3897 if (AllowOnlyNNSChanges &&
3898 I->second.front().getCorrectionAsIdentifierInfo() != Typo) {
3899 TypoCorrectionConsumer::result_iterator Prev = I;
3900 ++I;
3901 DI->second.erase(Prev);
3902 continue;
3903 }
3904
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003905 // If the item already has been looked up or is a keyword, keep it.
3906 // If a validator callback object was given, drop the correction
3907 // unless it passes validation.
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003908 bool Viable = false;
Benjamin Kramerb3996962012-07-27 10:21:08 +00003909 for (TypoResultList::iterator RI = I->second.begin();
3910 RI != I->second.end(); /* Increment in loop. */) {
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003911 TypoResultList::iterator Prev = RI;
3912 ++RI;
3913 if (Prev->isResolved()) {
3914 if (!isCandidateViable(CCC, *Prev))
Benjamin Kramerb3996962012-07-27 10:21:08 +00003915 RI = I->second.erase(Prev);
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003916 else
3917 Viable = true;
3918 }
3919 }
3920 if (Viable || I->second.empty()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003921 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003922 ++I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003923 if (!Viable)
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003924 DI->second.erase(Prev);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003925 continue;
Douglas Gregore24b5752010-10-14 20:34:08 +00003926 }
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003927 assert(I->second.size() == 1 && "Expected a single unresolved candidate");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003928
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003929 // Perform name lookup on this name.
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003930 TypoCorrection &Candidate = I->second.front();
3931 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003932 LookupPotentialTypoResult(*this, TmpRes, Name, S, SS, MemberContext,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00003933 EnteringContext, CCC.IsObjCIvarLookup);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003934
3935 switch (TmpRes.getResultKind()) {
3936 case LookupResult::NotFound:
3937 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00003938 case LookupResult::FoundUnresolvedValue:
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003939 QualifiedResults.push_back(Candidate);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003940 // We didn't find this name in our scope, or didn't like what we found;
3941 // ignore it.
3942 {
3943 TypoCorrectionConsumer::result_iterator Next = I;
3944 ++Next;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003945 DI->second.erase(I);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003946 I = Next;
3947 }
3948 break;
3949
3950 case LookupResult::Ambiguous:
3951 // We don't deal with ambiguities.
3952 return TypoCorrection();
3953
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003954 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003955 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003956 // Store all of the Decls for overloaded symbols
3957 for (LookupResult::iterator TRD = TmpRes.begin(),
3958 TRDEnd = TmpRes.end();
3959 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003960 Candidate.addCorrectionDecl(*TRD);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003961 ++I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003962 if (!isCandidateViable(CCC, Candidate))
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003963 DI->second.erase(Prev);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003964 break;
3965 }
3966
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003967 case LookupResult::Found: {
3968 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003969 Candidate.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003970 ++I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003971 if (!isCandidateViable(CCC, Candidate))
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003972 DI->second.erase(Prev);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003973 break;
3974 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003975
3976 }
Douglas Gregore24b5752010-10-14 20:34:08 +00003977 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003978
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003979 if (DI->second.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003980 Consumer.erase(DI);
David Blaikie4e4d0842012-03-11 07:00:24 +00003981 else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !ED)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003982 // If there are results in the closest possible bucket, stop
3983 break;
3984
3985 // Only perform the qualified lookups for C++
Douglas Gregor01798682012-03-26 16:54:18 +00003986 if (SearchNamespaces) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003987 TmpRes.suppressDiagnostics();
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003988 for (SmallVector<TypoCorrection,
3989 16>::iterator QRI = QualifiedResults.begin(),
3990 QRIEnd = QualifiedResults.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003991 QRI != QRIEnd; ++QRI) {
3992 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
3993 NIEnd = Namespaces.end();
3994 NI != NIEnd; ++NI) {
3995 DeclContext *Ctx = NI->DeclCtx;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003996
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003997 // FIXME: Stop searching once the namespaces are too far away to create
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003998 // acceptable corrections for this identifier (since the namespaces
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003999 // are sorted in ascending order by edit distance).
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004000
4001 TmpRes.clear();
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00004002 TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004003 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
4004
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004005 // Any corrections added below will be validated in subsequent
4006 // iterations of the main while() loop over the Consumer's contents.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004007 switch (TmpRes.getResultKind()) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004008 case LookupResult::Found: {
4009 TypoCorrection TC(*QRI);
4010 TC.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
4011 TC.setCorrectionSpecifier(NI->NameSpecifier);
4012 TC.setQualifierDistance(NI->EditDistance);
4013 Consumer.addCorrection(TC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004014 break;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004015 }
4016 case LookupResult::FoundOverloaded: {
4017 TypoCorrection TC(*QRI);
4018 TC.setCorrectionSpecifier(NI->NameSpecifier);
4019 TC.setQualifierDistance(NI->EditDistance);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004020 for (LookupResult::iterator TRD = TmpRes.begin(),
4021 TRDEnd = TmpRes.end();
4022 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004023 TC.addCorrectionDecl(*TRD);
4024 Consumer.addCorrection(TC);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004025 break;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004026 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004027 case LookupResult::NotFound:
4028 case LookupResult::NotFoundInCurrentInstantiation:
4029 case LookupResult::Ambiguous:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00004030 case LookupResult::FoundUnresolvedValue:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004031 break;
4032 }
4033 }
4034 }
4035 }
4036
4037 QualifiedResults.clear();
4038 }
4039
4040 // No corrections remain...
4041 if (Consumer.empty()) return TypoCorrection();
4042
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00004043 TypoResultsMap &BestResults = Consumer.getBestResults();
4044 ED = Consumer.getBestEditDistance(true);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004045
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00004046 if (!AllowOnlyNNSChanges && ED > 0 && Typo->getName().size() / ED < 3) {
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004047 // If this was an unqualified lookup and we believe the callback
4048 // object wouldn't have filtered out possible corrections, note
4049 // that no correction was found.
4050 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004051 (void)UnqualifiedTyposCorrected[Typo];
4052
4053 return TypoCorrection();
4054 }
4055
Douglas Gregore24b5752010-10-14 20:34:08 +00004056 // If only a single name remains, return that result.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004057 if (BestResults.size() == 1) {
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004058 const TypoResultList &CorrectionList = BestResults.begin()->second;
4059 const TypoCorrection &Result = CorrectionList.front();
4060 if (CorrectionList.size() != 1) return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004061
Douglas Gregor53e4b552010-10-26 17:18:00 +00004062 // Don't correct to a keyword that's the same as the typo; the keyword
4063 // wasn't actually in scope.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004064 if (ED == 0 && Result.isKeyword()) return TypoCorrection();
4065
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004066 // Record the correction for unqualified lookup.
4067 if (IsUnqualifiedLookup)
4068 UnqualifiedTyposCorrected[Typo] = Result;
4069
David Blaikie6952c012012-10-12 20:00:44 +00004070 TypoCorrection TC = Result;
4071 TC.setCorrectionRange(SS, TypoName);
4072 return TC;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004073 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004074 else if (BestResults.size() > 1
4075 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4076 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4077 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4078 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00004079 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004080 && BestResults["super"].front().isKeyword()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004081 // Prefer 'super' when we're completing in a message-receiver
4082 // context.
4083
4084 // Don't correct to a keyword that's the same as the typo; the keyword
4085 // wasn't actually in scope.
4086 if (ED == 0) return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004087
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004088 // Record the correction for unqualified lookup.
4089 if (IsUnqualifiedLookup)
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004090 UnqualifiedTyposCorrected[Typo] = BestResults["super"].front();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004091
David Blaikie6952c012012-10-12 20:00:44 +00004092 TypoCorrection TC = BestResults["super"].front();
4093 TC.setCorrectionRange(SS, TypoName);
4094 return TC;
Douglas Gregor7b824e82010-10-15 13:35:25 +00004095 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004096
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004097 // If this was an unqualified lookup and we believe the callback object did
4098 // not filter out possible corrections, note that no correction was found.
4099 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004100 (void)UnqualifiedTyposCorrected[Typo];
4101
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004102 return TypoCorrection();
4103}
4104
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004105void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4106 if (!CDecl) return;
4107
4108 if (isKeyword())
4109 CorrectionDecls.clear();
4110
Kaelyn Uhrain728948f2012-11-19 18:49:53 +00004111 CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004112
4113 if (!CorrectionName)
4114 CorrectionName = CDecl->getDeclName();
4115}
4116
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004117std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4118 if (CorrectionNameSpec) {
4119 std::string tmpBuffer;
4120 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4121 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004122 CorrectionName.printName(PrefixOStream);
4123 return PrefixOStream.str();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004124 }
4125
4126 return CorrectionName.getAsString();
Douglas Gregor546be3c2009-12-30 17:04:44 +00004127}