blob: 0fe3db1901fdebfaaf04c3b30d43c6219e22ec69 [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 Gregor6bed88e2013-03-27 12:51:49 +0000948 // If this is a file context, we need to perform unqualified name
949 // lookup considering using directives.
950 if (Ctx->isFileContext()) {
951 UnqualUsingDirectiveSet UDirs;
952 UDirs.visit(Ctx, Ctx);
953 UDirs.done();
954
955 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
956 R.resolveKind();
957 return true;
958 }
959
960 continue;
961 }
962
Douglas Gregore942bbe2009-09-10 16:57:35 +0000963 // Perform qualified name lookup into this context.
964 // FIXME: In some cases, we know that every name that could be found by
965 // this qualified name lookup will also be on the identifier chain. For
966 // example, inside a class without any base classes, we never need to
967 // perform qualified lookup because all of the members are on top of the
968 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000969 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +0000970 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +0000971 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000972 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000973 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000974
John McCalld7be78a2009-11-10 07:01:13 +0000975 // Stop if we ran out of scopes.
976 // FIXME: This really, really shouldn't be happening.
977 if (!S) return false;
978
Argyrios Kyrtzidis78f59112010-10-29 16:12:50 +0000979 // If we are looking for members, no need to look into global/namespace scope.
980 if (R.getLookupKind() == LookupMemberName)
981 return false;
982
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000983 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000984 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +0000985 //
Mike Stump390b4cc2009-05-16 07:39:55 +0000986 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
987 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000988
John McCalld7be78a2009-11-10 07:01:13 +0000989 UnqualUsingDirectiveSet UDirs;
990 UDirs.visitScopeChain(Initial, S);
991 UDirs.done();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000992
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000993 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000994 // Unqualified name lookup in C++ requires looking into scopes
995 // that aren't strictly lexical, and therefore we walk through the
996 // context as well as walking through the scopes.
997 for (; S; S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000998 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000999 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +00001000 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor55368912011-12-14 16:03:29 +00001001 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001002 // We found something. Look for anything else in our scope
1003 // with this same name and in an acceptable identifier
1004 // namespace, so that we can construct an overload set if we
1005 // need to.
John McCallf36e02d2009-10-09 21:13:30 +00001006 Found = true;
Douglas Gregor55368912011-12-14 16:03:29 +00001007 R.addDecl(ND);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001008 }
1009 }
1010
Douglas Gregor00b4b032010-05-14 04:53:42 +00001011 if (Found && S->isTemplateParamScope()) {
John McCallf36e02d2009-10-09 21:13:30 +00001012 R.resolveKind();
1013 return true;
1014 }
1015
Douglas Gregor00b4b032010-05-14 04:53:42 +00001016 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1017 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1018 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1019 // We've just searched the last template parameter scope and
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00001020 // found nothing, so look into the contexts between the
Douglas Gregor00b4b032010-05-14 04:53:42 +00001021 // lexical and semantic declaration contexts returned by
1022 // findOuterContext(). This implements the name lookup behavior
1023 // of C++ [temp.local]p8.
1024 Ctx = OutsideOfTemplateParamDC;
1025 OutsideOfTemplateParamDC = 0;
1026 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001027
Douglas Gregor00b4b032010-05-14 04:53:42 +00001028 if (Ctx) {
1029 DeclContext *OuterCtx;
1030 bool SearchAfterTemplateScope;
1031 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1032 if (SearchAfterTemplateScope)
1033 OutsideOfTemplateParamDC = OuterCtx;
1034
1035 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1036 // We do not directly look into transparent contexts, since
1037 // those entities will be found in the nearest enclosing
1038 // non-transparent context.
1039 if (Ctx->isTransparentContext())
1040 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001041
Douglas Gregor00b4b032010-05-14 04:53:42 +00001042 // If we have a context, and it's not a context stashed in the
1043 // template parameter scope for an out-of-line definition, also
1044 // look into that context.
1045 if (!(Found && S && S->isTemplateParamScope())) {
1046 assert(Ctx->isFileContext() &&
1047 "We should have been looking only at file context here already.");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001048
Douglas Gregor00b4b032010-05-14 04:53:42 +00001049 // Look into context considering using-directives.
1050 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1051 Found = true;
1052 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001053
Douglas Gregor00b4b032010-05-14 04:53:42 +00001054 if (Found) {
1055 R.resolveKind();
1056 return true;
1057 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001058
Douglas Gregor00b4b032010-05-14 04:53:42 +00001059 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1060 return false;
1061 }
1062 }
1063
Douglas Gregor1df0ee92010-02-05 07:07:10 +00001064 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +00001065 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001066 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001067
John McCallf36e02d2009-10-09 21:13:30 +00001068 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001069}
1070
Douglas Gregor55368912011-12-14 16:03:29 +00001071/// \brief Retrieve the visible declaration corresponding to D, if any.
1072///
1073/// This routine determines whether the declaration D is visible in the current
1074/// module, with the current imports. If not, it checks whether any
1075/// redeclaration of D is visible, and if so, returns that declaration.
1076///
1077/// \returns D, or a visible previous declaration of D, whichever is more recent
1078/// and visible. If no declaration of D is visible, returns null.
1079static NamedDecl *getVisibleDecl(NamedDecl *D) {
1080 if (LookupResult::isVisible(D))
1081 return D;
1082
Douglas Gregor0782ef22012-01-06 22:05:37 +00001083 for (Decl::redecl_iterator RD = D->redecls_begin(), RDEnd = D->redecls_end();
1084 RD != RDEnd; ++RD) {
David Blaikie581deb32012-06-06 20:45:41 +00001085 if (NamedDecl *ND = dyn_cast<NamedDecl>(*RD)) {
Douglas Gregor0782ef22012-01-06 22:05:37 +00001086 if (LookupResult::isVisible(ND))
1087 return ND;
1088 }
Douglas Gregor55368912011-12-14 16:03:29 +00001089 }
1090
1091 return 0;
1092}
1093
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001094/// @brief Perform unqualified name lookup starting from a given
1095/// scope.
1096///
1097/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1098/// used to find names within the current scope. For example, 'x' in
1099/// @code
1100/// int x;
1101/// int f() {
1102/// return x; // unqualified name look finds 'x' in the global scope
1103/// }
1104/// @endcode
1105///
1106/// Different lookup criteria can find different names. For example, a
1107/// particular scope can have both a struct and a function of the same
1108/// name, and each can be found by certain lookup criteria. For more
1109/// information about lookup criteria, see the documentation for the
1110/// class LookupCriteria.
1111///
1112/// @param S The scope from which unqualified name lookup will
1113/// begin. If the lookup criteria permits, name lookup may also search
1114/// in the parent scopes.
1115///
James Dennett8da16872012-06-22 10:32:46 +00001116/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1117/// look up and the lookup kind), and is updated with the results of lookup
1118/// including zero or more declarations and possibly additional information
1119/// used to diagnose ambiguities.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001120///
James Dennett8da16872012-06-22 10:32:46 +00001121/// @returns \c true if lookup succeeded and false otherwise.
John McCalla24dc2e2009-11-17 02:14:36 +00001122bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1123 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +00001124 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001125
John McCalla24dc2e2009-11-17 02:14:36 +00001126 LookupNameKind NameKind = R.getLookupKind();
1127
David Blaikie4e4d0842012-03-11 07:00:24 +00001128 if (!getLangOpts().CPlusPlus) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001129 // Unqualified name lookup in C/Objective-C is purely lexical, so
1130 // search in the declarations attached to the name.
John McCall1d7c5282009-12-18 10:40:03 +00001131 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001132 // Find the nearest non-transparent declaration scope.
1133 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001134 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001135 static_cast<DeclContext *>(S->getEntity())
1136 ->isTransparentContext()))
1137 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001138 }
1139
John McCall1d7c5282009-12-18 10:40:03 +00001140 unsigned IDNS = R.getIdentifierNamespace();
1141
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001142 // Scan up the scope chain looking for a decl that matches this
1143 // identifier that is in the appropriate namespace. This search
1144 // should not take long, as shadowing of names is uncommon, and
1145 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001146 bool LeftStartingScope = false;
1147
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001148 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +00001149 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001150 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001151 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001152 if (NameKind == LookupRedeclarationWithLinkage) {
1153 // Determine whether this (or a previous) declaration is
1154 // out-of-scope.
John McCalld226f652010-08-21 09:40:31 +00001155 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001156 LeftStartingScope = true;
1157
1158 // If we found something outside of our starting scope that
1159 // does not have linkage, skip it.
1160 if (LeftStartingScope && !((*I)->hasLinkage()))
1161 continue;
1162 }
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001163 else if (NameKind == LookupObjCImplicitSelfParam &&
1164 !isa<ImplicitParamDecl>(*I))
1165 continue;
1166
Douglas Gregor10ce9322011-12-02 20:08:44 +00001167 // If this declaration is module-private and it came from an AST
1168 // file, we can't see it.
Douglas Gregor447af242012-01-05 01:11:47 +00001169 NamedDecl *D = R.isHiddenDeclarationVisible()? *I : getVisibleDecl(*I);
Douglas Gregor55368912011-12-14 16:03:29 +00001170 if (!D)
Douglas Gregor10ce9322011-12-02 20:08:44 +00001171 continue;
Douglas Gregor55368912011-12-14 16:03:29 +00001172
1173 R.addDecl(D);
John McCallf36e02d2009-10-09 21:13:30 +00001174
Douglas Gregor7a537402012-01-03 23:26:26 +00001175 // Check whether there are any other declarations with the same name
1176 // and in the same scope.
Douglas Gregorda795b42012-01-04 16:44:10 +00001177 if (I != IEnd) {
Douglas Gregor117c4562012-01-13 23:06:53 +00001178 // Find the scope in which this declaration was declared (if it
1179 // actually exists in a Scope).
1180 while (S && !S->isDeclScope(D))
1181 S = S->getParent();
1182
1183 // If the scope containing the declaration is the translation unit,
1184 // then we'll need to perform our checks based on the matching
1185 // DeclContexts rather than matching scopes.
1186 if (S && isNamespaceOrTranslationUnitScope(S))
1187 S = 0;
1188
1189 // Compute the DeclContext, if we need it.
1190 DeclContext *DC = 0;
1191 if (!S)
1192 DC = (*I)->getDeclContext()->getRedeclContext();
1193
Douglas Gregorda795b42012-01-04 16:44:10 +00001194 IdentifierResolver::iterator LastI = I;
1195 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor117c4562012-01-13 23:06:53 +00001196 if (S) {
1197 // Match based on scope.
1198 if (!S->isDeclScope(*LastI))
1199 break;
1200 } else {
1201 // Match based on DeclContext.
1202 DeclContext *LastDC
1203 = (*LastI)->getDeclContext()->getRedeclContext();
1204 if (!LastDC->Equals(DC))
1205 break;
1206 }
1207
1208 // If the declaration isn't in the right namespace, skip it.
Douglas Gregorda795b42012-01-04 16:44:10 +00001209 if (!(*LastI)->isInIdentifierNamespace(IDNS))
1210 continue;
Douglas Gregor117c4562012-01-13 23:06:53 +00001211
Douglas Gregor447af242012-01-05 01:11:47 +00001212 D = R.isHiddenDeclarationVisible()? *LastI : getVisibleDecl(*LastI);
Douglas Gregorda795b42012-01-04 16:44:10 +00001213 if (D)
1214 R.addDecl(D);
1215 }
Douglas Gregorf9201e02009-02-11 23:02:49 +00001216
Douglas Gregorda795b42012-01-04 16:44:10 +00001217 R.resolveKind();
Douglas Gregorf9201e02009-02-11 23:02:49 +00001218 }
John McCallf36e02d2009-10-09 21:13:30 +00001219 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +00001220 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001221 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001222 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +00001223 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +00001224 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001225 }
1226
1227 // If we didn't find a use of this identifier, and if the identifier
1228 // corresponds to a compiler builtin, create the decl object for the builtin
1229 // now, injecting it into translation unit scope, and return it.
Axel Naumann42151d52011-04-13 13:19:46 +00001230 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1231 return true;
Douglas Gregor3e41d602009-02-13 23:20:09 +00001232
Axel Naumannf8291a12011-02-24 16:47:47 +00001233 // If we didn't find a use of this identifier, the ExternalSource
1234 // may be able to handle the situation.
1235 // Note: some lookup failures are expected!
1236 // See e.g. R.isForRedeclaration().
1237 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001238}
1239
John McCall6e247262009-10-10 05:48:19 +00001240/// @brief Perform qualified name lookup in the namespaces nominated by
1241/// using directives by the given context.
1242///
1243/// C++98 [namespace.qual]p2:
James Dennett7ba75922012-06-19 21:05:49 +00001244/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6e247262009-10-10 05:48:19 +00001245/// (where X is the global namespace), let S be the set of all
1246/// declarations of m in X and in the transitive closure of all
1247/// namespaces nominated by using-directives in X and its used
1248/// namespaces, except that using-directives are ignored in any
1249/// namespace, including X, directly containing one or more
1250/// declarations of m. No namespace is searched more than once in
1251/// the lookup of a name. If S is the empty set, the program is
1252/// ill-formed. Otherwise, if S has exactly one member, or if the
1253/// context of the reference is a using-declaration
1254/// (namespace.udecl), S is the required set of declarations of
1255/// m. Otherwise if the use of m is not one that allows a unique
1256/// declaration to be chosen from S, the program is ill-formed.
James Dennett7ba75922012-06-19 21:05:49 +00001257///
John McCall6e247262009-10-10 05:48:19 +00001258/// C++98 [namespace.qual]p5:
1259/// During the lookup of a qualified namespace member name, if the
1260/// lookup finds more than one declaration of the member, and if one
1261/// declaration introduces a class name or enumeration name and the
1262/// other declarations either introduce the same object, the same
1263/// enumerator or a set of functions, the non-type name hides the
1264/// class or enumeration name if and only if the declarations are
1265/// from the same namespace; otherwise (the declarations are from
1266/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +00001267static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +00001268 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +00001269 assert(StartDC->isFileContext() && "start context is not a file context");
1270
1271 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1272 DeclContext::udir_iterator E = StartDC->using_directives_end();
1273
1274 if (I == E) return false;
1275
1276 // We have at least added all these contexts to the queue.
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001277 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6e247262009-10-10 05:48:19 +00001278 Visited.insert(StartDC);
1279
1280 // We have not yet looked into these namespaces, much less added
1281 // their "using-children" to the queue.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001282 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6e247262009-10-10 05:48:19 +00001283
1284 // We have already looked into the initial namespace; seed the queue
1285 // with its using-children.
1286 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001287 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001288 if (Visited.insert(ND))
John McCall6e247262009-10-10 05:48:19 +00001289 Queue.push_back(ND);
1290 }
1291
1292 // The easiest way to implement the restriction in [namespace.qual]p5
1293 // is to check whether any of the individual results found a tag
1294 // and, if so, to declare an ambiguity if the final result is not
1295 // a tag.
1296 bool FoundTag = false;
1297 bool FoundNonTag = false;
1298
John McCall7d384dd2009-11-18 07:57:50 +00001299 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001300
1301 bool Found = false;
1302 while (!Queue.empty()) {
1303 NamespaceDecl *ND = Queue.back();
1304 Queue.pop_back();
1305
1306 // We go through some convolutions here to avoid copying results
1307 // between LookupResults.
1308 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001309 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001310 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001311
1312 if (FoundDirect) {
1313 // First do any local hiding.
1314 DirectR.resolveKind();
1315
1316 // If the local result is a tag, remember that.
1317 if (DirectR.isSingleTagDecl())
1318 FoundTag = true;
1319 else
1320 FoundNonTag = true;
1321
1322 // Append the local results to the total results if necessary.
1323 if (UseLocal) {
1324 R.addAllDecls(LocalR);
1325 LocalR.clear();
1326 }
1327 }
1328
1329 // If we find names in this namespace, ignore its using directives.
1330 if (FoundDirect) {
1331 Found = true;
1332 continue;
1333 }
1334
1335 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1336 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001337 if (Visited.insert(Nom))
John McCall6e247262009-10-10 05:48:19 +00001338 Queue.push_back(Nom);
1339 }
1340 }
1341
1342 if (Found) {
1343 if (FoundTag && FoundNonTag)
1344 R.setAmbiguousQualifiedTagHiding();
1345 else
1346 R.resolveKind();
1347 }
1348
1349 return Found;
1350}
1351
Douglas Gregor8071e422010-08-15 06:18:01 +00001352/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001353static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor8071e422010-08-15 06:18:01 +00001354 CXXBasePath &Path,
1355 void *Name) {
1356 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001357
Douglas Gregor8071e422010-08-15 06:18:01 +00001358 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1359 Path.Decls = BaseRecord->lookup(N);
David Blaikie3bc93e32012-12-19 00:45:41 +00001360 return !Path.Decls.empty();
Douglas Gregor8071e422010-08-15 06:18:01 +00001361}
1362
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001363/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001364/// static members, nested types, and enumerators.
1365template<typename InputIterator>
1366static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1367 Decl *D = (*First)->getUnderlyingDecl();
1368 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1369 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001370
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001371 if (isa<CXXMethodDecl>(D)) {
1372 // Determine whether all of the methods are static.
1373 bool AllMethodsAreStatic = true;
1374 for(; First != Last; ++First) {
1375 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001376
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001377 if (!isa<CXXMethodDecl>(D)) {
1378 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1379 break;
1380 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001381
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001382 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1383 AllMethodsAreStatic = false;
1384 break;
1385 }
1386 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001387
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001388 if (AllMethodsAreStatic)
1389 return true;
1390 }
1391
1392 return false;
1393}
1394
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001395/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001396///
1397/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1398/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001399/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001400///
1401/// Different lookup criteria can find different names. For example, a
1402/// particular scope can have both a struct and a function of the same
1403/// name, and each can be found by certain lookup criteria. For more
1404/// information about lookup criteria, see the documentation for the
1405/// class LookupCriteria.
1406///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001407/// \param R captures both the lookup criteria and any lookup results found.
1408///
1409/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001410/// search. If the lookup criteria permits, name lookup may also search
1411/// in the parent contexts or (for C++ classes) base classes.
1412///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001413/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001414/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001415///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001416/// \returns true if lookup succeeded, false if it failed.
1417bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1418 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001419 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001420
John McCalla24dc2e2009-11-17 02:14:36 +00001421 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001422 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001423
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001424 // Make sure that the declaration context is complete.
1425 assert((!isa<TagDecl>(LookupCtx) ||
1426 LookupCtx->isDependentContext() ||
John McCall5e1cdac2011-10-07 06:10:15 +00001427 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith1af83c42012-03-23 03:33:32 +00001428 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001429 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001430
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001431 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001432 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001433 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001434 if (isa<CXXRecordDecl>(LookupCtx))
1435 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001436 return true;
1437 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001438
John McCall6e247262009-10-10 05:48:19 +00001439 // Don't descend into implied contexts for redeclarations.
1440 // C++98 [namespace.qual]p6:
1441 // In a declaration for a namespace member in which the
1442 // declarator-id is a qualified-id, given that the qualified-id
1443 // for the namespace member has the form
1444 // nested-name-specifier unqualified-id
1445 // the unqualified-id shall name a member of the namespace
1446 // designated by the nested-name-specifier.
1447 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001448 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001449 return false;
1450
John McCalla24dc2e2009-11-17 02:14:36 +00001451 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001452 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001453 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001454
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001455 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001456 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001457 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor025291b2010-07-01 00:21:21 +00001458 if (!LookupRec || !LookupRec->getDefinition())
John McCallf36e02d2009-10-09 21:13:30 +00001459 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001460
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001461 // If we're performing qualified name lookup into a dependent class,
1462 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001463 // dependent base classes, then we either have to delay lookup until
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001464 // template instantiation time (at which point all bases will be available)
1465 // or we have to fail.
1466 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1467 LookupRec->hasAnyDependentBases()) {
1468 R.setNotFoundInCurrentInstantiation();
1469 return false;
1470 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001471
Douglas Gregor7176fff2009-01-15 00:26:24 +00001472 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001473 CXXBasePaths Paths;
1474 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001475
1476 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001477 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001478 switch (R.getLookupKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001479 case LookupObjCImplicitSelfParam:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001480 case LookupOrdinaryName:
1481 case LookupMemberName:
1482 case LookupRedeclarationWithLinkage:
1483 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1484 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001485
Douglas Gregora8f32e02009-10-06 17:59:45 +00001486 case LookupTagName:
1487 BaseCallback = &CXXRecordDecl::FindTagMember;
1488 break;
John McCall9f54ad42009-12-10 09:41:52 +00001489
Douglas Gregor8071e422010-08-15 06:18:01 +00001490 case LookupAnyName:
1491 BaseCallback = &LookupAnyMember;
1492 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001493
John McCall9f54ad42009-12-10 09:41:52 +00001494 case LookupUsingDeclName:
1495 // This lookup is for redeclarations only.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001496
Douglas Gregora8f32e02009-10-06 17:59:45 +00001497 case LookupOperatorName:
1498 case LookupNamespaceName:
1499 case LookupObjCProtocolName:
Chris Lattner337e5502011-02-18 01:27:55 +00001500 case LookupLabel:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001501 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001502 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001503
Douglas Gregora8f32e02009-10-06 17:59:45 +00001504 case LookupNestedNameSpecifierName:
1505 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1506 break;
1507 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001508
John McCalla24dc2e2009-11-17 02:14:36 +00001509 if (!LookupRec->lookupInBases(BaseCallback,
1510 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001511 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001512
John McCall92f88312010-01-23 00:46:32 +00001513 R.setNamingClass(LookupRec);
1514
Douglas Gregor7176fff2009-01-15 00:26:24 +00001515 // C++ [class.member.lookup]p2:
1516 // [...] If the resulting set of declarations are not all from
1517 // sub-objects of the same type, or the set has a nonstatic member
1518 // and includes members from distinct sub-objects, there is an
1519 // ambiguity and the program is ill-formed. Otherwise that set is
1520 // the result of the lookup.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001521 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001522 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001523 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001524
Douglas Gregora8f32e02009-10-06 17:59:45 +00001525 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001526 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001527 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001528
John McCall46460a62010-01-20 21:53:11 +00001529 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1530 // across all paths.
1531 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001532
Douglas Gregor7176fff2009-01-15 00:26:24 +00001533 // Determine whether we're looking at a distinct sub-object or not.
1534 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001535 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001536 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1537 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001538 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001539 }
1540
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001541 if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001542 != Context.getCanonicalType(PathElement.Base->getType())) {
1543 // We found members of the given name in two subobjects of
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001544 // different types. If the declaration sets aren't the same, this
1545 // this lookup is ambiguous.
David Blaikie3bc93e32012-12-19 00:45:41 +00001546 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001547 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikie3bc93e32012-12-19 00:45:41 +00001548 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
1549 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001550
David Blaikie3bc93e32012-12-19 00:45:41 +00001551 while (FirstD != FirstPath->Decls.end() &&
1552 CurrentD != Path->Decls.end()) {
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001553 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1554 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1555 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001556
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001557 ++FirstD;
1558 ++CurrentD;
1559 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001560
David Blaikie3bc93e32012-12-19 00:45:41 +00001561 if (FirstD == FirstPath->Decls.end() &&
1562 CurrentD == Path->Decls.end())
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001563 continue;
1564 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001565
John McCallf36e02d2009-10-09 21:13:30 +00001566 R.setAmbiguousBaseSubobjectTypes(Paths);
1567 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001568 }
1569
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001570 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001571 // We have a different subobject of the same type.
1572
1573 // C++ [class.member.lookup]p5:
1574 // A static member, a nested type or an enumerator defined in
1575 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001576 // has more than one base class subobject of type T.
David Blaikie3bc93e32012-12-19 00:45:41 +00001577 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor7176fff2009-01-15 00:26:24 +00001578 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001579
Douglas Gregor7176fff2009-01-15 00:26:24 +00001580 // We have found a nonstatic member name in multiple, distinct
1581 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001582 R.setAmbiguousBaseSubobjects(Paths);
1583 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001584 }
1585 }
1586
1587 // Lookup in a base class succeeded; return these results.
1588
David Blaikie3bc93e32012-12-19 00:45:41 +00001589 DeclContext::lookup_result DR = Paths.front().Decls;
1590 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E; ++I) {
John McCall92f88312010-01-23 00:46:32 +00001591 NamedDecl *D = *I;
1592 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1593 D->getAccess());
1594 R.addDecl(D, AS);
1595 }
John McCallf36e02d2009-10-09 21:13:30 +00001596 R.resolveKind();
1597 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001598}
1599
1600/// @brief Performs name lookup for a name that was parsed in the
1601/// source code, and may contain a C++ scope specifier.
1602///
1603/// This routine is a convenience routine meant to be called from
1604/// contexts that receive a name and an optional C++ scope specifier
1605/// (e.g., "N::M::x"). It will then perform either qualified or
1606/// unqualified name lookup (with LookupQualifiedName or LookupName,
1607/// respectively) on the given name and return those results.
1608///
1609/// @param S The scope from which unqualified name lookup will
1610/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001611///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001612/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001613///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001614/// @param EnteringContext Indicates whether we are going to enter the
1615/// context of the scope-specifier SS (if present).
1616///
John McCallf36e02d2009-10-09 21:13:30 +00001617/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001618bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001619 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001620 if (SS && SS->isInvalid()) {
1621 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001622 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001623 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001624 }
Mike Stump1eb44332009-09-09 15:08:12 +00001625
Douglas Gregor495c35d2009-08-25 22:51:20 +00001626 if (SS && SS->isSet()) {
1627 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001628 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001629 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001630 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001631 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001632
John McCalla24dc2e2009-11-17 02:14:36 +00001633 R.setContextRange(SS->getRange());
John McCalla24dc2e2009-11-17 02:14:36 +00001634 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001635 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001636
Douglas Gregor495c35d2009-08-25 22:51:20 +00001637 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001638 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001639 // Name lookup can't find anything in this case.
Douglas Gregor3eafbb82011-10-24 22:24:50 +00001640 R.setNotFoundInCurrentInstantiation();
1641 R.setContextRange(SS->getRange());
John McCallf36e02d2009-10-09 21:13:30 +00001642 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001643 }
1644
Mike Stump1eb44332009-09-09 15:08:12 +00001645 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001646 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001647}
1648
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001649
James Dennett16ae9de2012-06-22 10:16:05 +00001650/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor7176fff2009-01-15 00:26:24 +00001651/// from name lookup.
1652///
James Dennett16ae9de2012-06-22 10:16:05 +00001653/// \param Result The result of the ambiguous lookup to be diagnosed.
Mike Stump1eb44332009-09-09 15:08:12 +00001654///
James Dennett16ae9de2012-06-22 10:16:05 +00001655/// \returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001656bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001657 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1658
John McCalla24dc2e2009-11-17 02:14:36 +00001659 DeclarationName Name = Result.getLookupName();
1660 SourceLocation NameLoc = Result.getNameLoc();
1661 SourceRange LookupRange = Result.getContextRange();
1662
John McCall6e247262009-10-10 05:48:19 +00001663 switch (Result.getAmbiguityKind()) {
1664 case LookupResult::AmbiguousBaseSubobjects: {
1665 CXXBasePaths *Paths = Result.getBasePaths();
1666 QualType SubobjectType = Paths->front().back().Base->getType();
1667 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1668 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1669 << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001670
David Blaikie3bc93e32012-12-19 00:45:41 +00001671 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6e247262009-10-10 05:48:19 +00001672 while (isa<CXXMethodDecl>(*Found) &&
1673 cast<CXXMethodDecl>(*Found)->isStatic())
1674 ++Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001675
John McCall6e247262009-10-10 05:48:19 +00001676 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001677
John McCall6e247262009-10-10 05:48:19 +00001678 return true;
1679 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001680
John McCall6e247262009-10-10 05:48:19 +00001681 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001682 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1683 << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001684
John McCall6e247262009-10-10 05:48:19 +00001685 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001686 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001687 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1688 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001689 Path != PathEnd; ++Path) {
David Blaikie3bc93e32012-12-19 00:45:41 +00001690 Decl *D = Path->Decls.front();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001691 if (DeclsPrinted.insert(D).second)
1692 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1693 }
1694
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001695 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001696 }
1697
John McCall6e247262009-10-10 05:48:19 +00001698 case LookupResult::AmbiguousTagHiding: {
1699 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001700
John McCall6e247262009-10-10 05:48:19 +00001701 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1702
1703 LookupResult::iterator DI, DE = Result.end();
1704 for (DI = Result.begin(); DI != DE; ++DI)
1705 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1706 TagDecls.insert(TD);
1707 Diag(TD->getLocation(), diag::note_hidden_tag);
1708 }
1709
1710 for (DI = Result.begin(); DI != DE; ++DI)
1711 if (!isa<TagDecl>(*DI))
1712 Diag((*DI)->getLocation(), diag::note_hiding_object);
1713
1714 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001715 LookupResult::Filter F = Result.makeFilter();
1716 while (F.hasNext()) {
1717 if (TagDecls.count(F.next()))
1718 F.erase();
1719 }
1720 F.done();
John McCall6e247262009-10-10 05:48:19 +00001721
1722 return true;
1723 }
1724
1725 case LookupResult::AmbiguousReference: {
1726 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001727
John McCall6e247262009-10-10 05:48:19 +00001728 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1729 for (; DI != DE; ++DI)
1730 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001731
John McCall6e247262009-10-10 05:48:19 +00001732 return true;
1733 }
1734 }
1735
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001736 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001737}
Douglas Gregorfa047642009-02-04 00:32:51 +00001738
John McCallc7e04da2010-05-28 18:45:08 +00001739namespace {
1740 struct AssociatedLookup {
John McCall42f48fb2012-08-24 20:38:34 +00001741 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallc7e04da2010-05-28 18:45:08 +00001742 Sema::AssociatedNamespaceSet &Namespaces,
1743 Sema::AssociatedClassSet &Classes)
John McCall42f48fb2012-08-24 20:38:34 +00001744 : S(S), Namespaces(Namespaces), Classes(Classes),
1745 InstantiationLoc(InstantiationLoc) {
John McCallc7e04da2010-05-28 18:45:08 +00001746 }
1747
1748 Sema &S;
1749 Sema::AssociatedNamespaceSet &Namespaces;
1750 Sema::AssociatedClassSet &Classes;
John McCall42f48fb2012-08-24 20:38:34 +00001751 SourceLocation InstantiationLoc;
John McCallc7e04da2010-05-28 18:45:08 +00001752 };
1753}
1754
Mike Stump1eb44332009-09-09 15:08:12 +00001755static void
John McCallc7e04da2010-05-28 18:45:08 +00001756addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCall6ff07852009-08-07 22:18:02 +00001757
Douglas Gregor54022952010-04-30 07:08:38 +00001758static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1759 DeclContext *Ctx) {
1760 // Add the associated namespace for this class.
1761
1762 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1763 // be a locally scoped record.
1764
Sebastian Redl410c4f22010-08-31 20:53:31 +00001765 // We skip out of inline namespaces. The innermost non-inline namespace
1766 // contains all names of all its nested inline namespaces anyway, so we can
1767 // replace the entire inline namespace tree with its root.
1768 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1769 Ctx->isInlineNamespace())
Douglas Gregor54022952010-04-30 07:08:38 +00001770 Ctx = Ctx->getParent();
1771
John McCall6ff07852009-08-07 22:18:02 +00001772 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001773 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001774}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001775
Mike Stump1eb44332009-09-09 15:08:12 +00001776// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001777// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001778static void
John McCallc7e04da2010-05-28 18:45:08 +00001779addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1780 const TemplateArgument &Arg) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001781 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001782 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001783 switch (Arg.getKind()) {
1784 case TemplateArgument::Null:
1785 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001786
Douglas Gregor69be8d62009-07-08 07:51:57 +00001787 case TemplateArgument::Type:
1788 // [...] the namespaces and classes associated with the types of the
1789 // template arguments provided for template type parameters (excluding
1790 // template template parameters)
John McCallc7e04da2010-05-28 18:45:08 +00001791 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor69be8d62009-07-08 07:51:57 +00001792 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001793
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001794 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001795 case TemplateArgument::TemplateExpansion: {
Mike Stump1eb44332009-09-09 15:08:12 +00001796 // [...] the namespaces in which any template template arguments are
1797 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001798 // template template arguments are defined.
Douglas Gregora7fc9012011-01-05 18:58:31 +00001799 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump1eb44332009-09-09 15:08:12 +00001800 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001801 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001802 DeclContext *Ctx = ClassTemplate->getDeclContext();
1803 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001804 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001805 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001806 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001807 }
1808 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001809 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001810
Douglas Gregor788cd062009-11-11 01:00:40 +00001811 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001812 case TemplateArgument::Integral:
1813 case TemplateArgument::Expression:
Eli Friedmand7a6b162012-09-26 02:36:12 +00001814 case TemplateArgument::NullPtr:
Mike Stump1eb44332009-09-09 15:08:12 +00001815 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001816 // associated namespaces. ]
1817 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001818
Douglas Gregor69be8d62009-07-08 07:51:57 +00001819 case TemplateArgument::Pack:
1820 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1821 PEnd = Arg.pack_end();
1822 P != PEnd; ++P)
John McCallc7e04da2010-05-28 18:45:08 +00001823 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001824 break;
1825 }
1826}
1827
Douglas Gregorfa047642009-02-04 00:32:51 +00001828// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001829// argument-dependent lookup with an argument of class type
1830// (C++ [basic.lookup.koenig]p2).
1831static void
John McCallc7e04da2010-05-28 18:45:08 +00001832addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1833 CXXRecordDecl *Class) {
1834
1835 // Just silently ignore anything whose name is __va_list_tag.
1836 if (Class->getDeclName() == Result.S.VAListTagName)
1837 return;
1838
Douglas Gregorfa047642009-02-04 00:32:51 +00001839 // C++ [basic.lookup.koenig]p2:
1840 // [...]
1841 // -- If T is a class type (including unions), its associated
1842 // classes are: the class itself; the class of which it is a
1843 // member, if any; and its direct and indirect base
1844 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001845 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001846
1847 // Add the class of which it is a member, if any.
1848 DeclContext *Ctx = Class->getDeclContext();
1849 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001850 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001851 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001852 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001853
Douglas Gregorfa047642009-02-04 00:32:51 +00001854 // Add the class itself. If we've already seen this class, we don't
1855 // need to visit base classes.
John McCallc7e04da2010-05-28 18:45:08 +00001856 if (!Result.Classes.insert(Class))
Douglas Gregorfa047642009-02-04 00:32:51 +00001857 return;
1858
Mike Stump1eb44332009-09-09 15:08:12 +00001859 // -- If T is a template-id, its associated namespaces and classes are
1860 // the namespace in which the template is defined; for member
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001861 // templates, the member template's class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001862 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001863 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001864 // namespaces in which any template template arguments are defined; and
1865 // the classes in which any member templates used as template template
1866 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001867 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001868 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001869 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1870 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1871 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001872 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001873 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001874 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001875
Douglas Gregor69be8d62009-07-08 07:51:57 +00001876 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1877 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallc7e04da2010-05-28 18:45:08 +00001878 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001879 }
Mike Stump1eb44332009-09-09 15:08:12 +00001880
John McCall86ff3082010-02-04 22:26:26 +00001881 // Only recurse into base classes for complete types.
1882 if (!Class->hasDefinition()) {
John McCall42f48fb2012-08-24 20:38:34 +00001883 QualType type = Result.S.Context.getTypeDeclType(Class);
1884 if (Result.S.RequireCompleteType(Result.InstantiationLoc, type,
1885 /*no diagnostic*/ 0))
1886 return;
John McCall86ff3082010-02-04 22:26:26 +00001887 }
1888
Douglas Gregorfa047642009-02-04 00:32:51 +00001889 // Add direct and indirect base classes along with their associated
1890 // namespaces.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001891 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregorfa047642009-02-04 00:32:51 +00001892 Bases.push_back(Class);
1893 while (!Bases.empty()) {
1894 // Pop this class off the stack.
1895 Class = Bases.back();
1896 Bases.pop_back();
1897
1898 // Visit the base classes.
1899 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1900 BaseEnd = Class->bases_end();
1901 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001902 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001903 // In dependent contexts, we do ADL twice, and the first time around,
1904 // the base type might be a dependent TemplateSpecializationType, or a
1905 // TemplateTypeParmType. If that happens, simply ignore it.
1906 // FIXME: If we want to support export, we probably need to add the
1907 // namespace of the template in a TemplateSpecializationType, or even
1908 // the classes and namespaces of known non-dependent arguments.
1909 if (!BaseType)
1910 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001911 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001912 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001913 // Find the associated namespace for this base class.
1914 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallc7e04da2010-05-28 18:45:08 +00001915 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001916
1917 // Make sure we visit the bases of this base class.
1918 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1919 Bases.push_back(BaseDecl);
1920 }
1921 }
1922 }
1923}
1924
1925// \brief Add the associated classes and namespaces for
1926// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001927// (C++ [basic.lookup.koenig]p2).
1928static void
John McCallc7e04da2010-05-28 18:45:08 +00001929addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001930 // C++ [basic.lookup.koenig]p2:
1931 //
1932 // For each argument type T in the function call, there is a set
1933 // of zero or more associated namespaces and a set of zero or more
1934 // associated classes to be considered. The sets of namespaces and
1935 // classes is determined entirely by the types of the function
1936 // arguments (and the namespace of any template template
1937 // argument). Typedef names and using-declarations used to specify
1938 // the types do not contribute to this set. The sets of namespaces
1939 // and classes are determined in the following way:
Douglas Gregorfa047642009-02-04 00:32:51 +00001940
Chris Lattner5f9e2722011-07-23 10:55:15 +00001941 SmallVector<const Type *, 16> Queue;
John McCallfa4edcf2010-05-28 06:08:54 +00001942 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1943
Douglas Gregorfa047642009-02-04 00:32:51 +00001944 while (true) {
John McCallfa4edcf2010-05-28 06:08:54 +00001945 switch (T->getTypeClass()) {
1946
1947#define TYPE(Class, Base)
1948#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1949#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1950#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1951#define ABSTRACT_TYPE(Class, Base)
1952#include "clang/AST/TypeNodes.def"
1953 // T is canonical. We can also ignore dependent types because
1954 // we don't need to do ADL at the definition point, but if we
1955 // wanted to implement template export (or if we find some other
1956 // use for associated classes and namespaces...) this would be
1957 // wrong.
Douglas Gregorfa047642009-02-04 00:32:51 +00001958 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00001959
John McCallfa4edcf2010-05-28 06:08:54 +00001960 // -- If T is a pointer to U or an array of U, its associated
1961 // namespaces and classes are those associated with U.
1962 case Type::Pointer:
1963 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1964 continue;
1965 case Type::ConstantArray:
1966 case Type::IncompleteArray:
1967 case Type::VariableArray:
1968 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1969 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001970
John McCallfa4edcf2010-05-28 06:08:54 +00001971 // -- If T is a fundamental type, its associated sets of
1972 // namespaces and classes are both empty.
1973 case Type::Builtin:
1974 break;
1975
1976 // -- If T is a class type (including unions), its associated
1977 // classes are: the class itself; the class of which it is a
1978 // member, if any; and its direct and indirect base
1979 // classes. Its associated namespaces are the namespaces in
1980 // which its associated classes are defined.
1981 case Type::Record: {
1982 CXXRecordDecl *Class
1983 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001984 addAssociatedClassesAndNamespaces(Result, Class);
John McCallfa4edcf2010-05-28 06:08:54 +00001985 break;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001986 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00001987
John McCallfa4edcf2010-05-28 06:08:54 +00001988 // -- If T is an enumeration type, its associated namespace is
1989 // the namespace in which it is defined. If it is class
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001990 // member, its associated class is the member's class; else
John McCallfa4edcf2010-05-28 06:08:54 +00001991 // it has no associated class.
1992 case Type::Enum: {
1993 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001994
John McCallfa4edcf2010-05-28 06:08:54 +00001995 DeclContext *Ctx = Enum->getDeclContext();
1996 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001997 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001998
John McCallfa4edcf2010-05-28 06:08:54 +00001999 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00002000 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00002001
John McCallfa4edcf2010-05-28 06:08:54 +00002002 break;
2003 }
2004
2005 // -- If T is a function type, its associated namespaces and
2006 // classes are those associated with the function parameter
2007 // types and those associated with the return type.
2008 case Type::FunctionProto: {
2009 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2010 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
2011 ArgEnd = Proto->arg_type_end();
2012 Arg != ArgEnd; ++Arg)
2013 Queue.push_back(Arg->getTypePtr());
2014 // fallthrough
2015 }
2016 case Type::FunctionNoProto: {
2017 const FunctionType *FnType = cast<FunctionType>(T);
2018 T = FnType->getResultType().getTypePtr();
2019 continue;
2020 }
2021
2022 // -- If T is a pointer to a member function of a class X, its
2023 // associated namespaces and classes are those associated
2024 // with the function parameter types and return type,
2025 // together with those associated with X.
2026 //
2027 // -- If T is a pointer to a data member of class X, its
2028 // associated namespaces and classes are those associated
2029 // with the member type together with those associated with
2030 // X.
2031 case Type::MemberPointer: {
2032 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2033
2034 // Queue up the class type into which this points.
2035 Queue.push_back(MemberPtr->getClass());
2036
2037 // And directly continue with the pointee type.
2038 T = MemberPtr->getPointeeType().getTypePtr();
2039 continue;
2040 }
2041
2042 // As an extension, treat this like a normal pointer.
2043 case Type::BlockPointer:
2044 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2045 continue;
2046
2047 // References aren't covered by the standard, but that's such an
2048 // obvious defect that we cover them anyway.
2049 case Type::LValueReference:
2050 case Type::RValueReference:
2051 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2052 continue;
2053
2054 // These are fundamental types.
2055 case Type::Vector:
2056 case Type::ExtVector:
2057 case Type::Complex:
2058 break;
2059
Douglas Gregorf25760e2011-04-12 01:02:45 +00002060 // If T is an Objective-C object or interface type, or a pointer to an
2061 // object or interface type, the associated namespace is the global
2062 // namespace.
John McCallfa4edcf2010-05-28 06:08:54 +00002063 case Type::ObjCObject:
2064 case Type::ObjCInterface:
2065 case Type::ObjCObjectPointer:
Douglas Gregorf25760e2011-04-12 01:02:45 +00002066 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCallfa4edcf2010-05-28 06:08:54 +00002067 break;
Eli Friedmanb001de72011-10-06 23:00:33 +00002068
2069 // Atomic types are just wrappers; use the associations of the
2070 // contained type.
2071 case Type::Atomic:
2072 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2073 continue;
John McCallfa4edcf2010-05-28 06:08:54 +00002074 }
2075
2076 if (Queue.empty()) break;
2077 T = Queue.back();
2078 Queue.pop_back();
Douglas Gregorfa047642009-02-04 00:32:51 +00002079 }
Douglas Gregorfa047642009-02-04 00:32:51 +00002080}
2081
2082/// \brief Find the associated classes and namespaces for
2083/// argument-dependent lookup for a call with the given set of
2084/// arguments.
2085///
2086/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00002087/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00002088/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00002089void
John McCall42f48fb2012-08-24 20:38:34 +00002090Sema::FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
2091 llvm::ArrayRef<Expr *> Args,
Douglas Gregorfa047642009-02-04 00:32:51 +00002092 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00002093 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002094 AssociatedNamespaces.clear();
2095 AssociatedClasses.clear();
2096
John McCall42f48fb2012-08-24 20:38:34 +00002097 AssociatedLookup Result(*this, InstantiationLoc,
2098 AssociatedNamespaces, AssociatedClasses);
John McCallc7e04da2010-05-28 18:45:08 +00002099
Douglas Gregorfa047642009-02-04 00:32:51 +00002100 // C++ [basic.lookup.koenig]p2:
2101 // For each argument type T in the function call, there is a set
2102 // of zero or more associated namespaces and a set of zero or more
2103 // associated classes to be considered. The sets of namespaces and
2104 // classes is determined entirely by the types of the function
2105 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00002106 // argument).
Ahmed Charles13a140c2012-02-25 11:00:22 +00002107 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002108 Expr *Arg = Args[ArgIdx];
2109
2110 if (Arg->getType() != Context.OverloadTy) {
John McCallc7e04da2010-05-28 18:45:08 +00002111 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002112 continue;
2113 }
2114
2115 // [...] In addition, if the argument is the name or address of a
2116 // set of overloaded functions and/or function templates, its
2117 // associated classes and namespaces are the union of those
2118 // associated with each of the members of the set: the namespace
2119 // in which the function or function template is defined and the
2120 // classes and namespaces associated with its (non-dependent)
2121 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00002122 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00002123 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCall2de56d12010-08-25 11:45:40 +00002124 if (unaryOp->getOpcode() == UO_AddrOf)
John McCallba135432009-11-21 08:51:07 +00002125 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002126
John McCallc7e04da2010-05-28 18:45:08 +00002127 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2128 if (!ULE) continue;
John McCallba135432009-11-21 08:51:07 +00002129
John McCallc7e04da2010-05-28 18:45:08 +00002130 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2131 I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00002132 // Look through any using declarations to find the underlying function.
2133 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002134
Chandler Carruthbd647292009-12-29 06:17:27 +00002135 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2136 if (!FDecl)
2137 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002138
2139 // Add the classes and namespaces associated with the parameter
2140 // types and return type of this function.
John McCallc7e04da2010-05-28 18:45:08 +00002141 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002142 }
2143 }
2144}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002145
2146/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2147/// an acceptable non-member overloaded operator for a call whose
2148/// arguments have types T1 (and, if non-empty, T2). This routine
2149/// implements the check in C++ [over.match.oper]p3b2 concerning
2150/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00002151static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002152IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2153 QualType T1, QualType T2,
2154 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00002155 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2156 return true;
2157
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002158 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2159 return true;
2160
John McCall183700f2009-09-21 23:43:11 +00002161 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002162 if (Proto->getNumArgs() < 1)
2163 return false;
2164
2165 if (T1->isEnumeralType()) {
2166 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002167 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002168 return true;
2169 }
2170
2171 if (Proto->getNumArgs() < 2)
2172 return false;
2173
2174 if (!T2.isNull() && T2->isEnumeralType()) {
2175 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002176 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002177 return true;
2178 }
2179
2180 return false;
2181}
2182
John McCall7d384dd2009-11-18 07:57:50 +00002183NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002184 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00002185 LookupNameKind NameKind,
2186 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002187 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00002188 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00002189 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00002190}
2191
Douglas Gregor6e378de2009-04-23 23:18:26 +00002192/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002193ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002194 SourceLocation IdLoc,
2195 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002196 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002197 LookupObjCProtocolName, Redecl);
Douglas Gregor6e378de2009-04-23 23:18:26 +00002198 return cast_or_null<ObjCProtocolDecl>(D);
2199}
2200
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002201void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00002202 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00002203 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002204 // C++ [over.match.oper]p3:
2205 // -- The set of non-member candidates is the result of the
2206 // unqualified lookup of operator@ in the context of the
2207 // expression according to the usual rules for name lookup in
2208 // unqualified function calls (3.4.2) except that all member
2209 // functions are ignored. However, if no operand has a class
2210 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00002211 // that have a first parameter of type T1 or "reference to
2212 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002213 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00002214 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002215 // when T2 is an enumeration type, are candidate functions.
2216 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00002217 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2218 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002219
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002220 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2221
John McCallf36e02d2009-10-09 21:13:30 +00002222 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002223 return;
2224
2225 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2226 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002227 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2228 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002229 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002230 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00002231 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002232 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00002233 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00002234 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00002235 // later?
2236 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002237 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00002238 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002239 }
2240}
2241
Sean Huntc39b6bc2011-06-24 02:11:39 +00002242Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Sean Hunt308742c2011-06-04 04:32:43 +00002243 CXXSpecialMember SM,
2244 bool ConstArg,
2245 bool VolatileArg,
2246 bool RValueThis,
2247 bool ConstThis,
2248 bool VolatileThis) {
Richard Smithd0adeb62012-11-27 21:20:31 +00002249 assert(CanDeclareSpecialMemberFunction(RD) &&
Sean Hunt308742c2011-06-04 04:32:43 +00002250 "doing special member lookup into record that isn't fully complete");
Richard Smithd0adeb62012-11-27 21:20:31 +00002251 RD = RD->getDefinition();
Sean Hunt308742c2011-06-04 04:32:43 +00002252 if (RValueThis || ConstThis || VolatileThis)
2253 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2254 "constructors and destructors always have unqualified lvalue this");
2255 if (ConstArg || VolatileArg)
2256 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2257 "parameter-less special members can't have qualified arguments");
2258
2259 llvm::FoldingSetNodeID ID;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002260 ID.AddPointer(RD);
Sean Hunt308742c2011-06-04 04:32:43 +00002261 ID.AddInteger(SM);
2262 ID.AddInteger(ConstArg);
2263 ID.AddInteger(VolatileArg);
2264 ID.AddInteger(RValueThis);
2265 ID.AddInteger(ConstThis);
2266 ID.AddInteger(VolatileThis);
2267
2268 void *InsertPoint;
2269 SpecialMemberOverloadResult *Result =
2270 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2271
2272 // This was already cached
2273 if (Result)
2274 return Result;
2275
Sean Hunt30543582011-06-07 00:11:58 +00002276 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2277 Result = new (Result) SpecialMemberOverloadResult(ID);
Sean Hunt308742c2011-06-04 04:32:43 +00002278 SpecialMemberCache.InsertNode(Result, InsertPoint);
2279
2280 if (SM == CXXDestructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00002281 if (RD->needsImplicitDestructor())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002282 DeclareImplicitDestructor(RD);
2283 CXXDestructorDecl *DD = RD->getDestructor();
Sean Hunt308742c2011-06-04 04:32:43 +00002284 assert(DD && "record without a destructor");
2285 Result->setMethod(DD);
Richard Smith6c4c36c2012-03-30 20:53:28 +00002286 Result->setKind(DD->isDeleted() ?
2287 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith704c8f72012-04-20 18:46:14 +00002288 SpecialMemberOverloadResult::Success);
Sean Hunt308742c2011-06-04 04:32:43 +00002289 return Result;
2290 }
2291
Sean Huntb320e0c2011-06-10 03:50:41 +00002292 // Prepare for overload resolution. Here we construct a synthetic argument
2293 // if necessary and make sure that implicit functions are declared.
Sean Huntc39b6bc2011-06-24 02:11:39 +00002294 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Sean Huntb320e0c2011-06-10 03:50:41 +00002295 DeclarationName Name;
2296 Expr *Arg = 0;
2297 unsigned NumArgs;
2298
Richard Smith704c8f72012-04-20 18:46:14 +00002299 QualType ArgType = CanTy;
2300 ExprValueKind VK = VK_LValue;
2301
Sean Huntb320e0c2011-06-10 03:50:41 +00002302 if (SM == CXXDefaultConstructor) {
2303 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2304 NumArgs = 0;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002305 if (RD->needsImplicitDefaultConstructor())
2306 DeclareImplicitDefaultConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002307 } else {
2308 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2309 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smithe5411b72012-12-01 02:35:44 +00002310 if (RD->needsImplicitCopyConstructor())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002311 DeclareImplicitCopyConstructor(RD);
Richard Smith80ad52f2013-01-02 11:42:31 +00002312 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002313 DeclareImplicitMoveConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002314 } else {
2315 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smithe5411b72012-12-01 02:35:44 +00002316 if (RD->needsImplicitCopyAssignment())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002317 DeclareImplicitCopyAssignment(RD);
Richard Smith80ad52f2013-01-02 11:42:31 +00002318 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002319 DeclareImplicitMoveAssignment(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002320 }
2321
Sean Huntb320e0c2011-06-10 03:50:41 +00002322 if (ConstArg)
2323 ArgType.addConst();
2324 if (VolatileArg)
2325 ArgType.addVolatile();
2326
2327 // This isn't /really/ specified by the standard, but it's implied
2328 // we should be working from an RValue in the case of move to ensure
2329 // that we prefer to bind to rvalue references, and an LValue in the
2330 // case of copy to ensure we don't bind to rvalue references.
2331 // Possibly an XValue is actually correct in the case of move, but
2332 // there is no semantic difference for class types in this restricted
2333 // case.
Sean Huntab183df2011-06-22 22:13:13 +00002334 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Sean Huntb320e0c2011-06-10 03:50:41 +00002335 VK = VK_LValue;
2336 else
2337 VK = VK_RValue;
Richard Smith704c8f72012-04-20 18:46:14 +00002338 }
Sean Huntb320e0c2011-06-10 03:50:41 +00002339
Richard Smith704c8f72012-04-20 18:46:14 +00002340 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2341
2342 if (SM != CXXDefaultConstructor) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002343 NumArgs = 1;
Richard Smith704c8f72012-04-20 18:46:14 +00002344 Arg = &FakeArg;
Sean Huntb320e0c2011-06-10 03:50:41 +00002345 }
2346
2347 // Create the object argument
2348 QualType ThisTy = CanTy;
2349 if (ConstThis)
2350 ThisTy.addConst();
2351 if (VolatileThis)
2352 ThisTy.addVolatile();
Sean Hunt4cc12c62011-06-23 00:26:20 +00002353 Expr::Classification Classification =
Richard Smith704c8f72012-04-20 18:46:14 +00002354 OpaqueValueExpr(SourceLocation(), ThisTy,
2355 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Sean Huntb320e0c2011-06-10 03:50:41 +00002356
2357 // Now we perform lookup on the name we computed earlier and do overload
2358 // resolution. Lookup is only performed directly into the class since there
2359 // will always be a (possibly implicit) declaration to shadow any others.
2360 OverloadCandidateSet OCS((SourceLocation()));
David Blaikie3bc93e32012-12-19 00:45:41 +00002361 DeclContext::lookup_result R = RD->lookup(Name);
Sean Huntb320e0c2011-06-10 03:50:41 +00002362
David Blaikie3bc93e32012-12-19 00:45:41 +00002363 assert(!R.empty() &&
Sean Huntb320e0c2011-06-10 03:50:41 +00002364 "lookup for a constructor or assignment operator was empty");
David Blaikie3bc93e32012-12-19 00:45:41 +00002365 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
Sean Huntc39b6bc2011-06-24 02:11:39 +00002366 Decl *Cand = *I;
Sean Hunt4cc12c62011-06-23 00:26:20 +00002367
Sean Huntc39b6bc2011-06-24 02:11:39 +00002368 if (Cand->isInvalidDecl())
Sean Huntb320e0c2011-06-10 03:50:41 +00002369 continue;
2370
Sean Huntc39b6bc2011-06-24 02:11:39 +00002371 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2372 // FIXME: [namespace.udecl]p15 says that we should only consider a
2373 // using declaration here if it does not match a declaration in the
2374 // derived class. We do not implement this correctly in other cases
2375 // either.
2376 Cand = U->getTargetDecl();
2377
2378 if (Cand->isInvalidDecl())
2379 continue;
2380 }
2381
2382 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002383 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Sean Huntc39b6bc2011-06-24 02:11:39 +00002384 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002385 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2386 OCS, true);
Sean Hunt4cc12c62011-06-23 00:26:20 +00002387 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00002388 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2389 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Sean Hunt431a1cb2011-06-22 02:58:46 +00002390 } else if (FunctionTemplateDecl *Tmpl =
Sean Huntc39b6bc2011-06-24 02:11:39 +00002391 dyn_cast<FunctionTemplateDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002392 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2393 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charles13a140c2012-02-25 11:00:22 +00002394 RD, 0, ThisTy, Classification,
2395 llvm::makeArrayRef(&Arg, NumArgs),
Sean Hunt4cc12c62011-06-23 00:26:20 +00002396 OCS, true);
2397 else
2398 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charles13a140c2012-02-25 11:00:22 +00002399 0, llvm::makeArrayRef(&Arg, NumArgs),
2400 OCS, true);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002401 } else {
2402 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Sean Huntb320e0c2011-06-10 03:50:41 +00002403 }
2404 }
2405
2406 OverloadCandidateSet::iterator Best;
2407 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2408 case OR_Success:
2409 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith704c8f72012-04-20 18:46:14 +00002410 Result->setKind(SpecialMemberOverloadResult::Success);
Sean Huntb320e0c2011-06-10 03:50:41 +00002411 break;
2412
2413 case OR_Deleted:
2414 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith6c4c36c2012-03-30 20:53:28 +00002415 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Sean Huntb320e0c2011-06-10 03:50:41 +00002416 break;
2417
2418 case OR_Ambiguous:
Richard Smith6c4c36c2012-03-30 20:53:28 +00002419 Result->setMethod(0);
2420 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2421 break;
2422
Sean Huntb320e0c2011-06-10 03:50:41 +00002423 case OR_No_Viable_Function:
2424 Result->setMethod(0);
Richard Smith6c4c36c2012-03-30 20:53:28 +00002425 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Sean Huntb320e0c2011-06-10 03:50:41 +00002426 break;
2427 }
2428
2429 return Result;
2430}
2431
2432/// \brief Look up the default constructor for the given class.
2433CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Sean Huntc530d172011-06-10 04:44:37 +00002434 SpecialMemberOverloadResult *Result =
Sean Huntb320e0c2011-06-10 03:50:41 +00002435 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2436 false, false);
2437
2438 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Sean Hunt308742c2011-06-04 04:32:43 +00002439}
2440
Sean Hunt661c67a2011-06-21 23:42:56 +00002441/// \brief Look up the copying constructor for the given class.
2442CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith704c8f72012-04-20 18:46:14 +00002443 unsigned Quals) {
Sean Huntc530d172011-06-10 04:44:37 +00002444 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2445 "non-const, non-volatile qualifiers for copy ctor arg");
2446 SpecialMemberOverloadResult *Result =
2447 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2448 Quals & Qualifiers::Volatile, false, false, false);
2449
Sean Huntc530d172011-06-10 04:44:37 +00002450 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2451}
2452
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002453/// \brief Look up the moving constructor for the given class.
Richard Smith6a06e5f2012-07-18 03:36:00 +00002454CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2455 unsigned Quals) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002456 SpecialMemberOverloadResult *Result =
Richard Smith6a06e5f2012-07-18 03:36:00 +00002457 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2458 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002459
2460 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2461}
2462
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002463/// \brief Look up the constructors for the given class.
2464DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002465 // If the implicit constructors have not yet been declared, do so now.
Richard Smithd0adeb62012-11-27 21:20:31 +00002466 if (CanDeclareSpecialMemberFunction(Class)) {
Sean Huntcdee3fe2011-05-11 22:34:38 +00002467 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002468 DeclareImplicitDefaultConstructor(Class);
Richard Smithe5411b72012-12-01 02:35:44 +00002469 if (Class->needsImplicitCopyConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002470 DeclareImplicitCopyConstructor(Class);
Richard Smith80ad52f2013-01-02 11:42:31 +00002471 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002472 DeclareImplicitMoveConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +00002473 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002474
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002475 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2476 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2477 return Class->lookup(Name);
2478}
2479
Sean Hunt661c67a2011-06-21 23:42:56 +00002480/// \brief Look up the copying assignment operator for the given class.
2481CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2482 unsigned Quals, bool RValueThis,
Richard Smith704c8f72012-04-20 18:46:14 +00002483 unsigned ThisQuals) {
Sean Hunt661c67a2011-06-21 23:42:56 +00002484 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2485 "non-const, non-volatile qualifiers for copy assignment arg");
2486 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2487 "non-const, non-volatile qualifiers for copy assignment this");
2488 SpecialMemberOverloadResult *Result =
2489 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2490 Quals & Qualifiers::Volatile, RValueThis,
2491 ThisQuals & Qualifiers::Const,
2492 ThisQuals & Qualifiers::Volatile);
2493
Sean Hunt661c67a2011-06-21 23:42:56 +00002494 return Result->getMethod();
2495}
2496
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002497/// \brief Look up the moving assignment operator for the given class.
2498CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith6a06e5f2012-07-18 03:36:00 +00002499 unsigned Quals,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002500 bool RValueThis,
2501 unsigned ThisQuals) {
2502 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2503 "non-const, non-volatile qualifiers for copy assignment this");
2504 SpecialMemberOverloadResult *Result =
Richard Smith6a06e5f2012-07-18 03:36:00 +00002505 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2506 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002507 ThisQuals & Qualifiers::Const,
2508 ThisQuals & Qualifiers::Volatile);
2509
2510 return Result->getMethod();
2511}
2512
Douglas Gregordb89f282010-07-01 22:47:18 +00002513/// \brief Look for the destructor of the given class.
2514///
Sean Huntc5c9b532011-06-03 21:10:40 +00002515/// During semantic analysis, this routine should be used in lieu of
2516/// CXXRecordDecl::getDestructor().
Douglas Gregordb89f282010-07-01 22:47:18 +00002517///
2518/// \returns The destructor for this class.
2519CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Sean Hunt308742c2011-06-04 04:32:43 +00002520 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2521 false, false, false,
2522 false, false)->getMethod());
Douglas Gregordb89f282010-07-01 22:47:18 +00002523}
2524
Richard Smith36f5cfe2012-03-09 08:00:36 +00002525/// LookupLiteralOperator - Determine which literal operator should be used for
2526/// a user-defined literal, per C++11 [lex.ext].
2527///
2528/// Normal overload resolution is not used to select which literal operator to
2529/// call for a user-defined literal. Look up the provided literal operator name,
2530/// and filter the results to the appropriate set for the given argument types.
2531Sema::LiteralOperatorLookupResult
2532Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2533 ArrayRef<QualType> ArgTys,
2534 bool AllowRawAndTemplate) {
2535 LookupName(R, S);
2536 assert(R.getResultKind() != LookupResult::Ambiguous &&
2537 "literal operator lookup can't be ambiguous");
2538
2539 // Filter the lookup results appropriately.
2540 LookupResult::Filter F = R.makeFilter();
2541
2542 bool FoundTemplate = false;
2543 bool FoundRaw = false;
2544 bool FoundExactMatch = false;
2545
2546 while (F.hasNext()) {
2547 Decl *D = F.next();
2548 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2549 D = USD->getTargetDecl();
2550
2551 bool IsTemplate = isa<FunctionTemplateDecl>(D);
2552 bool IsRaw = false;
2553 bool IsExactMatch = false;
2554
2555 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2556 if (FD->getNumParams() == 1 &&
2557 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2558 IsRaw = true;
Richard Smitha121eb32013-01-15 07:12:59 +00002559 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smith36f5cfe2012-03-09 08:00:36 +00002560 IsExactMatch = true;
2561 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2562 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2563 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2564 IsExactMatch = false;
2565 break;
2566 }
2567 }
2568 }
2569 }
2570
2571 if (IsExactMatch) {
2572 FoundExactMatch = true;
2573 AllowRawAndTemplate = false;
2574 if (FoundRaw || FoundTemplate) {
2575 // Go through again and remove the raw and template decls we've
2576 // already found.
2577 F.restart();
2578 FoundRaw = FoundTemplate = false;
2579 }
2580 } else if (AllowRawAndTemplate && (IsTemplate || IsRaw)) {
2581 FoundTemplate |= IsTemplate;
2582 FoundRaw |= IsRaw;
2583 } else {
2584 F.erase();
2585 }
2586 }
2587
2588 F.done();
2589
2590 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2591 // parameter type, that is used in preference to a raw literal operator
2592 // or literal operator template.
2593 if (FoundExactMatch)
2594 return LOLR_Cooked;
2595
2596 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2597 // operator template, but not both.
2598 if (FoundRaw && FoundTemplate) {
2599 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
2600 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2601 Decl *D = *I;
2602 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2603 D = USD->getTargetDecl();
2604 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2605 D = FunTmpl->getTemplatedDecl();
2606 NoteOverloadCandidate(cast<FunctionDecl>(D));
2607 }
2608 return LOLR_Error;
2609 }
2610
2611 if (FoundRaw)
2612 return LOLR_Raw;
2613
2614 if (FoundTemplate)
2615 return LOLR_Template;
2616
2617 // Didn't find anything we could use.
2618 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2619 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
2620 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRawAndTemplate;
2621 return LOLR_Error;
2622}
2623
John McCall7edb5fd2010-01-26 07:16:45 +00002624void ADLResult::insert(NamedDecl *New) {
2625 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2626
2627 // If we haven't yet seen a decl for this key, or the last decl
2628 // was exactly this one, we're done.
2629 if (Old == 0 || Old == New) {
2630 Old = New;
2631 return;
2632 }
2633
2634 // Otherwise, decide which is a more recent redeclaration.
2635 FunctionDecl *OldFD, *NewFD;
2636 if (isa<FunctionTemplateDecl>(New)) {
2637 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2638 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2639 } else {
2640 OldFD = cast<FunctionDecl>(Old);
2641 NewFD = cast<FunctionDecl>(New);
2642 }
2643
2644 FunctionDecl *Cursor = NewFD;
2645 while (true) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002646 Cursor = Cursor->getPreviousDecl();
John McCall7edb5fd2010-01-26 07:16:45 +00002647
2648 // If we got to the end without finding OldFD, OldFD is the newer
2649 // declaration; leave things as they are.
2650 if (!Cursor) return;
2651
2652 // If we do find OldFD, then NewFD is newer.
2653 if (Cursor == OldFD) break;
2654
2655 // Otherwise, keep looking.
2656 }
2657
2658 Old = New;
2659}
2660
Sebastian Redl644be852009-10-23 19:23:15 +00002661void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00002662 SourceLocation Loc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002663 llvm::ArrayRef<Expr *> Args,
Richard Smithb1502bc2012-10-18 17:56:02 +00002664 ADLResult &Result) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002665 // Find all of the associated namespaces and classes based on the
2666 // arguments we have.
2667 AssociatedNamespaceSet AssociatedNamespaces;
2668 AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00002669 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCall6ff07852009-08-07 22:18:02 +00002670 AssociatedNamespaces,
2671 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002672
Sebastian Redl644be852009-10-23 19:23:15 +00002673 QualType T1, T2;
2674 if (Operator) {
2675 T1 = Args[0]->getType();
Ahmed Charles13a140c2012-02-25 11:00:22 +00002676 if (Args.size() >= 2)
Sebastian Redl644be852009-10-23 19:23:15 +00002677 T2 = Args[1]->getType();
2678 }
2679
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002680 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002681 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2682 // and let Y be the lookup set produced by argument dependent
2683 // lookup (defined as follows). If X contains [...] then Y is
2684 // empty. Otherwise Y is the set of declarations found in the
2685 // namespaces associated with the argument types as described
2686 // below. The set of declarations found by the lookup of the name
2687 // is the union of X and Y.
2688 //
2689 // Here, we compute Y and add its members to the overloaded
2690 // candidate set.
2691 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002692 NSEnd = AssociatedNamespaces.end();
2693 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002694 // When considering an associated namespace, the lookup is the
2695 // same as the lookup performed when the associated namespace is
2696 // used as a qualifier (3.4.3.2) except that:
2697 //
2698 // -- Any using-directives in the associated namespace are
2699 // ignored.
2700 //
John McCall6ff07852009-08-07 22:18:02 +00002701 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002702 // associated classes are visible within their respective
2703 // namespaces even if they are not visible during an ordinary
2704 // lookup (11.4).
David Blaikie3bc93e32012-12-19 00:45:41 +00002705 DeclContext::lookup_result R = (*NS)->lookup(Name);
2706 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
2707 ++I) {
John McCall6e266892010-01-26 03:27:55 +00002708 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00002709 // If the only declaration here is an ordinary friend, consider
2710 // it only if it was declared in an associated classes.
2711 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00002712 DeclContext *LexDC = D->getLexicalDeclContext();
2713 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2714 continue;
2715 }
Mike Stump1eb44332009-09-09 15:08:12 +00002716
John McCalla113e722010-01-26 06:04:06 +00002717 if (isa<UsingShadowDecl>(D))
2718 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00002719
John McCalla113e722010-01-26 06:04:06 +00002720 if (isa<FunctionDecl>(D)) {
2721 if (Operator &&
2722 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2723 T1, T2, Context))
2724 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00002725 } else if (!isa<FunctionTemplateDecl>(D))
2726 continue;
2727
2728 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00002729 }
2730 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002731}
Douglas Gregor546be3c2009-12-30 17:04:44 +00002732
2733//----------------------------------------------------------------------------
2734// Search for all visible declarations.
2735//----------------------------------------------------------------------------
2736VisibleDeclConsumer::~VisibleDeclConsumer() { }
2737
2738namespace {
2739
2740class ShadowContextRAII;
2741
2742class VisibleDeclsRecord {
2743public:
2744 /// \brief An entry in the shadow map, which is optimized to store a
2745 /// single declaration (the common case) but can also store a list
2746 /// of declarations.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002747 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002748
2749private:
2750 /// \brief A mapping from declaration names to the declarations that have
2751 /// this name within a particular scope.
2752 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2753
2754 /// \brief A list of shadow maps, which is used to model name hiding.
2755 std::list<ShadowMap> ShadowMaps;
2756
2757 /// \brief The declaration contexts we have already visited.
2758 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2759
2760 friend class ShadowContextRAII;
2761
2762public:
2763 /// \brief Determine whether we have already visited this context
2764 /// (and, if not, note that we are going to visit that context now).
2765 bool visitedContext(DeclContext *Ctx) {
2766 return !VisitedContexts.insert(Ctx);
2767 }
2768
Douglas Gregor8071e422010-08-15 06:18:01 +00002769 bool alreadyVisitedContext(DeclContext *Ctx) {
2770 return VisitedContexts.count(Ctx);
2771 }
2772
Douglas Gregor546be3c2009-12-30 17:04:44 +00002773 /// \brief Determine whether the given declaration is hidden in the
2774 /// current scope.
2775 ///
2776 /// \returns the declaration that hides the given declaration, or
2777 /// NULL if no such declaration exists.
2778 NamedDecl *checkHidden(NamedDecl *ND);
2779
2780 /// \brief Add a declaration to the current shadow map.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002781 void add(NamedDecl *ND) {
2782 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2783 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002784};
2785
2786/// \brief RAII object that records when we've entered a shadow context.
2787class ShadowContextRAII {
2788 VisibleDeclsRecord &Visible;
2789
2790 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2791
2792public:
2793 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2794 Visible.ShadowMaps.push_back(ShadowMap());
2795 }
2796
2797 ~ShadowContextRAII() {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002798 Visible.ShadowMaps.pop_back();
2799 }
2800};
2801
2802} // end anonymous namespace
2803
Douglas Gregor546be3c2009-12-30 17:04:44 +00002804NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002805 // Look through using declarations.
2806 ND = ND->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002807
Douglas Gregor546be3c2009-12-30 17:04:44 +00002808 unsigned IDNS = ND->getIdentifierNamespace();
2809 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2810 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2811 SM != SMEnd; ++SM) {
2812 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2813 if (Pos == SM->end())
2814 continue;
2815
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002816 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00002817 IEnd = Pos->second.end();
2818 I != IEnd; ++I) {
2819 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002820 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002821 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor546be3c2009-12-30 17:04:44 +00002822 Decl::IDNS_ObjCProtocol)))
2823 continue;
2824
2825 // Protocols are in distinct namespaces from everything else.
2826 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2827 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2828 (*I)->getIdentifierNamespace() != IDNS)
2829 continue;
2830
Douglas Gregor0cc84042010-01-14 15:47:35 +00002831 // Functions and function templates in the same scope overload
2832 // rather than hide. FIXME: Look for hiding based on function
2833 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002834 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002835 ND->isFunctionOrFunctionTemplate() &&
2836 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002837 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002838
Douglas Gregor546be3c2009-12-30 17:04:44 +00002839 // We've found a declaration that hides this one.
2840 return *I;
2841 }
2842 }
2843
2844 return 0;
2845}
2846
2847static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2848 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002849 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002850 VisibleDeclConsumer &Consumer,
2851 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00002852 if (!Ctx)
2853 return;
2854
Douglas Gregor546be3c2009-12-30 17:04:44 +00002855 // Make sure we don't visit the same context twice.
2856 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2857 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002858
Douglas Gregor4923aa22010-07-02 20:37:36 +00002859 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2860 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2861
Douglas Gregor546be3c2009-12-30 17:04:44 +00002862 // Enumerate all of the results in this context.
Nick Lewycky173a37a2012-04-03 21:44:08 +00002863 for (DeclContext::all_lookups_iterator L = Ctx->lookups_begin(),
2864 LEnd = Ctx->lookups_end();
2865 L != LEnd; ++L) {
David Blaikie3bc93e32012-12-19 00:45:41 +00002866 DeclContext::lookup_result R = *L;
2867 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
2868 ++I) {
2869 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) {
Douglas Gregor55368912011-12-14 16:03:29 +00002870 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00002871 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002872 Visited.add(ND);
2873 }
Douglas Gregor70c23352010-12-09 21:44:02 +00002874 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002875 }
2876 }
2877
2878 // Traverse using directives for qualified name lookup.
2879 if (QualifiedNameLookup) {
2880 ShadowContextRAII Shadow(Visited);
2881 DeclContext::udir_iterator I, E;
2882 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002883 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002884 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002885 }
2886 }
2887
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002888 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002889 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00002890 if (!Record->hasDefinition())
2891 return;
2892
Douglas Gregor546be3c2009-12-30 17:04:44 +00002893 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2894 BEnd = Record->bases_end();
2895 B != BEnd; ++B) {
2896 QualType BaseType = B->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002897
Douglas Gregor546be3c2009-12-30 17:04:44 +00002898 // Don't look into dependent bases, because name lookup can't look
2899 // there anyway.
2900 if (BaseType->isDependentType())
2901 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002902
Douglas Gregor546be3c2009-12-30 17:04:44 +00002903 const RecordType *Record = BaseType->getAs<RecordType>();
2904 if (!Record)
2905 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002906
Douglas Gregor546be3c2009-12-30 17:04:44 +00002907 // FIXME: It would be nice to be able to determine whether referencing
2908 // a particular member would be ambiguous. For example, given
2909 //
2910 // struct A { int member; };
2911 // struct B { int member; };
2912 // struct C : A, B { };
2913 //
2914 // void f(C *c) { c->### }
2915 //
2916 // accessing 'member' would result in an ambiguity. However, we
2917 // could be smart enough to qualify the member with the base
2918 // class, e.g.,
2919 //
2920 // c->B::member
2921 //
2922 // or
2923 //
2924 // c->A::member
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002925
Douglas Gregor546be3c2009-12-30 17:04:44 +00002926 // Find results in this base class (and its bases).
2927 ShadowContextRAII Shadow(Visited);
2928 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002929 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002930 }
2931 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002932
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002933 // Traverse the contexts of Objective-C classes.
2934 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2935 // Traverse categories.
Douglas Gregord3297242013-01-16 23:00:23 +00002936 for (ObjCInterfaceDecl::visible_categories_iterator
2937 Cat = IFace->visible_categories_begin(),
2938 CatEnd = IFace->visible_categories_end();
2939 Cat != CatEnd; ++Cat) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002940 ShadowContextRAII Shadow(Visited);
Douglas Gregord3297242013-01-16 23:00:23 +00002941 LookupVisibleDecls(*Cat, Result, QualifiedNameLookup, false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002942 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002943 }
2944
2945 // Traverse protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00002946 for (ObjCInterfaceDecl::all_protocol_iterator
2947 I = IFace->all_referenced_protocol_begin(),
2948 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002949 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002950 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002951 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002952 }
2953
2954 // Traverse the superclass.
2955 if (IFace->getSuperClass()) {
2956 ShadowContextRAII Shadow(Visited);
2957 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002958 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002959 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002960
Douglas Gregorc220a182010-04-19 18:02:19 +00002961 // If there is an implementation, traverse it. We do this to find
2962 // synthesized ivars.
2963 if (IFace->getImplementation()) {
2964 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002965 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky893a6ea2012-04-03 20:26:45 +00002966 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregorc220a182010-04-19 18:02:19 +00002967 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002968 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2969 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2970 E = Protocol->protocol_end(); I != E; ++I) {
2971 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002972 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002973 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002974 }
2975 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2976 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2977 E = Category->protocol_end(); I != E; ++I) {
2978 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002979 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002980 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002981 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002982
Douglas Gregorc220a182010-04-19 18:02:19 +00002983 // If there is an implementation, traverse it.
2984 if (Category->getImplementation()) {
2985 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002986 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00002987 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002988 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002989 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002990}
2991
2992static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2993 UnqualUsingDirectiveSet &UDirs,
2994 VisibleDeclConsumer &Consumer,
2995 VisibleDeclsRecord &Visited) {
2996 if (!S)
2997 return;
2998
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002999 if (!S->getEntity() ||
3000 (!S->getParent() &&
Douglas Gregor8071e422010-08-15 06:18:01 +00003001 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor539c5c32010-01-07 00:31:29 +00003002 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
3003 // Walk through the declarations in this Scope.
3004 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
3005 D != DEnd; ++D) {
John McCalld226f652010-08-21 09:40:31 +00003006 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor55368912011-12-14 16:03:29 +00003007 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00003008 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00003009 Visited.add(ND);
3010 }
3011 }
3012 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003013
Douglas Gregor711be1e2010-03-15 14:33:29 +00003014 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00003015 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00003016 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003017 // Look into this scope's declaration context, along with any of its
3018 // parent lookup contexts (e.g., enclosing classes), up to the point
3019 // where we hit the context stored in the next outer scope.
3020 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00003021 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003022
Douglas Gregordbdf5e72010-03-15 15:26:48 +00003023 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003024 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003025 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3026 if (Method->isInstanceMethod()) {
3027 // For instance methods, look for ivars in the method's interface.
3028 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3029 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregorca45da02010-11-02 20:36:02 +00003030 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003031 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Fariborz Jahanian8697d302011-08-31 22:24:06 +00003032 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorca45da02010-11-02 20:36:02 +00003033 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003034 }
3035
3036 // We've already performed all of the name lookup that we need
3037 // to for Objective-C methods; the next context will be the
3038 // outer scope.
3039 break;
3040 }
3041
Douglas Gregor546be3c2009-12-30 17:04:44 +00003042 if (Ctx->isFunctionOrMethod())
3043 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003044
3045 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003046 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003047 }
3048 } else if (!S->getParent()) {
3049 // Look into the translation unit scope. We walk through the translation
3050 // unit's declaration context, because the Scope itself won't have all of
3051 // the declarations if we loaded a precompiled header.
3052 // FIXME: We would like the translation unit's Scope object to point to the
3053 // translation unit, so we don't need this special "if" branch. However,
3054 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003055 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003056 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00003057 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003058 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003059 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003060 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003061 }
3062
Douglas Gregor546be3c2009-12-30 17:04:44 +00003063 if (Entity) {
3064 // Lookup visible declarations in any namespaces found by using
3065 // directives.
3066 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
3067 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
3068 for (; UI != UEnd; ++UI)
3069 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003070 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003071 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003072 }
3073
3074 // Lookup names in the parent scope.
3075 ShadowContextRAII Shadow(Visited);
3076 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3077}
3078
3079void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00003080 VisibleDeclConsumer &Consumer,
3081 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003082 // Determine the set of using directives available during
3083 // unqualified name lookup.
3084 Scope *Initial = S;
3085 UnqualUsingDirectiveSet UDirs;
David Blaikie4e4d0842012-03-11 07:00:24 +00003086 if (getLangOpts().CPlusPlus) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003087 // Find the first namespace or translation-unit scope.
3088 while (S && !isNamespaceOrTranslationUnitScope(S))
3089 S = S->getParent();
3090
3091 UDirs.visitScopeChain(Initial, S);
3092 }
3093 UDirs.done();
3094
3095 // Look for visible declarations.
3096 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3097 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003098 if (!IncludeGlobalScope)
3099 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003100 ShadowContextRAII Shadow(Visited);
3101 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3102}
3103
3104void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00003105 VisibleDeclConsumer &Consumer,
3106 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003107 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3108 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003109 if (!IncludeGlobalScope)
3110 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003111 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003112 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003113 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003114}
3115
Chris Lattner4ae493c2011-02-18 02:08:43 +00003116/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara67843042011-03-05 18:21:20 +00003117/// If GnuLabelLoc is a valid source location, then this is a definition
3118/// of an __label__ label name, otherwise it is a normal label definition
3119/// or use.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003120LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara67843042011-03-05 18:21:20 +00003121 SourceLocation GnuLabelLoc) {
Chris Lattner337e5502011-02-18 01:27:55 +00003122 // Do a lookup to see if we have a label with this name already.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003123 NamedDecl *Res = 0;
Abramo Bagnara67843042011-03-05 18:21:20 +00003124
3125 if (GnuLabelLoc.isValid()) {
3126 // Local label definitions always shadow existing labels.
3127 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3128 Scope *S = CurScope;
3129 PushOnScopeChains(Res, S, true);
3130 return cast<LabelDecl>(Res);
3131 }
3132
3133 // Not a GNU local label.
3134 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3135 // If we found a label, check to see if it is in the same context as us.
3136 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattner337e5502011-02-18 01:27:55 +00003137 if (Res && Res->getDeclContext() != CurContext)
3138 Res = 0;
Chris Lattner337e5502011-02-18 01:27:55 +00003139 if (Res == 0) {
3140 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara67843042011-03-05 18:21:20 +00003141 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3142 Scope *S = CurScope->getFnParent();
Chris Lattnerfebb5b82011-02-18 21:16:39 +00003143 assert(S && "Not in a function?");
3144 PushOnScopeChains(Res, S, true);
Chris Lattner337e5502011-02-18 01:27:55 +00003145 }
Chris Lattner337e5502011-02-18 01:27:55 +00003146 return cast<LabelDecl>(Res);
3147}
3148
3149//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003150// Typo correction
Chris Lattner337e5502011-02-18 01:27:55 +00003151//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003152
3153namespace {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003154
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003155typedef SmallVector<TypoCorrection, 1> TypoResultList;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003156typedef llvm::StringMap<TypoResultList, llvm::BumpPtrAllocator> TypoResultsMap;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003157typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003158
3159static const unsigned MaxTypoDistanceResultSets = 5;
3160
Douglas Gregor546be3c2009-12-30 17:04:44 +00003161class TypoCorrectionConsumer : public VisibleDeclConsumer {
3162 /// \brief The name written that is a typo in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003163 StringRef Typo;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003164
3165 /// \brief The results found that have the smallest edit distance
3166 /// found (so far) with the typo name.
Douglas Gregore24b5752010-10-14 20:34:08 +00003167 ///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003168 /// The pointer value being set to the current DeclContext indicates
3169 /// whether there is a keyword with this name.
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003170 TypoEditDistanceMap CorrectionResults;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003171
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003172 Sema &SemaRef;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003173
Douglas Gregor546be3c2009-12-30 17:04:44 +00003174public:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003175 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003176 : Typo(Typo->getName()),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003177 SemaRef(SemaRef) { }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003178
Erik Verbruggend1205962011-10-06 07:27:49 +00003179 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3180 bool InBaseClass);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003181 void FoundName(StringRef Name);
3182 void addKeywordResult(StringRef Keyword);
3183 void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003184 NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003185 void addCorrection(TypoCorrection Correction);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003186
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003187 typedef TypoResultsMap::iterator result_iterator;
3188 typedef TypoEditDistanceMap::iterator distance_iterator;
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003189 distance_iterator begin() { return CorrectionResults.begin(); }
3190 distance_iterator end() { return CorrectionResults.end(); }
3191 void erase(distance_iterator I) { CorrectionResults.erase(I); }
3192 unsigned size() const { return CorrectionResults.size(); }
3193 bool empty() const { return CorrectionResults.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003194
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003195 TypoResultList &operator[](StringRef Name) {
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003196 return CorrectionResults.begin()->second[Name];
Douglas Gregor7b824e82010-10-15 13:35:25 +00003197 }
3198
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003199 unsigned getBestEditDistance(bool Normalized) {
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003200 if (CorrectionResults.empty())
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003201 return (std::numeric_limits<unsigned>::max)();
3202
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003203 unsigned BestED = CorrectionResults.begin()->first;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003204 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003205 }
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003206
3207 TypoResultsMap &getBestResults() {
3208 return CorrectionResults.begin()->second;
3209 }
3210
Douglas Gregor546be3c2009-12-30 17:04:44 +00003211};
3212
3213}
3214
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003215void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggend1205962011-10-06 07:27:49 +00003216 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003217 // Don't consider hidden names for typo correction.
3218 if (Hiding)
3219 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003220
Douglas Gregor546be3c2009-12-30 17:04:44 +00003221 // Only consider entities with identifiers for names, ignoring
3222 // special names (constructors, overloaded operators, selectors,
3223 // etc.).
3224 IdentifierInfo *Name = ND->getIdentifier();
3225 if (!Name)
3226 return;
3227
Douglas Gregor95f42922010-10-14 22:11:03 +00003228 FoundName(Name->getName());
3229}
3230
Chris Lattner5f9e2722011-07-23 10:55:15 +00003231void TypoCorrectionConsumer::FoundName(StringRef Name) {
Douglas Gregor362a8f22010-10-19 19:39:10 +00003232 // Use a simple length-based heuristic to determine the minimum possible
3233 // edit distance. If the minimum isn't good enough, bail out early.
3234 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003235 if (MinED && Typo.size() / MinED < 3)
Douglas Gregor362a8f22010-10-19 19:39:10 +00003236 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003237
Douglas Gregora1194772010-10-19 22:14:33 +00003238 // Compute an upper bound on the allowable edit distance, so that the
3239 // edit-distance algorithm can short-circuit.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003240 unsigned UpperBound = (Typo.size() + 2) / 3;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003241
Douglas Gregor546be3c2009-12-30 17:04:44 +00003242 // Compute the edit distance between the typo and the name of this
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003243 // entity, and add the identifier to the list of results.
3244 addName(Name, NULL, Typo.edit_distance(Name, true, UpperBound));
Douglas Gregor546be3c2009-12-30 17:04:44 +00003245}
3246
Chris Lattner5f9e2722011-07-23 10:55:15 +00003247void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003248 // Compute the edit distance between the typo and this keyword,
3249 // and add the keyword to the list of results.
3250 addName(Keyword, NULL, Typo.edit_distance(Keyword), NULL, true);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003251}
3252
Chris Lattner5f9e2722011-07-23 10:55:15 +00003253void TypoCorrectionConsumer::addName(StringRef Name,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003254 NamedDecl *ND,
3255 unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003256 NestedNameSpecifier *NNS,
3257 bool isKeyword) {
3258 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
3259 if (isKeyword) TC.makeKeyword();
3260 addCorrection(TC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003261}
3262
3263void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003264 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003265 TypoResultList &CList =
3266 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth55620532011-06-28 22:48:40 +00003267
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003268 if (!CList.empty() && !CList.back().isResolved())
3269 CList.pop_back();
3270 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3271 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3272 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3273 RI != RIEnd; ++RI) {
3274 // If the Correction refers to a decl already in the result list,
3275 // replace the existing result if the string representation of Correction
3276 // comes before the current result alphabetically, then stop as there is
3277 // nothing more to be done to add Correction to the candidate set.
3278 if (RI->getCorrectionDecl() == NewND) {
3279 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3280 *RI = Correction;
3281 return;
3282 }
3283 }
3284 }
3285 if (CList.empty() || Correction.isResolved())
3286 CList.push_back(Correction);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003287
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003288 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
3289 erase(llvm::prior(CorrectionResults.end()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003290}
3291
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003292// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3293// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3294// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3295static void getNestedNameSpecifierIdentifiers(
3296 NestedNameSpecifier *NNS,
3297 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3298 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3299 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3300 else
3301 Identifiers.clear();
3302
3303 const IdentifierInfo *II = NULL;
3304
3305 switch (NNS->getKind()) {
3306 case NestedNameSpecifier::Identifier:
3307 II = NNS->getAsIdentifier();
3308 break;
3309
3310 case NestedNameSpecifier::Namespace:
3311 if (NNS->getAsNamespace()->isAnonymousNamespace())
3312 return;
3313 II = NNS->getAsNamespace()->getIdentifier();
3314 break;
3315
3316 case NestedNameSpecifier::NamespaceAlias:
3317 II = NNS->getAsNamespaceAlias()->getIdentifier();
3318 break;
3319
3320 case NestedNameSpecifier::TypeSpecWithTemplate:
3321 case NestedNameSpecifier::TypeSpec:
3322 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3323 break;
3324
3325 case NestedNameSpecifier::Global:
3326 return;
3327 }
3328
3329 if (II)
3330 Identifiers.push_back(II);
3331}
3332
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003333namespace {
3334
3335class SpecifierInfo {
3336 public:
3337 DeclContext* DeclCtx;
3338 NestedNameSpecifier* NameSpecifier;
3339 unsigned EditDistance;
3340
3341 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3342 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3343};
3344
Chris Lattner5f9e2722011-07-23 10:55:15 +00003345typedef SmallVector<DeclContext*, 4> DeclContextList;
3346typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003347
3348class NamespaceSpecifierSet {
3349 ASTContext &Context;
3350 DeclContextList CurContextChain;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003351 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3352 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003353 bool isSorted;
3354
3355 SpecifierInfoList Specifiers;
3356 llvm::SmallSetVector<unsigned, 4> Distances;
3357 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3358
3359 /// \brief Helper for building the list of DeclContexts between the current
3360 /// context and the top of the translation unit
3361 static DeclContextList BuildContextChain(DeclContext *Start);
3362
3363 void SortNamespaces();
3364
3365 public:
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003366 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3367 CXXScopeSpec *CurScopeSpec)
Benjamin Kramerc5bb9d42011-07-05 09:46:31 +00003368 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003369 isSorted(true) {
3370 if (CurScopeSpec && CurScopeSpec->getScopeRep())
3371 getNestedNameSpecifierIdentifiers(CurScopeSpec->getScopeRep(),
3372 CurNameSpecifierIdentifiers);
3373 // Build the list of identifiers that would be used for an absolute
Benjamin Kramer48d798c2012-06-02 10:20:41 +00003374 // (from the global context) NestedNameSpecifier referring to the current
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003375 // context.
3376 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3377 CEnd = CurContextChain.rend();
3378 C != CEnd; ++C) {
3379 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3380 CurContextIdentifiers.push_back(ND->getIdentifier());
3381 }
3382 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003383
3384 /// \brief Add the namespace to the set, computing the corresponding
3385 /// NestedNameSpecifier and its distance in the process.
3386 void AddNamespace(NamespaceDecl *ND);
3387
3388 typedef SpecifierInfoList::iterator iterator;
3389 iterator begin() {
3390 if (!isSorted) SortNamespaces();
3391 return Specifiers.begin();
3392 }
3393 iterator end() { return Specifiers.end(); }
3394};
3395
3396}
3397
3398DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003399 assert(Start && "Bulding a context chain from a null context");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003400 DeclContextList Chain;
3401 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3402 DC = DC->getLookupParent()) {
3403 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3404 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3405 !(ND && ND->isAnonymousNamespace()))
3406 Chain.push_back(DC->getPrimaryContext());
3407 }
3408 return Chain;
3409}
3410
3411void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003412 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003413 sortedDistances.append(Distances.begin(), Distances.end());
3414
3415 if (sortedDistances.size() > 1)
3416 std::sort(sortedDistances.begin(), sortedDistances.end());
3417
3418 Specifiers.clear();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003419 for (SmallVector<unsigned, 4>::iterator DI = sortedDistances.begin(),
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003420 DIEnd = sortedDistances.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003421 DI != DIEnd; ++DI) {
3422 SpecifierInfoList &SpecList = DistanceMap[*DI];
3423 Specifiers.append(SpecList.begin(), SpecList.end());
3424 }
3425
3426 isSorted = true;
3427}
3428
3429void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003430 DeclContext *Ctx = cast<DeclContext>(ND);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003431 NestedNameSpecifier *NNS = NULL;
3432 unsigned NumSpecifiers = 0;
3433 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003434 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003435
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003436 // Eliminate common elements from the two DeclContext chains.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003437 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3438 CEnd = CurContextChain.rend();
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003439 C != CEnd && !NamespaceDeclChain.empty() &&
3440 NamespaceDeclChain.back() == *C; ++C) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003441 NamespaceDeclChain.pop_back();
3442 }
3443
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003444 // Add an explicit leading '::' specifier if needed.
3445 if (NamespaceDecl *ND =
Kaelyn Uhrain3ad02aa2012-02-15 22:59:03 +00003446 NamespaceDeclChain.empty() ? NULL :
3447 dyn_cast_or_null<NamespaceDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003448 IdentifierInfo *Name = ND->getIdentifier();
3449 if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3450 Name) != CurContextIdentifiers.end() ||
3451 std::find(CurNameSpecifierIdentifiers.begin(),
3452 CurNameSpecifierIdentifiers.end(),
3453 Name) != CurNameSpecifierIdentifiers.end()) {
3454 NamespaceDeclChain = FullNamespaceDeclChain;
3455 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3456 }
3457 }
3458
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003459 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3460 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3461 CEnd = NamespaceDeclChain.rend();
3462 C != CEnd; ++C) {
3463 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3464 if (ND) {
3465 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3466 ++NumSpecifiers;
3467 }
3468 }
3469
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003470 // If the built NestedNameSpecifier would be replacing an existing
3471 // NestedNameSpecifier, use the number of component identifiers that
3472 // would need to be changed as the edit distance instead of the number
3473 // of components in the built NestedNameSpecifier.
3474 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3475 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3476 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3477 NumSpecifiers = llvm::ComputeEditDistance(
3478 llvm::ArrayRef<const IdentifierInfo*>(CurNameSpecifierIdentifiers),
3479 llvm::ArrayRef<const IdentifierInfo*>(NewNameSpecifierIdentifiers));
3480 }
3481
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003482 isSorted = false;
3483 Distances.insert(NumSpecifiers);
3484 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
Douglas Gregoraaf87162010-04-14 20:04:41 +00003485}
3486
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003487/// \brief Perform name lookup for a possible result for typo correction.
3488static void LookupPotentialTypoResult(Sema &SemaRef,
3489 LookupResult &Res,
3490 IdentifierInfo *Name,
3491 Scope *S, CXXScopeSpec *SS,
3492 DeclContext *MemberContext,
3493 bool EnteringContext,
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003494 bool isObjCIvarLookup) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003495 Res.suppressDiagnostics();
3496 Res.clear();
3497 Res.setLookupName(Name);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003498 if (MemberContext) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003499 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003500 if (isObjCIvarLookup) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003501 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3502 Res.addDecl(Ivar);
3503 Res.resolveKind();
3504 return;
3505 }
3506 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003507
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003508 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3509 Res.addDecl(Prop);
3510 Res.resolveKind();
3511 return;
3512 }
3513 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003514
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003515 SemaRef.LookupQualifiedName(Res, MemberContext);
3516 return;
3517 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003518
3519 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003520 EnteringContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003521
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003522 // Fake ivar lookup; this should really be part of
3523 // LookupParsedName.
3524 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3525 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003526 (Res.empty() ||
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003527 (Res.isSingleResult() &&
3528 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003529 if (ObjCIvarDecl *IV
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003530 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3531 Res.addDecl(IV);
3532 Res.resolveKind();
3533 }
3534 }
3535 }
3536}
3537
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003538/// \brief Add keywords to the consumer as possible typo corrections.
3539static void AddKeywordsToConsumer(Sema &SemaRef,
3540 TypoCorrectionConsumer &Consumer,
Richard Smith0f4b5be2012-06-08 21:35:42 +00003541 Scope *S, CorrectionCandidateCallback &CCC,
3542 bool AfterNestedNameSpecifier) {
3543 if (AfterNestedNameSpecifier) {
3544 // For 'X::', we know exactly which keywords can appear next.
3545 Consumer.addKeywordResult("template");
3546 if (CCC.WantExpressionKeywords)
3547 Consumer.addKeywordResult("operator");
3548 return;
3549 }
3550
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003551 if (CCC.WantObjCSuper)
3552 Consumer.addKeywordResult("super");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003553
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003554 if (CCC.WantTypeSpecifiers) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003555 // Add type-specifier keywords to the set of results.
3556 const char *CTypeSpecs[] = {
3557 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor07f4a062011-07-01 21:27:45 +00003558 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003559 "_Complex", "_Imaginary",
3560 // storage-specifiers as well
3561 "extern", "inline", "static", "typedef"
3562 };
3563
3564 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3565 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3566 Consumer.addKeywordResult(CTypeSpecs[I]);
3567
David Blaikie4e4d0842012-03-11 07:00:24 +00003568 if (SemaRef.getLangOpts().C99)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003569 Consumer.addKeywordResult("restrict");
David Blaikie4e4d0842012-03-11 07:00:24 +00003570 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003571 Consumer.addKeywordResult("bool");
David Blaikie4e4d0842012-03-11 07:00:24 +00003572 else if (SemaRef.getLangOpts().C99)
Douglas Gregor07f4a062011-07-01 21:27:45 +00003573 Consumer.addKeywordResult("_Bool");
3574
David Blaikie4e4d0842012-03-11 07:00:24 +00003575 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003576 Consumer.addKeywordResult("class");
3577 Consumer.addKeywordResult("typename");
3578 Consumer.addKeywordResult("wchar_t");
3579
Richard Smith80ad52f2013-01-02 11:42:31 +00003580 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003581 Consumer.addKeywordResult("char16_t");
3582 Consumer.addKeywordResult("char32_t");
3583 Consumer.addKeywordResult("constexpr");
3584 Consumer.addKeywordResult("decltype");
3585 Consumer.addKeywordResult("thread_local");
3586 }
3587 }
3588
David Blaikie4e4d0842012-03-11 07:00:24 +00003589 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003590 Consumer.addKeywordResult("typeof");
3591 }
3592
David Blaikie4e4d0842012-03-11 07:00:24 +00003593 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003594 Consumer.addKeywordResult("const_cast");
3595 Consumer.addKeywordResult("dynamic_cast");
3596 Consumer.addKeywordResult("reinterpret_cast");
3597 Consumer.addKeywordResult("static_cast");
3598 }
3599
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003600 if (CCC.WantExpressionKeywords) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003601 Consumer.addKeywordResult("sizeof");
David Blaikie4e4d0842012-03-11 07:00:24 +00003602 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003603 Consumer.addKeywordResult("false");
3604 Consumer.addKeywordResult("true");
3605 }
3606
David Blaikie4e4d0842012-03-11 07:00:24 +00003607 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003608 const char *CXXExprs[] = {
3609 "delete", "new", "operator", "throw", "typeid"
3610 };
3611 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3612 for (unsigned I = 0; I != NumCXXExprs; ++I)
3613 Consumer.addKeywordResult(CXXExprs[I]);
3614
3615 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3616 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3617 Consumer.addKeywordResult("this");
3618
Richard Smith80ad52f2013-01-02 11:42:31 +00003619 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003620 Consumer.addKeywordResult("alignof");
3621 Consumer.addKeywordResult("nullptr");
3622 }
3623 }
Jordan Rosef70a8862012-06-30 21:33:57 +00003624
3625 if (SemaRef.getLangOpts().C11) {
3626 // FIXME: We should not suggest _Alignof if the alignof macro
3627 // is present.
3628 Consumer.addKeywordResult("_Alignof");
3629 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003630 }
3631
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003632 if (CCC.WantRemainingKeywords) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003633 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3634 // Statements.
3635 const char *CStmts[] = {
3636 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3637 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3638 for (unsigned I = 0; I != NumCStmts; ++I)
3639 Consumer.addKeywordResult(CStmts[I]);
3640
David Blaikie4e4d0842012-03-11 07:00:24 +00003641 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003642 Consumer.addKeywordResult("catch");
3643 Consumer.addKeywordResult("try");
3644 }
3645
3646 if (S && S->getBreakParent())
3647 Consumer.addKeywordResult("break");
3648
3649 if (S && S->getContinueParent())
3650 Consumer.addKeywordResult("continue");
3651
3652 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3653 Consumer.addKeywordResult("case");
3654 Consumer.addKeywordResult("default");
3655 }
3656 } else {
David Blaikie4e4d0842012-03-11 07:00:24 +00003657 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003658 Consumer.addKeywordResult("namespace");
3659 Consumer.addKeywordResult("template");
3660 }
3661
3662 if (S && S->isClassScope()) {
3663 Consumer.addKeywordResult("explicit");
3664 Consumer.addKeywordResult("friend");
3665 Consumer.addKeywordResult("mutable");
3666 Consumer.addKeywordResult("private");
3667 Consumer.addKeywordResult("protected");
3668 Consumer.addKeywordResult("public");
3669 Consumer.addKeywordResult("virtual");
3670 }
3671 }
3672
David Blaikie4e4d0842012-03-11 07:00:24 +00003673 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003674 Consumer.addKeywordResult("using");
3675
Richard Smith80ad52f2013-01-02 11:42:31 +00003676 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003677 Consumer.addKeywordResult("static_assert");
3678 }
3679 }
3680}
3681
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003682static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3683 TypoCorrection &Candidate) {
3684 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3685 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3686}
3687
Douglas Gregor546be3c2009-12-30 17:04:44 +00003688/// \brief Try to "correct" a typo in the source code by finding
3689/// visible declarations whose names are similar to the name that was
3690/// present in the source code.
3691///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003692/// \param TypoName the \c DeclarationNameInfo structure that contains
3693/// the name that was present in the source code along with its location.
3694///
3695/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003696///
3697/// \param S the scope in which name lookup occurs.
3698///
3699/// \param SS the nested-name-specifier that precedes the name we're
3700/// looking for, if present.
3701///
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003702/// \param CCC A CorrectionCandidateCallback object that provides further
3703/// validation of typo correction candidates. It also provides flags for
3704/// determining the set of keywords permitted.
3705///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003706/// \param MemberContext if non-NULL, the context in which to look for
3707/// a member access expression.
3708///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003709/// \param EnteringContext whether we're entering the context described by
Douglas Gregorbb092ba2009-12-31 05:20:13 +00003710/// the nested-name-specifier SS.
3711///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003712/// \param OPT when non-NULL, the search for visible declarations will
3713/// also walk the protocols in the qualified interfaces of \p OPT.
3714///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003715/// \returns a \c TypoCorrection containing the corrected name if the typo
3716/// along with information such as the \c NamedDecl where the corrected name
3717/// was declared, and any additional \c NestedNameSpecifier needed to access
3718/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3719TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3720 Sema::LookupNameKind LookupKind,
3721 Scope *S, CXXScopeSpec *SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00003722 CorrectionCandidateCallback &CCC,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003723 DeclContext *MemberContext,
3724 bool EnteringContext,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003725 const ObjCObjectPointerType *OPT) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003726 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003727 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003728
Francois Pichet4d604d62011-12-03 15:55:29 +00003729 // In Microsoft mode, don't perform typo correction in a template member
3730 // function dependent context because it interferes with the "lookup into
3731 // dependent bases of class templates" feature.
David Blaikie4e4d0842012-03-11 07:00:24 +00003732 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichet4d604d62011-12-03 15:55:29 +00003733 isa<CXXMethodDecl>(CurContext))
3734 return TypoCorrection();
3735
Douglas Gregor546be3c2009-12-30 17:04:44 +00003736 // We only attempt to correct typos for identifiers.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003737 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003738 if (!Typo)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003739 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003740
3741 // If the scope specifier itself was invalid, don't try to correct
3742 // typos.
3743 if (SS && SS->isInvalid())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003744 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003745
3746 // Never try to correct typos during template deduction or
3747 // instantiation.
3748 if (!ActiveTemplateInstantiations.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003749 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003750
Argyrios Kyrtzidis57f8da52013-03-14 22:56:43 +00003751 // Don't try to correct 'super'.
3752 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
3753 return TypoCorrection();
3754
Argyrios Kyrtzidis6aa240c2013-03-16 01:40:35 +00003755 // This is for testing.
3756 if (Diags.getWarnOnSpellCheck()) {
3757 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
3758 "spell-checking initiated for %0");
3759 Diag(TypoName.getLoc(), DiagID) << TypoName.getName();
3760 }
Argyrios Kyrtzidis57f8da52013-03-14 22:56:43 +00003761
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003762 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003763
3764 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003765
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003766 // If a callback object considers an empty typo correction candidate to be
3767 // viable, assume it does not do any actual validation of the candidates.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003768 TypoCorrection EmptyCorrection;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003769 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003770
Douglas Gregoraaf87162010-04-14 20:04:41 +00003771 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003772 bool IsUnqualifiedLookup = false;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003773 DeclContext *QualifiedDC = MemberContext;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003774 if (MemberContext) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003775 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003776
3777 // Look in qualified interfaces.
3778 if (OPT) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003779 for (ObjCObjectPointerType::qual_iterator
3780 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003781 I != E; ++I)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003782 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003783 }
3784 } else if (SS && SS->isSet()) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003785 QualifiedDC = computeDeclContext(*SS, EnteringContext);
3786 if (!QualifiedDC)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003787 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003788
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003789 // Provide a stop gap for files that are just seriously broken. Trying
3790 // to correct all typos can turn into a HUGE performance penalty, causing
3791 // some files to take minutes to get rejected by the parser.
3792 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003793 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003794 ++TyposCorrected;
3795
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003796 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003797 } else {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003798 IsUnqualifiedLookup = true;
3799 UnqualifiedTyposCorrectedMap::iterator Cached
3800 = UnqualifiedTyposCorrected.find(Typo);
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003801 if (Cached != UnqualifiedTyposCorrected.end()) {
3802 // Add the cached value, unless it's a keyword or fails validation. In the
3803 // keyword case, we'll end up adding the keyword below.
3804 if (Cached->second) {
3805 if (!Cached->second.isKeyword() &&
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003806 isCandidateViable(CCC, Cached->second))
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003807 Consumer.addCorrection(Cached->second);
3808 } else {
3809 // Only honor no-correction cache hits when a callback that will validate
3810 // correction candidates is not being used.
3811 if (!ValidatingCallback)
3812 return TypoCorrection();
3813 }
3814 }
3815 if (Cached == UnqualifiedTyposCorrected.end()) {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003816 // Provide a stop gap for files that are just seriously broken. Trying
3817 // to correct all typos can turn into a HUGE performance penalty, causing
3818 // some files to take minutes to get rejected by the parser.
3819 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003820 return TypoCorrection();
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003821 }
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003822 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003823
Douglas Gregor01798682012-03-26 16:54:18 +00003824 // Determine whether we are going to search in the various namespaces for
3825 // corrections.
3826 bool SearchNamespaces
Kaelyn Uhrain6d858d92012-04-03 18:20:11 +00003827 = getLangOpts().CPlusPlus &&
Douglas Gregor01798682012-03-26 16:54:18 +00003828 (IsUnqualifiedLookup || (QualifiedDC && QualifiedDC->isNamespace()));
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00003829 // In a few cases we *only* want to search for corrections bases on just
3830 // adding or changing the nested name specifier.
3831 bool AllowOnlyNNSChanges = Typo->getName().size() < 3;
Douglas Gregor01798682012-03-26 16:54:18 +00003832
3833 if (IsUnqualifiedLookup || SearchNamespaces) {
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003834 // For unqualified lookup, look through all of the names that we have
3835 // seen in this translation unit.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003836 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003837 for (IdentifierTable::iterator I = Context.Idents.begin(),
3838 IEnd = Context.Idents.end();
3839 I != IEnd; ++I)
3840 Consumer.FoundName(I->getKey());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003841
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003842 // Walk through identifiers in external identifier sources.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003843 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003844 if (IdentifierInfoLookup *External
3845 = Context.Idents.getExternalIdentifierLookup()) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00003846 OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003847 do {
3848 StringRef Name = Iter->Next();
3849 if (Name.empty())
3850 break;
Douglas Gregor95f42922010-10-14 22:11:03 +00003851
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00003852 Consumer.FoundName(Name);
3853 } while (true);
Douglas Gregor95f42922010-10-14 22:11:03 +00003854 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003855 }
3856
Richard Smith0f4b5be2012-06-08 21:35:42 +00003857 AddKeywordsToConsumer(*this, Consumer, S, CCC, SS && SS->isNotEmpty());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003858
Douglas Gregoraaf87162010-04-14 20:04:41 +00003859 // If we haven't found anything, we're done.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003860 if (Consumer.empty()) {
3861 // If this was an unqualified lookup, note that no correction was found.
3862 if (IsUnqualifiedLookup)
3863 (void)UnqualifiedTyposCorrected[Typo];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003864
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003865 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003866 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003867
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00003868 // Make sure the best edit distance (prior to adding any namespace qualifiers)
3869 // is not more that about a third of the length of the typo's identifier.
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003870 unsigned ED = Consumer.getBestEditDistance(true);
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003871 if (ED > 0 && Typo->getName().size() / ED < 3) {
3872 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregor157a3ff2010-10-27 14:20:34 +00003873 if (IsUnqualifiedLookup)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003874 (void)UnqualifiedTyposCorrected[Typo];
3875
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003876 return TypoCorrection();
3877 }
3878
Douglas Gregor01798682012-03-26 16:54:18 +00003879 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
3880 // to search those namespaces.
3881 if (SearchNamespaces) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003882 // Load any externally-known namespaces.
3883 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003884 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003885 LoadedExternalKnownNamespaces = true;
3886 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
3887 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
3888 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
3889 }
3890
Nick Lewycky01a41142013-01-26 00:35:08 +00003891 for (llvm::MapVector<NamespaceDecl*, bool>::iterator
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003892 KNI = KnownNamespaces.begin(),
3893 KNIEnd = KnownNamespaces.end();
3894 KNI != KNIEnd; ++KNI)
3895 Namespaces.AddNamespace(KNI->first);
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003896 }
Douglas Gregore24b5752010-10-14 20:34:08 +00003897
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003898 // Weed out any names that could not be found by name lookup or, if a
3899 // CorrectionCandidateCallback object was provided, failed validation.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003900 SmallVector<TypoCorrection, 16> QualifiedResults;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003901 LookupResult TmpRes(*this, TypoName, LookupKind);
3902 TmpRes.suppressDiagnostics();
3903 while (!Consumer.empty()) {
3904 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3905 unsigned ED = DI->first;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003906 for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(),
3907 IEnd = DI->second.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003908 I != IEnd; /* Increment in loop. */) {
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00003909 // If we only want nested name specifier corrections, ignore potential
3910 // corrections that have a different base identifier from the typo.
3911 if (AllowOnlyNNSChanges &&
3912 I->second.front().getCorrectionAsIdentifierInfo() != Typo) {
3913 TypoCorrectionConsumer::result_iterator Prev = I;
3914 ++I;
3915 DI->second.erase(Prev);
3916 continue;
3917 }
3918
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003919 // If the item already has been looked up or is a keyword, keep it.
3920 // If a validator callback object was given, drop the correction
3921 // unless it passes validation.
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003922 bool Viable = false;
Benjamin Kramerb3996962012-07-27 10:21:08 +00003923 for (TypoResultList::iterator RI = I->second.begin();
3924 RI != I->second.end(); /* Increment in loop. */) {
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003925 TypoResultList::iterator Prev = RI;
3926 ++RI;
3927 if (Prev->isResolved()) {
3928 if (!isCandidateViable(CCC, *Prev))
Benjamin Kramerb3996962012-07-27 10:21:08 +00003929 RI = I->second.erase(Prev);
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003930 else
3931 Viable = true;
3932 }
3933 }
3934 if (Viable || I->second.empty()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003935 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003936 ++I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003937 if (!Viable)
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003938 DI->second.erase(Prev);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003939 continue;
Douglas Gregore24b5752010-10-14 20:34:08 +00003940 }
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003941 assert(I->second.size() == 1 && "Expected a single unresolved candidate");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003942
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003943 // Perform name lookup on this name.
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003944 TypoCorrection &Candidate = I->second.front();
3945 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003946 LookupPotentialTypoResult(*this, TmpRes, Name, S, SS, MemberContext,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00003947 EnteringContext, CCC.IsObjCIvarLookup);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003948
3949 switch (TmpRes.getResultKind()) {
3950 case LookupResult::NotFound:
3951 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00003952 case LookupResult::FoundUnresolvedValue:
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003953 QualifiedResults.push_back(Candidate);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003954 // We didn't find this name in our scope, or didn't like what we found;
3955 // ignore it.
3956 {
3957 TypoCorrectionConsumer::result_iterator Next = I;
3958 ++Next;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003959 DI->second.erase(I);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003960 I = Next;
3961 }
3962 break;
3963
3964 case LookupResult::Ambiguous:
3965 // We don't deal with ambiguities.
3966 return TypoCorrection();
3967
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003968 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003969 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003970 // Store all of the Decls for overloaded symbols
3971 for (LookupResult::iterator TRD = TmpRes.begin(),
3972 TRDEnd = TmpRes.end();
3973 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003974 Candidate.addCorrectionDecl(*TRD);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003975 ++I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003976 if (!isCandidateViable(CCC, Candidate))
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003977 DI->second.erase(Prev);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003978 break;
3979 }
3980
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003981 case LookupResult::Found: {
3982 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003983 Candidate.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003984 ++I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003985 if (!isCandidateViable(CCC, Candidate))
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003986 DI->second.erase(Prev);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003987 break;
3988 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003989
3990 }
Douglas Gregore24b5752010-10-14 20:34:08 +00003991 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003992
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003993 if (DI->second.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003994 Consumer.erase(DI);
David Blaikie4e4d0842012-03-11 07:00:24 +00003995 else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !ED)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003996 // If there are results in the closest possible bucket, stop
3997 break;
3998
3999 // Only perform the qualified lookups for C++
Douglas Gregor01798682012-03-26 16:54:18 +00004000 if (SearchNamespaces) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004001 TmpRes.suppressDiagnostics();
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004002 for (SmallVector<TypoCorrection,
4003 16>::iterator QRI = QualifiedResults.begin(),
4004 QRIEnd = QualifiedResults.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004005 QRI != QRIEnd; ++QRI) {
4006 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
4007 NIEnd = Namespaces.end();
4008 NI != NIEnd; ++NI) {
4009 DeclContext *Ctx = NI->DeclCtx;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004010
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00004011 // FIXME: Stop searching once the namespaces are too far away to create
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004012 // acceptable corrections for this identifier (since the namespaces
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00004013 // are sorted in ascending order by edit distance).
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004014
4015 TmpRes.clear();
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00004016 TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004017 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
4018
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004019 // Any corrections added below will be validated in subsequent
4020 // iterations of the main while() loop over the Consumer's contents.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004021 switch (TmpRes.getResultKind()) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004022 case LookupResult::Found: {
4023 TypoCorrection TC(*QRI);
4024 TC.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
4025 TC.setCorrectionSpecifier(NI->NameSpecifier);
4026 TC.setQualifierDistance(NI->EditDistance);
4027 Consumer.addCorrection(TC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004028 break;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004029 }
4030 case LookupResult::FoundOverloaded: {
4031 TypoCorrection TC(*QRI);
4032 TC.setCorrectionSpecifier(NI->NameSpecifier);
4033 TC.setQualifierDistance(NI->EditDistance);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004034 for (LookupResult::iterator TRD = TmpRes.begin(),
4035 TRDEnd = TmpRes.end();
4036 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004037 TC.addCorrectionDecl(*TRD);
4038 Consumer.addCorrection(TC);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004039 break;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004040 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004041 case LookupResult::NotFound:
4042 case LookupResult::NotFoundInCurrentInstantiation:
4043 case LookupResult::Ambiguous:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00004044 case LookupResult::FoundUnresolvedValue:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004045 break;
4046 }
4047 }
4048 }
4049 }
4050
4051 QualifiedResults.clear();
4052 }
4053
4054 // No corrections remain...
4055 if (Consumer.empty()) return TypoCorrection();
4056
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00004057 TypoResultsMap &BestResults = Consumer.getBestResults();
4058 ED = Consumer.getBestEditDistance(true);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004059
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00004060 if (!AllowOnlyNNSChanges && ED > 0 && Typo->getName().size() / ED < 3) {
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004061 // If this was an unqualified lookup and we believe the callback
4062 // object wouldn't have filtered out possible corrections, note
4063 // that no correction was found.
4064 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004065 (void)UnqualifiedTyposCorrected[Typo];
4066
4067 return TypoCorrection();
4068 }
4069
Douglas Gregore24b5752010-10-14 20:34:08 +00004070 // If only a single name remains, return that result.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004071 if (BestResults.size() == 1) {
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004072 const TypoResultList &CorrectionList = BestResults.begin()->second;
4073 const TypoCorrection &Result = CorrectionList.front();
4074 if (CorrectionList.size() != 1) return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004075
Douglas Gregor53e4b552010-10-26 17:18:00 +00004076 // Don't correct to a keyword that's the same as the typo; the keyword
4077 // wasn't actually in scope.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004078 if (ED == 0 && Result.isKeyword()) return TypoCorrection();
4079
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004080 // Record the correction for unqualified lookup.
4081 if (IsUnqualifiedLookup)
4082 UnqualifiedTyposCorrected[Typo] = Result;
4083
David Blaikie6952c012012-10-12 20:00:44 +00004084 TypoCorrection TC = Result;
4085 TC.setCorrectionRange(SS, TypoName);
4086 return TC;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004087 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004088 else if (BestResults.size() > 1
4089 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4090 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4091 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4092 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00004093 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004094 && BestResults["super"].front().isKeyword()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004095 // Prefer 'super' when we're completing in a message-receiver
4096 // context.
4097
4098 // Don't correct to a keyword that's the same as the typo; the keyword
4099 // wasn't actually in scope.
4100 if (ED == 0) return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004101
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004102 // Record the correction for unqualified lookup.
4103 if (IsUnqualifiedLookup)
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004104 UnqualifiedTyposCorrected[Typo] = BestResults["super"].front();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004105
David Blaikie6952c012012-10-12 20:00:44 +00004106 TypoCorrection TC = BestResults["super"].front();
4107 TC.setCorrectionRange(SS, TypoName);
4108 return TC;
Douglas Gregor7b824e82010-10-15 13:35:25 +00004109 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004110
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004111 // If this was an unqualified lookup and we believe the callback object did
4112 // not filter out possible corrections, note that no correction was found.
4113 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004114 (void)UnqualifiedTyposCorrected[Typo];
4115
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004116 return TypoCorrection();
4117}
4118
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004119void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4120 if (!CDecl) return;
4121
4122 if (isKeyword())
4123 CorrectionDecls.clear();
4124
Kaelyn Uhrain728948f2012-11-19 18:49:53 +00004125 CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004126
4127 if (!CorrectionName)
4128 CorrectionName = CDecl->getDeclName();
4129}
4130
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004131std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4132 if (CorrectionNameSpec) {
4133 std::string tmpBuffer;
4134 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4135 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004136 CorrectionName.printName(PrefixOStream);
4137 return PrefixOStream.str();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004138 }
4139
4140 return CorrectionName.getAsString();
Douglas Gregor546be3c2009-12-30 17:04:44 +00004141}