blob: 2a096cfd978148a7101b6845a6bcfb85c64507c0 [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
Robert Wilhelm344472e2013-08-23 16:11:15 +0000170 DC = queue.pop_back_val();
John McCalld7be78a2009-11-10 07:01:13 +0000171 }
172 }
173
174 // Add a using directive as if it had been declared in the given
175 // context. This helps implement C++ [namespace.udir]p3:
176 // The using-directive is transitive: if a scope contains a
177 // using-directive that nominates a second namespace that itself
178 // contains using-directives, the effect is as if the
179 // using-directives from the second namespace also appeared in
180 // the first.
181 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
182 // Find the common ancestor between the effective context and
183 // the nominated namespace.
184 DeclContext *Common = UD->getNominatedNamespace();
185 while (!Common->Encloses(EffectiveDC))
186 Common = Common->getParent();
John McCall12ea5782009-11-10 09:20:04 +0000187 Common = Common->getPrimaryContext();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000188
John McCalld7be78a2009-11-10 07:01:13 +0000189 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
190 }
191
192 void done() {
193 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
194 }
195
John McCalld7be78a2009-11-10 07:01:13 +0000196 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000197
John McCalld7be78a2009-11-10 07:01:13 +0000198 const_iterator begin() const { return list.begin(); }
199 const_iterator end() const { return list.end(); }
200
201 std::pair<const_iterator,const_iterator>
202 getNamespacesFor(DeclContext *DC) const {
John McCall12ea5782009-11-10 09:20:04 +0000203 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCalld7be78a2009-11-10 07:01:13 +0000204 UnqualUsingEntry::Comparator());
205 }
206 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000207}
208
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000209// Retrieve the set of identifier namespaces that correspond to a
210// specific kind of name lookup.
John McCall1d7c5282009-12-18 10:40:03 +0000211static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
212 bool CPlusPlus,
213 bool Redeclaration) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000214 unsigned IDNS = 0;
215 switch (NameKind) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +0000216 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000217 case Sema::LookupOrdinaryName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000218 case Sema::LookupRedeclarationWithLinkage:
Richard Smith4e9686b2013-08-09 04:35:01 +0000219 case Sema::LookupLocalFriendName:
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 }
Richard Smitha41c97a2013-09-20 01:15:31 +0000226 if (Redeclaration)
227 IDNS |= Decl::IDNS_LocalExtern;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000228 break;
229
John McCall76d32642010-04-24 01:30:58 +0000230 case Sema::LookupOperatorName:
231 // Operator lookup is its own crazy thing; it is not the same
232 // as (e.g.) looking up an operator name for redeclaration.
233 assert(!Redeclaration && "cannot do redeclaration operator lookup");
234 IDNS = Decl::IDNS_NonMemberOperator;
235 break;
236
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000237 case Sema::LookupTagName:
John McCall0d6b1642010-04-23 18:46:30 +0000238 if (CPlusPlus) {
239 IDNS = Decl::IDNS_Type;
240
241 // When looking for a redeclaration of a tag name, we add:
242 // 1) TagFriend to find undeclared friend decls
243 // 2) Namespace because they can't "overload" with tag decls.
244 // 3) Tag because it includes class templates, which can't
245 // "overload" with tag decls.
246 if (Redeclaration)
247 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
248 } else {
249 IDNS = Decl::IDNS_Tag;
250 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000251 break;
Chris Lattner337e5502011-02-18 01:27:55 +0000252 case Sema::LookupLabel:
253 IDNS = Decl::IDNS_Label;
254 break;
255
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000256 case Sema::LookupMemberName:
257 IDNS = Decl::IDNS_Member;
258 if (CPlusPlus)
Mike Stump1eb44332009-09-09 15:08:12 +0000259 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000260 break;
261
262 case Sema::LookupNestedNameSpecifierName:
John McCall0d6b1642010-04-23 18:46:30 +0000263 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
264 break;
265
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000266 case Sema::LookupNamespaceName:
John McCall0d6b1642010-04-23 18:46:30 +0000267 IDNS = Decl::IDNS_Namespace;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000268 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000269
John McCall9f54ad42009-12-10 09:41:52 +0000270 case Sema::LookupUsingDeclName:
271 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
272 | Decl::IDNS_Member | Decl::IDNS_Using;
273 break;
274
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000275 case Sema::LookupObjCProtocolName:
276 IDNS = Decl::IDNS_ObjCProtocol;
277 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000278
Douglas Gregor8071e422010-08-15 06:18:01 +0000279 case Sema::LookupAnyName:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000280 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor8071e422010-08-15 06:18:01 +0000281 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
282 | Decl::IDNS_Type;
283 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000284 }
285 return IDNS;
286}
287
John McCall1d7c5282009-12-18 10:40:03 +0000288void LookupResult::configure() {
David Blaikie4e4d0842012-03-11 07:00:24 +0000289 IDNS = getIDNS(LookupKind, SemaRef.getLangOpts().CPlusPlus,
John McCall1d7c5282009-12-18 10:40:03 +0000290 isForRedeclaration());
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000291
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000292 if (!isForRedeclaration()) {
Douglas Gregor96df3562013-04-03 23:06:26 +0000293 // If we're looking for one of the allocation or deallocation
294 // operators, make sure that the implicitly-declared new and delete
295 // operators can be found.
Abramo Bagnara25777432010-08-11 22:01:17 +0000296 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000297 case OO_New:
298 case OO_Delete:
299 case OO_Array_New:
300 case OO_Array_Delete:
301 SemaRef.DeclareGlobalNewDelete();
302 break;
303
304 default:
305 break;
306 }
Douglas Gregor96df3562013-04-03 23:06:26 +0000307
308 // Compiler builtins are always visible, regardless of where they end
309 // up being declared.
310 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
311 if (unsigned BuiltinID = Id->getBuiltinID()) {
312 if (!SemaRef.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
313 AllowHidden = true;
314 }
315 }
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000316 }
John McCall1d7c5282009-12-18 10:40:03 +0000317}
318
Daniel Dunbarc2bd73b2012-03-08 01:43:06 +0000319void LookupResult::sanityImpl() const {
320 // Note that this function is never called by NDEBUG builds. See
321 // LookupResult::sanity().
John McCall2a7fb272010-08-25 05:32:35 +0000322 assert(ResultKind != NotFound || Decls.size() == 0);
323 assert(ResultKind != Found || Decls.size() == 1);
324 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
325 (Decls.size() == 1 &&
326 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
327 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
328 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorf17b58c2010-10-22 22:08:47 +0000329 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
330 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall2a7fb272010-08-25 05:32:35 +0000331 assert((Paths != NULL) == (ResultKind == Ambiguous &&
332 (Ambiguity == AmbiguousBaseSubobjectTypes ||
333 Ambiguity == AmbiguousBaseSubobjects)));
334}
John McCall2a7fb272010-08-25 05:32:35 +0000335
John McCallf36e02d2009-10-09 21:13:30 +0000336// Necessary because CXXBasePaths is not complete in Sema.h
John McCall7d384dd2009-11-18 07:57:50 +0000337void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCallf36e02d2009-10-09 21:13:30 +0000338 delete Paths;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000339}
340
John McCall7453ed42009-11-22 00:44:51 +0000341/// Resolves the result kind of this lookup.
John McCall7d384dd2009-11-18 07:57:50 +0000342void LookupResult::resolveKind() {
John McCallf36e02d2009-10-09 21:13:30 +0000343 unsigned N = Decls.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000344
John McCallf36e02d2009-10-09 21:13:30 +0000345 // Fast case: no possible ambiguity.
John McCall68263142009-11-18 22:49:29 +0000346 if (N == 0) {
John McCalldc5c7862010-01-15 21:27:01 +0000347 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall68263142009-11-18 22:49:29 +0000348 return;
349 }
350
John McCall7453ed42009-11-22 00:44:51 +0000351 // If there's a single decl, we need to examine it to decide what
352 // kind of lookup this is.
John McCall7ba107a2009-11-18 02:36:19 +0000353 if (N == 1) {
Douglas Gregor2b147f02010-04-25 21:15:30 +0000354 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
355 if (isa<FunctionTemplateDecl>(D))
John McCall7453ed42009-11-22 00:44:51 +0000356 ResultKind = FoundOverloaded;
Douglas Gregor2b147f02010-04-25 21:15:30 +0000357 else if (isa<UnresolvedUsingValueDecl>(D))
John McCall7ba107a2009-11-18 02:36:19 +0000358 ResultKind = FoundUnresolvedValue;
359 return;
360 }
John McCallf36e02d2009-10-09 21:13:30 +0000361
John McCall6e247262009-10-10 05:48:19 +0000362 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000363 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000364
John McCallf36e02d2009-10-09 21:13:30 +0000365 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000366 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000367
John McCallf36e02d2009-10-09 21:13:30 +0000368 bool Ambiguous = false;
369 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000370 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000371
372 unsigned UniqueTagIndex = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000373
John McCallf36e02d2009-10-09 21:13:30 +0000374 unsigned I = 0;
375 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000376 NamedDecl *D = Decls[I]->getUnderlyingDecl();
377 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000378
Argyrios Kyrtzidis745af1c2013-02-22 06:58:37 +0000379 // Ignore an invalid declaration unless it's the only one left.
380 if (D->isInvalidDecl() && I < N-1) {
381 Decls[I] = Decls[--N];
382 continue;
383 }
384
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000385 // Redeclarations of types via typedef can occur both within a scope
386 // and, through using declarations and directives, across scopes. There is
387 // no ambiguity if they all refer to the same type, so unique based on the
388 // canonical type.
389 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
390 if (!TD->getDeclContext()->isRecord()) {
391 QualType T = SemaRef.Context.getTypeDeclType(TD);
392 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
393 // The type is not unique; pull something off the back and continue
394 // at this index.
395 Decls[I] = Decls[--N];
396 continue;
397 }
398 }
399 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000400
John McCall314be4e2009-11-17 07:50:12 +0000401 if (!Unique.insert(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000402 // If it's not unique, pull something off the back (and
403 // continue at this index).
404 Decls[I] = Decls[--N];
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000405 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000406 }
407
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000408 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000409
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000410 if (isa<UnresolvedUsingValueDecl>(D)) {
411 HasUnresolved = true;
412 } else if (isa<TagDecl>(D)) {
413 if (HasTag)
414 Ambiguous = true;
415 UniqueTagIndex = I;
416 HasTag = true;
417 } else if (isa<FunctionTemplateDecl>(D)) {
418 HasFunction = true;
419 HasFunctionTemplate = true;
420 } else if (isa<FunctionDecl>(D)) {
421 HasFunction = true;
422 } else {
423 if (HasNonFunction)
424 Ambiguous = true;
425 HasNonFunction = true;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000426 }
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000427 I++;
Mike Stump1eb44332009-09-09 15:08:12 +0000428 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000429
John McCallf36e02d2009-10-09 21:13:30 +0000430 // C++ [basic.scope.hiding]p2:
431 // A class name or enumeration name can be hidden by the name of
432 // an object, function, or enumerator declared in the same
433 // scope. If a class or enumeration name and an object, function,
434 // or enumerator are declared in the same scope (in any order)
435 // with the same name, the class or enumeration name is hidden
436 // wherever the object, function, or enumerator name is visible.
437 // But it's still an error if there are distinct tag types found,
438 // even if they're not visible. (ref?)
John McCallfda8e122009-12-03 00:58:24 +0000439 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregor77a1a882010-10-23 16:06:17 +0000440 (HasFunction || HasNonFunction || HasUnresolved)) {
441 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
442 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
443 Decls[UniqueTagIndex] = Decls[--N];
444 else
445 Ambiguous = true;
446 }
Anders Carlsson8b50d012009-06-26 03:37:05 +0000447
John McCallf36e02d2009-10-09 21:13:30 +0000448 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000449
John McCallfda8e122009-12-03 00:58:24 +0000450 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000451 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000452
John McCallf36e02d2009-10-09 21:13:30 +0000453 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000454 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000455 else if (HasUnresolved)
456 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000457 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000458 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000459 else
John McCalla24dc2e2009-11-17 02:14:36 +0000460 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000461}
462
John McCall7d384dd2009-11-18 07:57:50 +0000463void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall6b2accb2010-02-10 09:31:12 +0000464 CXXBasePaths::const_paths_iterator I, E;
John McCallf36e02d2009-10-09 21:13:30 +0000465 for (I = P.begin(), E = P.end(); I != E; ++I)
David Blaikie3bc93e32012-12-19 00:45:41 +0000466 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
467 DE = I->Decls.end(); DI != DE; ++DI)
John McCallf36e02d2009-10-09 21:13:30 +0000468 addDecl(*DI);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000469}
470
John McCall7d384dd2009-11-18 07:57:50 +0000471void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000472 Paths = new CXXBasePaths;
473 Paths->swap(P);
474 addDeclsFromBasePaths(*Paths);
475 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000476 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000477}
478
John McCall7d384dd2009-11-18 07:57:50 +0000479void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000480 Paths = new CXXBasePaths;
481 Paths->swap(P);
482 addDeclsFromBasePaths(*Paths);
483 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000484 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000485}
486
Chris Lattner5f9e2722011-07-23 10:55:15 +0000487void LookupResult::print(raw_ostream &Out) {
John McCallf36e02d2009-10-09 21:13:30 +0000488 Out << Decls.size() << " result(s)";
489 if (isAmbiguous()) Out << ", ambiguous";
490 if (Paths) Out << ", base paths present";
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000491
John McCallf36e02d2009-10-09 21:13:30 +0000492 for (iterator I = begin(), E = end(); I != E; ++I) {
493 Out << "\n";
494 (*I)->print(Out, 2);
495 }
496}
497
Douglas Gregor85910982010-02-12 05:48:04 +0000498/// \brief Lookup a builtin function, when name lookup would otherwise
499/// fail.
500static bool LookupBuiltin(Sema &S, LookupResult &R) {
501 Sema::LookupNameKind NameKind = R.getLookupKind();
502
503 // If we didn't find a use of this identifier, and if the identifier
504 // corresponds to a compiler builtin, create the decl object for the builtin
505 // now, injecting it into translation unit scope, and return it.
506 if (NameKind == Sema::LookupOrdinaryName ||
507 NameKind == Sema::LookupRedeclarationWithLinkage) {
508 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
509 if (II) {
Nico Webercac18ad2013-06-20 21:44:55 +0000510 if (S.getLangOpts().CPlusPlus11 && S.getLangOpts().GNUMode &&
511 II == S.getFloat128Identifier()) {
512 // libstdc++4.7's type_traits expects type __float128 to exist, so
513 // insert a dummy type to make that header build in gnu++11 mode.
514 R.addDecl(S.getASTContext().getFloat128StubType());
515 return true;
516 }
517
Douglas Gregor85910982010-02-12 05:48:04 +0000518 // If this is a builtin on this (or all) targets, create the decl.
519 if (unsigned BuiltinID = II->getBuiltinID()) {
520 // In C++, we don't have any predefined library functions like
521 // 'malloc'. Instead, we'll just error.
David Blaikie4e4d0842012-03-11 07:00:24 +0000522 if (S.getLangOpts().CPlusPlus &&
Douglas Gregor85910982010-02-12 05:48:04 +0000523 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
524 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000525
526 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
527 BuiltinID, S.TUScope,
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000528 R.isForRedeclaration(),
529 R.getNameLoc())) {
Douglas Gregor85910982010-02-12 05:48:04 +0000530 R.addDecl(D);
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000531 return true;
532 }
533
534 if (R.isForRedeclaration()) {
535 // If we're redeclaring this function anyway, forget that
536 // this was a builtin at all.
537 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
538 }
539
540 return false;
Douglas Gregor85910982010-02-12 05:48:04 +0000541 }
542 }
543 }
544
545 return false;
546}
547
Douglas Gregor4923aa22010-07-02 20:37:36 +0000548/// \brief Determine whether we can declare a special member function within
549/// the class at this point.
Richard Smithd0adeb62012-11-27 21:20:31 +0000550static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor4923aa22010-07-02 20:37:36 +0000551 // We need to have a definition for the class.
552 if (!Class->getDefinition() || Class->isDependentContext())
553 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000554
Douglas Gregor4923aa22010-07-02 20:37:36 +0000555 // We can't be in the middle of defining the class.
Richard Smithd0adeb62012-11-27 21:20:31 +0000556 return !Class->isBeingDefined();
Douglas Gregor4923aa22010-07-02 20:37:36 +0000557}
558
559void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smithd0adeb62012-11-27 21:20:31 +0000560 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregor22584312010-07-02 23:41:54 +0000561 return;
Douglas Gregor18274032010-07-03 00:47:00 +0000562
563 // If the default constructor has not yet been declared, do so now.
Sean Huntcdee3fe2011-05-11 22:34:38 +0000564 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +0000565 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000566
Douglas Gregor22584312010-07-02 23:41:54 +0000567 // If the copy constructor has not yet been declared, do so now.
Richard Smithe5411b72012-12-01 02:35:44 +0000568 if (Class->needsImplicitCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +0000569 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000570
Douglas Gregora376d102010-07-02 21:50:04 +0000571 // If the copy assignment operator has not yet been declared, do so now.
Richard Smithe5411b72012-12-01 02:35:44 +0000572 if (Class->needsImplicitCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +0000573 DeclareImplicitCopyAssignment(Class);
574
Richard Smith80ad52f2013-01-02 11:42:31 +0000575 if (getLangOpts().CPlusPlus11) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000576 // If the move constructor has not yet been declared, do so now.
577 if (Class->needsImplicitMoveConstructor())
578 DeclareImplicitMoveConstructor(Class); // might not actually do it
579
580 // If the move assignment operator has not yet been declared, do so now.
581 if (Class->needsImplicitMoveAssignment())
582 DeclareImplicitMoveAssignment(Class); // might not actually do it
583 }
584
Douglas Gregor4923aa22010-07-02 20:37:36 +0000585 // If the destructor has not yet been declared, do so now.
Richard Smithe5411b72012-12-01 02:35:44 +0000586 if (Class->needsImplicitDestructor())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000587 DeclareImplicitDestructor(Class);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000588}
589
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000590/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregora376d102010-07-02 21:50:04 +0000591/// special member function.
592static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
593 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000594 case DeclarationName::CXXConstructorName:
Douglas Gregora376d102010-07-02 21:50:04 +0000595 case DeclarationName::CXXDestructorName:
596 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000597
Douglas Gregora376d102010-07-02 21:50:04 +0000598 case DeclarationName::CXXOperatorName:
599 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000600
Douglas Gregora376d102010-07-02 21:50:04 +0000601 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000602 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000603 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000604
Douglas Gregora376d102010-07-02 21:50:04 +0000605 return false;
606}
607
608/// \brief If there are any implicit member functions with the given name
609/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000610static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregora376d102010-07-02 21:50:04 +0000611 DeclarationName Name,
612 const DeclContext *DC) {
613 if (!DC)
614 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000615
Douglas Gregora376d102010-07-02 21:50:04 +0000616 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000617 case DeclarationName::CXXConstructorName:
618 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smithd0adeb62012-11-27 21:20:31 +0000619 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000620 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Sean Huntcdee3fe2011-05-11 22:34:38 +0000621 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000622 S.DeclareImplicitDefaultConstructor(Class);
Richard Smithe5411b72012-12-01 02:35:44 +0000623 if (Record->needsImplicitCopyConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000624 S.DeclareImplicitCopyConstructor(Class);
Richard Smith80ad52f2013-01-02 11:42:31 +0000625 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000626 Record->needsImplicitMoveConstructor())
627 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +0000628 }
Douglas Gregor22584312010-07-02 23:41:54 +0000629 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000630
Douglas Gregora376d102010-07-02 21:50:04 +0000631 case DeclarationName::CXXDestructorName:
632 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smithe5411b72012-12-01 02:35:44 +0000633 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smithd0adeb62012-11-27 21:20:31 +0000634 CanDeclareSpecialMemberFunction(Record))
Douglas Gregora376d102010-07-02 21:50:04 +0000635 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregora376d102010-07-02 21:50:04 +0000636 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000637
Douglas Gregora376d102010-07-02 21:50:04 +0000638 case DeclarationName::CXXOperatorName:
639 if (Name.getCXXOverloadedOperator() != OO_Equal)
640 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000641
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000642 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smithd0adeb62012-11-27 21:20:31 +0000643 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000644 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smithe5411b72012-12-01 02:35:44 +0000645 if (Record->needsImplicitCopyAssignment())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000646 S.DeclareImplicitCopyAssignment(Class);
Richard Smith80ad52f2013-01-02 11:42:31 +0000647 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000648 Record->needsImplicitMoveAssignment())
649 S.DeclareImplicitMoveAssignment(Class);
650 }
651 }
Douglas Gregora376d102010-07-02 21:50:04 +0000652 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000653
Douglas Gregora376d102010-07-02 21:50:04 +0000654 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000655 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000656 }
657}
Douglas Gregor4923aa22010-07-02 20:37:36 +0000658
John McCallf36e02d2009-10-09 21:13:30 +0000659// Adds all qualifying matches for a name within a decl context to the
660// given lookup result. Returns true if any matches were found.
Douglas Gregor85910982010-02-12 05:48:04 +0000661static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000662 bool Found = false;
663
Douglas Gregor4923aa22010-07-02 20:37:36 +0000664 // Lazily declare C++ special member functions.
David Blaikie4e4d0842012-03-11 07:00:24 +0000665 if (S.getLangOpts().CPlusPlus)
Douglas Gregora376d102010-07-02 21:50:04 +0000666 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000667
Douglas Gregor4923aa22010-07-02 20:37:36 +0000668 // Perform lookup into this declaration context.
David Blaikie3bc93e32012-12-19 00:45:41 +0000669 DeclContext::lookup_const_result DR = DC->lookup(R.getLookupName());
670 for (DeclContext::lookup_const_iterator I = DR.begin(), E = DR.end(); I != E;
671 ++I) {
John McCall46460a62010-01-20 21:53:11 +0000672 NamedDecl *D = *I;
Douglas Gregor55368912011-12-14 16:03:29 +0000673 if ((D = R.getAcceptableDecl(D))) {
John McCall46460a62010-01-20 21:53:11 +0000674 R.addDecl(D);
Douglas Gregor48026d22010-01-11 18:40:55 +0000675 Found = true;
676 }
677 }
John McCallf36e02d2009-10-09 21:13:30 +0000678
Douglas Gregor85910982010-02-12 05:48:04 +0000679 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
680 return true;
681
Douglas Gregor48026d22010-01-11 18:40:55 +0000682 if (R.getLookupName().getNameKind()
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000683 != DeclarationName::CXXConversionFunctionName ||
684 R.getLookupName().getCXXNameType()->isDependentType() ||
685 !isa<CXXRecordDecl>(DC))
686 return Found;
687
688 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000689 // A specialization of a conversion function template is not found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000690 // name lookup. Instead, any conversion function templates visible in the
691 // context of the use are considered. [...]
692 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCall5e1cdac2011-10-07 06:10:15 +0000693 if (!Record->isCompleteDefinition())
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000694 return Found;
695
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +0000696 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
697 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000698 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
699 if (!ConvTemplate)
700 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000701
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000702 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000703 // add the conversion function template. When we deduce template
704 // arguments for specializations, we'll end up unifying the return
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000705 // type of the new declaration with the type of the function template.
706 if (R.isForRedeclaration()) {
707 R.addDecl(ConvTemplate);
708 Found = true;
709 continue;
710 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000711
Douglas Gregor48026d22010-01-11 18:40:55 +0000712 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000713 // [...] For each such operator, if argument deduction succeeds
714 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000715 // name lookup.
716 //
717 // When referencing a conversion function for any purpose other than
718 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000719 // result), perform template argument deduction and place the
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000720 // specialization into the result set. We do this to avoid forcing all
721 // callers to perform special deduction for conversion functions.
Craig Topper93e45992012-09-19 02:26:47 +0000722 TemplateDeductionInfo Info(R.getNameLoc());
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000723 FunctionDecl *Specialization = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000724
725 const FunctionProtoType *ConvProto
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000726 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
727 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3f477a12010-01-12 01:17:50 +0000728
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000729 // Compute the type of the function that we would expect the conversion
730 // function to have, if it were to match the name given.
731 // FIXME: Calling convention!
John McCalle23cf432010-12-14 08:05:40 +0000732 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
Reid Kleckneref072032013-08-27 23:08:25 +0000733 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
Sebastian Redl8b5b4092011-03-06 10:52:04 +0000734 EPI.ExceptionSpecType = EST_None;
John McCalle23cf432010-12-14 08:05:40 +0000735 EPI.NumExceptions = 0;
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000736 QualType ExpectedType
737 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
Dmitri Gribenko55431692013-05-05 00:41:58 +0000738 None, EPI);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000739
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000740 // Perform template argument deduction against the type that we would
741 // expect the function to have.
742 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
743 Specialization, Info)
744 == Sema::TDK_Success) {
745 R.addDecl(Specialization);
746 Found = true;
Douglas Gregor48026d22010-01-11 18:40:55 +0000747 }
748 }
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000749
John McCallf36e02d2009-10-09 21:13:30 +0000750 return Found;
751}
752
John McCalld7be78a2009-11-10 07:01:13 +0000753// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000754static bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000755CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregor85910982010-02-12 05:48:04 +0000756 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000757
758 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
759
John McCalld7be78a2009-11-10 07:01:13 +0000760 // Perform direct name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +0000761 bool Found = LookupDirect(S, R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000762
John McCalld7be78a2009-11-10 07:01:13 +0000763 // Perform direct name lookup into the namespaces nominated by the
764 // using directives whose common ancestor is this namespace.
765 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
766 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000767
John McCalld7be78a2009-11-10 07:01:13 +0000768 for (; UI != UEnd; ++UI)
Douglas Gregor85910982010-02-12 05:48:04 +0000769 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000770 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000771
772 R.resolveKind();
773
774 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000775}
776
777static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000778 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000779 return Ctx->isFileContext();
780 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000781}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000782
Douglas Gregor711be1e2010-03-15 14:33:29 +0000783// Find the next outer declaration context from this scope. This
784// routine actually returns the semantic outer context, which may
785// differ from the lexical context (encoded directly in the Scope
786// stack) when we are parsing a member of a class template. In this
787// case, the second element of the pair will be true, to indicate that
788// name lookup should continue searching in this semantic context when
789// it leaves the current template parameter scope.
790static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
791 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
792 DeclContext *Lexical = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000793 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor711be1e2010-03-15 14:33:29 +0000794 OuterS = OuterS->getParent()) {
795 if (OuterS->getEntity()) {
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000796 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor711be1e2010-03-15 14:33:29 +0000797 break;
798 }
799 }
800
801 // C++ [temp.local]p8:
802 // In the definition of a member of a class template that appears
803 // outside of the namespace containing the class template
804 // definition, the name of a template-parameter hides the name of
805 // a member of this namespace.
806 //
807 // Example:
808 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000809 // namespace N {
810 // class C { };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000811 //
812 // template<class T> class B {
813 // void f(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000814 // };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000815 // }
816 //
817 // template<class C> void N::B<C>::f(C) {
818 // C b; // C is the template parameter, not N::C
819 // }
820 //
821 // In this example, the lexical context we return is the
822 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000823 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor711be1e2010-03-15 14:33:29 +0000824 !S->getParent()->isTemplateParamScope())
825 return std::make_pair(Lexical, false);
826
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000827 // Find the outermost template parameter scope.
Douglas Gregor711be1e2010-03-15 14:33:29 +0000828 // For the example, this is the scope for the template parameters of
829 // template<class C>.
830 Scope *OutermostTemplateScope = S->getParent();
831 while (OutermostTemplateScope->getParent() &&
832 OutermostTemplateScope->getParent()->isTemplateParamScope())
833 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000834
Douglas Gregor711be1e2010-03-15 14:33:29 +0000835 // Find the namespace context in which the original scope occurs. In
836 // the example, this is namespace N.
837 DeclContext *Semantic = DC;
838 while (!Semantic->isFileContext())
839 Semantic = Semantic->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000840
Douglas Gregor711be1e2010-03-15 14:33:29 +0000841 // Find the declaration context just outside of the template
842 // parameter scope. This is the context in which the template is
843 // being lexically declaration (a namespace context). In the
844 // example, this is the global scope.
845 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
846 Lexical->Encloses(Semantic))
847 return std::make_pair(Semantic, true);
848
849 return std::make_pair(Lexical, false);
Douglas Gregore942bbe2009-09-10 16:57:35 +0000850}
851
Richard Smitha41c97a2013-09-20 01:15:31 +0000852namespace {
853/// An RAII object to specify that we want to find block scope extern
854/// declarations.
855struct FindLocalExternScope {
856 FindLocalExternScope(LookupResult &R)
857 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
858 Decl::IDNS_LocalExtern) {
859 R.setFindLocalExtern(R.getIdentifierNamespace() & Decl::IDNS_Ordinary);
860 }
861 void restore() {
862 R.setFindLocalExtern(OldFindLocalExtern);
863 }
864 ~FindLocalExternScope() {
865 restore();
866 }
867 LookupResult &R;
868 bool OldFindLocalExtern;
869};
870}
871
John McCalla24dc2e2009-11-17 02:14:36 +0000872bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000873 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000874
875 DeclarationName Name = R.getLookupName();
Richard Smithdd9459f2013-08-13 18:18:50 +0000876 Sema::LookupNameKind NameKind = R.getLookupKind();
John McCalla24dc2e2009-11-17 02:14:36 +0000877
Douglas Gregora376d102010-07-02 21:50:04 +0000878 // If this is the name of an implicitly-declared special member function,
879 // go through the scope stack to implicitly declare
880 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
881 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
882 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
883 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
884 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000885
Douglas Gregora376d102010-07-02 21:50:04 +0000886 // Implicitly declare member functions with the name we're looking for, if in
887 // fact we are in a scope where it matters.
888
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000889 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000890 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000891 I = IdResolver.begin(Name),
892 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000893
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000894 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000895 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000896 // ...During unqualified name lookup (3.4.1), the names appear as if
897 // they were declared in the nearest enclosing namespace which contains
898 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000899 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000900 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000901 //
902 // For example:
903 // namespace A { int i; }
904 // void foo() {
905 // int i;
906 // {
907 // using namespace A;
908 // ++i; // finds local 'i', A::i appears at global scope
909 // }
910 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000911 //
Douglas Gregor44b2ea92013-04-08 23:11:25 +0000912 UnqualUsingDirectiveSet UDirs;
913 bool VisitedUsingDirectives = false;
Richard Smithdd9459f2013-08-13 18:18:50 +0000914 bool LeftStartingScope = false;
Douglas Gregor711be1e2010-03-15 14:33:29 +0000915 DeclContext *OutsideOfTemplateParamDC = 0;
Richard Smitha41c97a2013-09-20 01:15:31 +0000916
917 // When performing a scope lookup, we want to find local extern decls.
918 FindLocalExternScope FindLocals(R);
919
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000920 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregord2235f62010-05-20 20:58:56 +0000921 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
922
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000923 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000924 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000925 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor55368912011-12-14 16:03:29 +0000926 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Richard Smithdd9459f2013-08-13 18:18:50 +0000927 if (NameKind == LookupRedeclarationWithLinkage) {
928 // Determine whether this (or a previous) declaration is
929 // out-of-scope.
930 if (!LeftStartingScope && !Initial->isDeclScope(*I))
931 LeftStartingScope = true;
932
933 // If we found something outside of our starting scope that
934 // does not have linkage, skip it.
935 if (LeftStartingScope && !((*I)->hasLinkage())) {
936 R.setShadowed();
937 continue;
938 }
939 }
940
John McCallf36e02d2009-10-09 21:13:30 +0000941 Found = true;
Douglas Gregor55368912011-12-14 16:03:29 +0000942 R.addDecl(ND);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000943 }
944 }
John McCallf36e02d2009-10-09 21:13:30 +0000945 if (Found) {
946 R.resolveKind();
Douglas Gregord2235f62010-05-20 20:58:56 +0000947 if (S->isClassScope())
948 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
949 R.setNamingClass(Record);
John McCallf36e02d2009-10-09 21:13:30 +0000950 return true;
951 }
952
Richard Smithdd9459f2013-08-13 18:18:50 +0000953 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
Richard Smith4e9686b2013-08-09 04:35:01 +0000954 // C++11 [class.friend]p11:
955 // If a friend declaration appears in a local class and the name
956 // specified is an unqualified name, a prior declaration is
957 // looked up without considering scopes that are outside the
958 // innermost enclosing non-class scope.
959 return false;
960 }
961
Douglas Gregor711be1e2010-03-15 14:33:29 +0000962 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
963 S->getParent() && !S->getParent()->isTemplateParamScope()) {
964 // We've just searched the last template parameter scope and
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +0000965 // found nothing, so look into the contexts between the
Douglas Gregor711be1e2010-03-15 14:33:29 +0000966 // lexical and semantic declaration contexts returned by
967 // findOuterContext(). This implements the name lookup behavior
968 // of C++ [temp.local]p8.
969 Ctx = OutsideOfTemplateParamDC;
970 OutsideOfTemplateParamDC = 0;
971 }
972
973 if (Ctx) {
974 DeclContext *OuterCtx;
975 bool SearchAfterTemplateScope;
976 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
977 if (SearchAfterTemplateScope)
978 OutsideOfTemplateParamDC = OuterCtx;
979
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000980 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-02-19 16:08:35 +0000981 // We do not directly look into transparent contexts, since
982 // those entities will be found in the nearest enclosing
983 // non-transparent context.
984 if (Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000985 continue;
Douglas Gregor36262b82010-02-19 16:08:35 +0000986
987 // We do not look directly into function or method contexts,
988 // since all of the local variables and parameters of the
989 // function/method are present within the Scope.
990 if (Ctx->isFunctionOrMethod()) {
991 // If we have an Objective-C instance method, look for ivars
992 // in the corresponding interface.
993 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
994 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
995 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
996 ObjCInterfaceDecl *ClassDeclared;
997 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000998 Name.getAsIdentifierInfo(),
Douglas Gregor36262b82010-02-19 16:08:35 +0000999 ClassDeclared)) {
Douglas Gregor55368912011-12-14 16:03:29 +00001000 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1001 R.addDecl(ND);
Douglas Gregor36262b82010-02-19 16:08:35 +00001002 R.resolveKind();
1003 return true;
1004 }
1005 }
1006 }
1007 }
1008
1009 continue;
1010 }
1011
Douglas Gregor6bed88e2013-03-27 12:51:49 +00001012 // If this is a file context, we need to perform unqualified name
1013 // lookup considering using directives.
1014 if (Ctx->isFileContext()) {
Douglas Gregor44b2ea92013-04-08 23:11:25 +00001015 // If we haven't handled using directives yet, do so now.
1016 if (!VisitedUsingDirectives) {
1017 // Add using directives from this context up to the top level.
Douglas Gregor34366202013-04-09 01:49:26 +00001018 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1019 if (UCtx->isTransparentContext())
1020 continue;
1021
Douglas Gregor44b2ea92013-04-08 23:11:25 +00001022 UDirs.visit(UCtx, UCtx);
Douglas Gregor34366202013-04-09 01:49:26 +00001023 }
Douglas Gregor44b2ea92013-04-08 23:11:25 +00001024
1025 // Find the innermost file scope, so we can add using directives
1026 // from local scopes.
1027 Scope *InnermostFileScope = S;
1028 while (InnermostFileScope &&
1029 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1030 InnermostFileScope = InnermostFileScope->getParent();
1031 UDirs.visitScopeChain(Initial, InnermostFileScope);
1032
1033 UDirs.done();
1034
1035 VisitedUsingDirectives = true;
1036 }
Douglas Gregor6bed88e2013-03-27 12:51:49 +00001037
1038 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1039 R.resolveKind();
1040 return true;
1041 }
1042
1043 continue;
1044 }
1045
Douglas Gregore942bbe2009-09-10 16:57:35 +00001046 // Perform qualified name lookup into this context.
1047 // FIXME: In some cases, we know that every name that could be found by
1048 // this qualified name lookup will also be on the identifier chain. For
1049 // example, inside a class without any base classes, we never need to
1050 // perform qualified lookup because all of the members are on top of the
1051 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001052 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +00001053 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +00001054 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001055 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001056 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001057
John McCalld7be78a2009-11-10 07:01:13 +00001058 // Stop if we ran out of scopes.
1059 // FIXME: This really, really shouldn't be happening.
1060 if (!S) return false;
1061
Argyrios Kyrtzidis78f59112010-10-29 16:12:50 +00001062 // If we are looking for members, no need to look into global/namespace scope.
Richard Smithdd9459f2013-08-13 18:18:50 +00001063 if (NameKind == LookupMemberName)
Argyrios Kyrtzidis78f59112010-10-29 16:12:50 +00001064 return false;
1065
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001066 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001067 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +00001068 //
Mike Stump390b4cc2009-05-16 07:39:55 +00001069 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1070 // don't build it for each lookup!
Douglas Gregor44b2ea92013-04-08 23:11:25 +00001071 if (!VisitedUsingDirectives) {
1072 UDirs.visitScopeChain(Initial, S);
1073 UDirs.done();
1074 }
Richard Smitha41c97a2013-09-20 01:15:31 +00001075
1076 // If we're not performing redeclaration lookup, do not look for local
1077 // extern declarations outside of a function scope.
1078 if (!R.isForRedeclaration())
1079 FindLocals.restore();
1080
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001081 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001082 // Unqualified name lookup in C++ requires looking into scopes
1083 // that aren't strictly lexical, and therefore we walk through the
1084 // context as well as walking through the scopes.
1085 for (; S; S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001086 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +00001087 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +00001088 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor55368912011-12-14 16:03:29 +00001089 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001090 // We found something. Look for anything else in our scope
1091 // with this same name and in an acceptable identifier
1092 // namespace, so that we can construct an overload set if we
1093 // need to.
John McCallf36e02d2009-10-09 21:13:30 +00001094 Found = true;
Douglas Gregor55368912011-12-14 16:03:29 +00001095 R.addDecl(ND);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001096 }
1097 }
1098
Douglas Gregor00b4b032010-05-14 04:53:42 +00001099 if (Found && S->isTemplateParamScope()) {
John McCallf36e02d2009-10-09 21:13:30 +00001100 R.resolveKind();
1101 return true;
1102 }
1103
Douglas Gregor00b4b032010-05-14 04:53:42 +00001104 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1105 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1106 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1107 // We've just searched the last template parameter scope and
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00001108 // found nothing, so look into the contexts between the
Douglas Gregor00b4b032010-05-14 04:53:42 +00001109 // lexical and semantic declaration contexts returned by
1110 // findOuterContext(). This implements the name lookup behavior
1111 // of C++ [temp.local]p8.
1112 Ctx = OutsideOfTemplateParamDC;
1113 OutsideOfTemplateParamDC = 0;
1114 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001115
Douglas Gregor00b4b032010-05-14 04:53:42 +00001116 if (Ctx) {
1117 DeclContext *OuterCtx;
1118 bool SearchAfterTemplateScope;
1119 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1120 if (SearchAfterTemplateScope)
1121 OutsideOfTemplateParamDC = OuterCtx;
1122
1123 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1124 // We do not directly look into transparent contexts, since
1125 // those entities will be found in the nearest enclosing
1126 // non-transparent context.
1127 if (Ctx->isTransparentContext())
1128 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001129
Douglas Gregor00b4b032010-05-14 04:53:42 +00001130 // If we have a context, and it's not a context stashed in the
1131 // template parameter scope for an out-of-line definition, also
1132 // look into that context.
1133 if (!(Found && S && S->isTemplateParamScope())) {
1134 assert(Ctx->isFileContext() &&
1135 "We should have been looking only at file context here already.");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001136
Douglas Gregor00b4b032010-05-14 04:53:42 +00001137 // Look into context considering using-directives.
1138 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1139 Found = true;
1140 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001141
Douglas Gregor00b4b032010-05-14 04:53:42 +00001142 if (Found) {
1143 R.resolveKind();
1144 return true;
1145 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001146
Douglas Gregor00b4b032010-05-14 04:53:42 +00001147 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1148 return false;
1149 }
1150 }
1151
Douglas Gregor1df0ee92010-02-05 07:07:10 +00001152 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +00001153 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001154 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001155
John McCallf36e02d2009-10-09 21:13:30 +00001156 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001157}
1158
Richard Smithb7751002013-07-25 23:08:39 +00001159/// \brief Find the declaration that a class temploid member specialization was
1160/// instantiated from, or the member itself if it is an explicit specialization.
1161static Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) {
1162 return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom();
1163}
1164
1165/// \brief Find the module in which the given declaration was defined.
1166static Module *getDefiningModule(Decl *Entity) {
1167 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1168 // If this function was instantiated from a template, the defining module is
1169 // the module containing the pattern.
1170 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1171 Entity = Pattern;
1172 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
1173 // If it's a class template specialization, find the template or partial
1174 // specialization from which it was instantiated.
1175 if (ClassTemplateSpecializationDecl *SpecRD =
1176 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
1177 llvm::PointerUnion<ClassTemplateDecl*,
1178 ClassTemplatePartialSpecializationDecl*> From =
1179 SpecRD->getInstantiatedFrom();
1180 if (ClassTemplateDecl *FromTemplate = From.dyn_cast<ClassTemplateDecl*>())
1181 Entity = FromTemplate->getTemplatedDecl();
1182 else if (From)
1183 Entity = From.get<ClassTemplatePartialSpecializationDecl*>();
1184 // Otherwise, it's an explicit specialization.
1185 } else if (MemberSpecializationInfo *MSInfo =
1186 RD->getMemberSpecializationInfo())
1187 Entity = getInstantiatedFrom(RD, MSInfo);
1188 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1189 if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo())
1190 Entity = getInstantiatedFrom(ED, MSInfo);
1191 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1192 // FIXME: Map from variable template specializations back to the template.
1193 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo())
1194 Entity = getInstantiatedFrom(VD, MSInfo);
1195 }
1196
1197 // Walk up to the containing context. That might also have been instantiated
1198 // from a template.
1199 DeclContext *Context = Entity->getDeclContext();
1200 if (Context->isFileContext())
1201 return Entity->getOwningModule();
1202 return getDefiningModule(cast<Decl>(Context));
1203}
1204
1205llvm::DenseSet<Module*> &Sema::getLookupModules() {
1206 unsigned N = ActiveTemplateInstantiations.size();
1207 for (unsigned I = ActiveTemplateInstantiationLookupModules.size();
1208 I != N; ++I) {
1209 Module *M = getDefiningModule(ActiveTemplateInstantiations[I].Entity);
1210 if (M && !LookupModulesCache.insert(M).second)
1211 M = 0;
1212 ActiveTemplateInstantiationLookupModules.push_back(M);
1213 }
1214 return LookupModulesCache;
1215}
1216
1217/// \brief Determine whether a declaration is visible to name lookup.
1218///
1219/// This routine determines whether the declaration D is visible in the current
1220/// lookup context, taking into account the current template instantiation
1221/// stack. During template instantiation, a declaration is visible if it is
1222/// visible from a module containing any entity on the template instantiation
1223/// path (by instantiating a template, you allow it to see the declarations that
1224/// your module can see, including those later on in your module).
1225bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
1226 assert(D->isHidden() && !SemaRef.ActiveTemplateInstantiations.empty() &&
1227 "should not call this: not in slow case");
1228 Module *DeclModule = D->getOwningModule();
1229 assert(DeclModule && "hidden decl not from a module");
1230
1231 // Find the extra places where we need to look.
1232 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
1233 if (LookupModules.empty())
1234 return false;
1235
1236 // If our lookup set contains the decl's module, it's visible.
1237 if (LookupModules.count(DeclModule))
1238 return true;
1239
1240 // If the declaration isn't exported, it's not visible in any other module.
1241 if (D->isModulePrivate())
1242 return false;
1243
1244 // Check whether DeclModule is transitively exported to an import of
1245 // the lookup set.
1246 for (llvm::DenseSet<Module *>::iterator I = LookupModules.begin(),
1247 E = LookupModules.end();
1248 I != E; ++I)
1249 if ((*I)->isModuleVisible(DeclModule))
1250 return true;
1251 return false;
1252}
1253
Douglas Gregor55368912011-12-14 16:03:29 +00001254/// \brief Retrieve the visible declaration corresponding to D, if any.
1255///
1256/// This routine determines whether the declaration D is visible in the current
1257/// module, with the current imports. If not, it checks whether any
1258/// redeclaration of D is visible, and if so, returns that declaration.
Richard Smithb7751002013-07-25 23:08:39 +00001259///
Douglas Gregor55368912011-12-14 16:03:29 +00001260/// \returns D, or a visible previous declaration of D, whichever is more recent
1261/// and visible. If no declaration of D is visible, returns null.
Richard Smithd67679d2013-08-20 20:35:18 +00001262static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
1263 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
Richard Smithb7751002013-07-25 23:08:39 +00001264
Douglas Gregor0782ef22012-01-06 22:05:37 +00001265 for (Decl::redecl_iterator RD = D->redecls_begin(), RDEnd = D->redecls_end();
1266 RD != RDEnd; ++RD) {
David Blaikie581deb32012-06-06 20:45:41 +00001267 if (NamedDecl *ND = dyn_cast<NamedDecl>(*RD)) {
Richard Smithd67679d2013-08-20 20:35:18 +00001268 if (LookupResult::isVisible(SemaRef, ND))
Douglas Gregor0782ef22012-01-06 22:05:37 +00001269 return ND;
1270 }
Douglas Gregor55368912011-12-14 16:03:29 +00001271 }
Richard Smithb7751002013-07-25 23:08:39 +00001272
Douglas Gregor55368912011-12-14 16:03:29 +00001273 return 0;
1274}
1275
Richard Smithd67679d2013-08-20 20:35:18 +00001276NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
1277 return findAcceptableDecl(SemaRef, D);
1278}
1279
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001280/// @brief Perform unqualified name lookup starting from a given
1281/// scope.
1282///
1283/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1284/// used to find names within the current scope. For example, 'x' in
1285/// @code
1286/// int x;
1287/// int f() {
1288/// return x; // unqualified name look finds 'x' in the global scope
1289/// }
1290/// @endcode
1291///
1292/// Different lookup criteria can find different names. For example, a
1293/// particular scope can have both a struct and a function of the same
1294/// name, and each can be found by certain lookup criteria. For more
1295/// information about lookup criteria, see the documentation for the
1296/// class LookupCriteria.
1297///
1298/// @param S The scope from which unqualified name lookup will
1299/// begin. If the lookup criteria permits, name lookup may also search
1300/// in the parent scopes.
1301///
James Dennett8da16872012-06-22 10:32:46 +00001302/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1303/// look up and the lookup kind), and is updated with the results of lookup
1304/// including zero or more declarations and possibly additional information
1305/// used to diagnose ambiguities.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001306///
James Dennett8da16872012-06-22 10:32:46 +00001307/// @returns \c true if lookup succeeded and false otherwise.
John McCalla24dc2e2009-11-17 02:14:36 +00001308bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1309 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +00001310 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001311
John McCalla24dc2e2009-11-17 02:14:36 +00001312 LookupNameKind NameKind = R.getLookupKind();
1313
David Blaikie4e4d0842012-03-11 07:00:24 +00001314 if (!getLangOpts().CPlusPlus) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001315 // Unqualified name lookup in C/Objective-C is purely lexical, so
1316 // search in the declarations attached to the name.
John McCall1d7c5282009-12-18 10:40:03 +00001317 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001318 // Find the nearest non-transparent declaration scope.
1319 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001320 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001321 static_cast<DeclContext *>(S->getEntity())
1322 ->isTransparentContext()))
1323 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001324 }
1325
Richard Smitha41c97a2013-09-20 01:15:31 +00001326 // When performing a scope lookup, we want to find local extern decls.
1327 FindLocalExternScope FindLocals(R);
1328
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001329 // Scan up the scope chain looking for a decl that matches this
1330 // identifier that is in the appropriate namespace. This search
1331 // should not take long, as shadowing of names is uncommon, and
1332 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001333 bool LeftStartingScope = false;
1334
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001335 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +00001336 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001337 I != IEnd; ++I)
Richard Smithb7751002013-07-25 23:08:39 +00001338 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001339 if (NameKind == LookupRedeclarationWithLinkage) {
1340 // Determine whether this (or a previous) declaration is
1341 // out-of-scope.
John McCalld226f652010-08-21 09:40:31 +00001342 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001343 LeftStartingScope = true;
1344
1345 // If we found something outside of our starting scope that
1346 // does not have linkage, skip it.
Richard Smithdd9459f2013-08-13 18:18:50 +00001347 if (LeftStartingScope && !((*I)->hasLinkage())) {
1348 R.setShadowed();
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001349 continue;
Richard Smithdd9459f2013-08-13 18:18:50 +00001350 }
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001351 }
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001352 else if (NameKind == LookupObjCImplicitSelfParam &&
1353 !isa<ImplicitParamDecl>(*I))
1354 continue;
Richard Smithb7751002013-07-25 23:08:39 +00001355
Douglas Gregor55368912011-12-14 16:03:29 +00001356 R.addDecl(D);
John McCallf36e02d2009-10-09 21:13:30 +00001357
Douglas Gregor7a537402012-01-03 23:26:26 +00001358 // Check whether there are any other declarations with the same name
1359 // and in the same scope.
Douglas Gregorda795b42012-01-04 16:44:10 +00001360 if (I != IEnd) {
Douglas Gregor117c4562012-01-13 23:06:53 +00001361 // Find the scope in which this declaration was declared (if it
1362 // actually exists in a Scope).
1363 while (S && !S->isDeclScope(D))
1364 S = S->getParent();
1365
1366 // If the scope containing the declaration is the translation unit,
1367 // then we'll need to perform our checks based on the matching
1368 // DeclContexts rather than matching scopes.
1369 if (S && isNamespaceOrTranslationUnitScope(S))
1370 S = 0;
1371
1372 // Compute the DeclContext, if we need it.
1373 DeclContext *DC = 0;
1374 if (!S)
1375 DC = (*I)->getDeclContext()->getRedeclContext();
1376
Douglas Gregorda795b42012-01-04 16:44:10 +00001377 IdentifierResolver::iterator LastI = I;
1378 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor117c4562012-01-13 23:06:53 +00001379 if (S) {
1380 // Match based on scope.
1381 if (!S->isDeclScope(*LastI))
1382 break;
1383 } else {
1384 // Match based on DeclContext.
1385 DeclContext *LastDC
1386 = (*LastI)->getDeclContext()->getRedeclContext();
1387 if (!LastDC->Equals(DC))
1388 break;
1389 }
Richard Smithb7751002013-07-25 23:08:39 +00001390
1391 // If the declaration is in the right namespace and visible, add it.
1392 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1393 R.addDecl(LastD);
Douglas Gregorda795b42012-01-04 16:44:10 +00001394 }
Douglas Gregorf9201e02009-02-11 23:02:49 +00001395
Douglas Gregorda795b42012-01-04 16:44:10 +00001396 R.resolveKind();
Douglas Gregorf9201e02009-02-11 23:02:49 +00001397 }
Richard Smitha41c97a2013-09-20 01:15:31 +00001398
John McCallf36e02d2009-10-09 21:13:30 +00001399 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +00001400 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001401 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001402 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +00001403 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +00001404 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001405 }
1406
1407 // If we didn't find a use of this identifier, and if the identifier
1408 // corresponds to a compiler builtin, create the decl object for the builtin
1409 // now, injecting it into translation unit scope, and return it.
Axel Naumann42151d52011-04-13 13:19:46 +00001410 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1411 return true;
Douglas Gregor3e41d602009-02-13 23:20:09 +00001412
Axel Naumannf8291a12011-02-24 16:47:47 +00001413 // If we didn't find a use of this identifier, the ExternalSource
1414 // may be able to handle the situation.
1415 // Note: some lookup failures are expected!
1416 // See e.g. R.isForRedeclaration().
1417 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001418}
1419
John McCall6e247262009-10-10 05:48:19 +00001420/// @brief Perform qualified name lookup in the namespaces nominated by
1421/// using directives by the given context.
1422///
1423/// C++98 [namespace.qual]p2:
James Dennett7ba75922012-06-19 21:05:49 +00001424/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6e247262009-10-10 05:48:19 +00001425/// (where X is the global namespace), let S be the set of all
1426/// declarations of m in X and in the transitive closure of all
1427/// namespaces nominated by using-directives in X and its used
1428/// namespaces, except that using-directives are ignored in any
1429/// namespace, including X, directly containing one or more
1430/// declarations of m. No namespace is searched more than once in
1431/// the lookup of a name. If S is the empty set, the program is
1432/// ill-formed. Otherwise, if S has exactly one member, or if the
1433/// context of the reference is a using-declaration
1434/// (namespace.udecl), S is the required set of declarations of
1435/// m. Otherwise if the use of m is not one that allows a unique
1436/// declaration to be chosen from S, the program is ill-formed.
James Dennett7ba75922012-06-19 21:05:49 +00001437///
John McCall6e247262009-10-10 05:48:19 +00001438/// C++98 [namespace.qual]p5:
1439/// During the lookup of a qualified namespace member name, if the
1440/// lookup finds more than one declaration of the member, and if one
1441/// declaration introduces a class name or enumeration name and the
1442/// other declarations either introduce the same object, the same
1443/// enumerator or a set of functions, the non-type name hides the
1444/// class or enumeration name if and only if the declarations are
1445/// from the same namespace; otherwise (the declarations are from
1446/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +00001447static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +00001448 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +00001449 assert(StartDC->isFileContext() && "start context is not a file context");
1450
1451 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1452 DeclContext::udir_iterator E = StartDC->using_directives_end();
1453
1454 if (I == E) return false;
1455
1456 // We have at least added all these contexts to the queue.
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001457 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6e247262009-10-10 05:48:19 +00001458 Visited.insert(StartDC);
1459
1460 // We have not yet looked into these namespaces, much less added
1461 // their "using-children" to the queue.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001462 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6e247262009-10-10 05:48:19 +00001463
1464 // We have already looked into the initial namespace; seed the queue
1465 // with its using-children.
1466 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001467 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001468 if (Visited.insert(ND))
John McCall6e247262009-10-10 05:48:19 +00001469 Queue.push_back(ND);
1470 }
1471
1472 // The easiest way to implement the restriction in [namespace.qual]p5
1473 // is to check whether any of the individual results found a tag
1474 // and, if so, to declare an ambiguity if the final result is not
1475 // a tag.
1476 bool FoundTag = false;
1477 bool FoundNonTag = false;
1478
John McCall7d384dd2009-11-18 07:57:50 +00001479 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001480
1481 bool Found = false;
1482 while (!Queue.empty()) {
Robert Wilhelm344472e2013-08-23 16:11:15 +00001483 NamespaceDecl *ND = Queue.pop_back_val();
John McCall6e247262009-10-10 05:48:19 +00001484
1485 // We go through some convolutions here to avoid copying results
1486 // between LookupResults.
1487 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001488 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001489 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001490
1491 if (FoundDirect) {
1492 // First do any local hiding.
1493 DirectR.resolveKind();
1494
1495 // If the local result is a tag, remember that.
1496 if (DirectR.isSingleTagDecl())
1497 FoundTag = true;
1498 else
1499 FoundNonTag = true;
1500
1501 // Append the local results to the total results if necessary.
1502 if (UseLocal) {
1503 R.addAllDecls(LocalR);
1504 LocalR.clear();
1505 }
1506 }
1507
1508 // If we find names in this namespace, ignore its using directives.
1509 if (FoundDirect) {
1510 Found = true;
1511 continue;
1512 }
1513
1514 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1515 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001516 if (Visited.insert(Nom))
John McCall6e247262009-10-10 05:48:19 +00001517 Queue.push_back(Nom);
1518 }
1519 }
1520
1521 if (Found) {
1522 if (FoundTag && FoundNonTag)
1523 R.setAmbiguousQualifiedTagHiding();
1524 else
1525 R.resolveKind();
1526 }
1527
1528 return Found;
1529}
1530
Douglas Gregor8071e422010-08-15 06:18:01 +00001531/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001532static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor8071e422010-08-15 06:18:01 +00001533 CXXBasePath &Path,
1534 void *Name) {
1535 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001536
Douglas Gregor8071e422010-08-15 06:18:01 +00001537 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1538 Path.Decls = BaseRecord->lookup(N);
David Blaikie3bc93e32012-12-19 00:45:41 +00001539 return !Path.Decls.empty();
Douglas Gregor8071e422010-08-15 06:18:01 +00001540}
1541
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001542/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001543/// static members, nested types, and enumerators.
1544template<typename InputIterator>
1545static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1546 Decl *D = (*First)->getUnderlyingDecl();
1547 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1548 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001549
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001550 if (isa<CXXMethodDecl>(D)) {
1551 // Determine whether all of the methods are static.
1552 bool AllMethodsAreStatic = true;
1553 for(; First != Last; ++First) {
1554 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001555
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001556 if (!isa<CXXMethodDecl>(D)) {
1557 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1558 break;
1559 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001560
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001561 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1562 AllMethodsAreStatic = false;
1563 break;
1564 }
1565 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001566
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001567 if (AllMethodsAreStatic)
1568 return true;
1569 }
1570
1571 return false;
1572}
1573
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001574/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001575///
1576/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1577/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001578/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001579///
1580/// Different lookup criteria can find different names. For example, a
1581/// particular scope can have both a struct and a function of the same
1582/// name, and each can be found by certain lookup criteria. For more
1583/// information about lookup criteria, see the documentation for the
1584/// class LookupCriteria.
1585///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001586/// \param R captures both the lookup criteria and any lookup results found.
1587///
1588/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001589/// search. If the lookup criteria permits, name lookup may also search
1590/// in the parent contexts or (for C++ classes) base classes.
1591///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001592/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001593/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001594///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001595/// \returns true if lookup succeeded, false if it failed.
1596bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1597 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001598 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001599
John McCalla24dc2e2009-11-17 02:14:36 +00001600 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001601 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001602
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001603 // Make sure that the declaration context is complete.
1604 assert((!isa<TagDecl>(LookupCtx) ||
1605 LookupCtx->isDependentContext() ||
John McCall5e1cdac2011-10-07 06:10:15 +00001606 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith1af83c42012-03-23 03:33:32 +00001607 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001608 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001609
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001610 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001611 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001612 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001613 if (isa<CXXRecordDecl>(LookupCtx))
1614 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001615 return true;
1616 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001617
John McCall6e247262009-10-10 05:48:19 +00001618 // Don't descend into implied contexts for redeclarations.
1619 // C++98 [namespace.qual]p6:
1620 // In a declaration for a namespace member in which the
1621 // declarator-id is a qualified-id, given that the qualified-id
1622 // for the namespace member has the form
1623 // nested-name-specifier unqualified-id
1624 // the unqualified-id shall name a member of the namespace
1625 // designated by the nested-name-specifier.
1626 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001627 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001628 return false;
1629
John McCalla24dc2e2009-11-17 02:14:36 +00001630 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001631 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001632 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001633
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001634 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001635 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001636 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor025291b2010-07-01 00:21:21 +00001637 if (!LookupRec || !LookupRec->getDefinition())
John McCallf36e02d2009-10-09 21:13:30 +00001638 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001639
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001640 // If we're performing qualified name lookup into a dependent class,
1641 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001642 // dependent base classes, then we either have to delay lookup until
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001643 // template instantiation time (at which point all bases will be available)
1644 // or we have to fail.
1645 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1646 LookupRec->hasAnyDependentBases()) {
1647 R.setNotFoundInCurrentInstantiation();
1648 return false;
1649 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001650
Douglas Gregor7176fff2009-01-15 00:26:24 +00001651 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001652 CXXBasePaths Paths;
1653 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001654
1655 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001656 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001657 switch (R.getLookupKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001658 case LookupObjCImplicitSelfParam:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001659 case LookupOrdinaryName:
1660 case LookupMemberName:
1661 case LookupRedeclarationWithLinkage:
Richard Smith4e9686b2013-08-09 04:35:01 +00001662 case LookupLocalFriendName:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001663 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1664 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001665
Douglas Gregora8f32e02009-10-06 17:59:45 +00001666 case LookupTagName:
1667 BaseCallback = &CXXRecordDecl::FindTagMember;
1668 break;
John McCall9f54ad42009-12-10 09:41:52 +00001669
Douglas Gregor8071e422010-08-15 06:18:01 +00001670 case LookupAnyName:
1671 BaseCallback = &LookupAnyMember;
1672 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001673
John McCall9f54ad42009-12-10 09:41:52 +00001674 case LookupUsingDeclName:
1675 // This lookup is for redeclarations only.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001676
Douglas Gregora8f32e02009-10-06 17:59:45 +00001677 case LookupOperatorName:
1678 case LookupNamespaceName:
1679 case LookupObjCProtocolName:
Chris Lattner337e5502011-02-18 01:27:55 +00001680 case LookupLabel:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001681 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001682 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001683
Douglas Gregora8f32e02009-10-06 17:59:45 +00001684 case LookupNestedNameSpecifierName:
1685 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1686 break;
1687 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001688
John McCalla24dc2e2009-11-17 02:14:36 +00001689 if (!LookupRec->lookupInBases(BaseCallback,
1690 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001691 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001692
John McCall92f88312010-01-23 00:46:32 +00001693 R.setNamingClass(LookupRec);
1694
Douglas Gregor7176fff2009-01-15 00:26:24 +00001695 // C++ [class.member.lookup]p2:
1696 // [...] If the resulting set of declarations are not all from
1697 // sub-objects of the same type, or the set has a nonstatic member
1698 // and includes members from distinct sub-objects, there is an
1699 // ambiguity and the program is ill-formed. Otherwise that set is
1700 // the result of the lookup.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001701 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001702 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001703 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001704
Douglas Gregora8f32e02009-10-06 17:59:45 +00001705 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001706 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001707 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001708
John McCall46460a62010-01-20 21:53:11 +00001709 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1710 // across all paths.
1711 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001712
Douglas Gregor7176fff2009-01-15 00:26:24 +00001713 // Determine whether we're looking at a distinct sub-object or not.
1714 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001715 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001716 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1717 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001718 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001719 }
1720
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001721 if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001722 != Context.getCanonicalType(PathElement.Base->getType())) {
1723 // We found members of the given name in two subobjects of
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001724 // different types. If the declaration sets aren't the same, this
1725 // this lookup is ambiguous.
David Blaikie3bc93e32012-12-19 00:45:41 +00001726 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001727 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikie3bc93e32012-12-19 00:45:41 +00001728 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
1729 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001730
David Blaikie3bc93e32012-12-19 00:45:41 +00001731 while (FirstD != FirstPath->Decls.end() &&
1732 CurrentD != Path->Decls.end()) {
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001733 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1734 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1735 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001736
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001737 ++FirstD;
1738 ++CurrentD;
1739 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001740
David Blaikie3bc93e32012-12-19 00:45:41 +00001741 if (FirstD == FirstPath->Decls.end() &&
1742 CurrentD == Path->Decls.end())
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001743 continue;
1744 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001745
John McCallf36e02d2009-10-09 21:13:30 +00001746 R.setAmbiguousBaseSubobjectTypes(Paths);
1747 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001748 }
1749
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001750 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001751 // We have a different subobject of the same type.
1752
1753 // C++ [class.member.lookup]p5:
1754 // A static member, a nested type or an enumerator defined in
1755 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001756 // has more than one base class subobject of type T.
David Blaikie3bc93e32012-12-19 00:45:41 +00001757 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor7176fff2009-01-15 00:26:24 +00001758 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001759
Douglas Gregor7176fff2009-01-15 00:26:24 +00001760 // We have found a nonstatic member name in multiple, distinct
1761 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001762 R.setAmbiguousBaseSubobjects(Paths);
1763 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001764 }
1765 }
1766
1767 // Lookup in a base class succeeded; return these results.
1768
David Blaikie3bc93e32012-12-19 00:45:41 +00001769 DeclContext::lookup_result DR = Paths.front().Decls;
1770 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E; ++I) {
John McCall92f88312010-01-23 00:46:32 +00001771 NamedDecl *D = *I;
1772 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1773 D->getAccess());
1774 R.addDecl(D, AS);
1775 }
John McCallf36e02d2009-10-09 21:13:30 +00001776 R.resolveKind();
1777 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001778}
1779
1780/// @brief Performs name lookup for a name that was parsed in the
1781/// source code, and may contain a C++ scope specifier.
1782///
1783/// This routine is a convenience routine meant to be called from
1784/// contexts that receive a name and an optional C++ scope specifier
1785/// (e.g., "N::M::x"). It will then perform either qualified or
1786/// unqualified name lookup (with LookupQualifiedName or LookupName,
1787/// respectively) on the given name and return those results.
1788///
1789/// @param S The scope from which unqualified name lookup will
1790/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001791///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001792/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001793///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001794/// @param EnteringContext Indicates whether we are going to enter the
1795/// context of the scope-specifier SS (if present).
1796///
John McCallf36e02d2009-10-09 21:13:30 +00001797/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001798bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001799 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001800 if (SS && SS->isInvalid()) {
1801 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001802 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001803 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001804 }
Mike Stump1eb44332009-09-09 15:08:12 +00001805
Douglas Gregor495c35d2009-08-25 22:51:20 +00001806 if (SS && SS->isSet()) {
1807 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001808 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001809 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001810 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001811 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001812
John McCalla24dc2e2009-11-17 02:14:36 +00001813 R.setContextRange(SS->getRange());
John McCalla24dc2e2009-11-17 02:14:36 +00001814 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001815 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001816
Douglas Gregor495c35d2009-08-25 22:51:20 +00001817 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001818 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001819 // Name lookup can't find anything in this case.
Douglas Gregor3eafbb82011-10-24 22:24:50 +00001820 R.setNotFoundInCurrentInstantiation();
1821 R.setContextRange(SS->getRange());
John McCallf36e02d2009-10-09 21:13:30 +00001822 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001823 }
1824
Mike Stump1eb44332009-09-09 15:08:12 +00001825 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001826 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001827}
1828
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001829
James Dennett16ae9de2012-06-22 10:16:05 +00001830/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor7176fff2009-01-15 00:26:24 +00001831/// from name lookup.
1832///
James Dennett16ae9de2012-06-22 10:16:05 +00001833/// \param Result The result of the ambiguous lookup to be diagnosed.
Serge Pavlov8ed2f3a2013-08-29 07:23:24 +00001834void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001835 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1836
John McCalla24dc2e2009-11-17 02:14:36 +00001837 DeclarationName Name = Result.getLookupName();
1838 SourceLocation NameLoc = Result.getNameLoc();
1839 SourceRange LookupRange = Result.getContextRange();
1840
John McCall6e247262009-10-10 05:48:19 +00001841 switch (Result.getAmbiguityKind()) {
1842 case LookupResult::AmbiguousBaseSubobjects: {
1843 CXXBasePaths *Paths = Result.getBasePaths();
1844 QualType SubobjectType = Paths->front().back().Base->getType();
1845 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1846 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1847 << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001848
David Blaikie3bc93e32012-12-19 00:45:41 +00001849 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6e247262009-10-10 05:48:19 +00001850 while (isa<CXXMethodDecl>(*Found) &&
1851 cast<CXXMethodDecl>(*Found)->isStatic())
1852 ++Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001853
John McCall6e247262009-10-10 05:48:19 +00001854 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
Serge Pavlov8ed2f3a2013-08-29 07:23:24 +00001855 break;
John McCall6e247262009-10-10 05:48:19 +00001856 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001857
John McCall6e247262009-10-10 05:48:19 +00001858 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001859 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1860 << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001861
John McCall6e247262009-10-10 05:48:19 +00001862 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001863 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001864 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1865 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001866 Path != PathEnd; ++Path) {
David Blaikie3bc93e32012-12-19 00:45:41 +00001867 Decl *D = Path->Decls.front();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001868 if (DeclsPrinted.insert(D).second)
1869 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1870 }
Serge Pavlov8ed2f3a2013-08-29 07:23:24 +00001871 break;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001872 }
1873
John McCall6e247262009-10-10 05:48:19 +00001874 case LookupResult::AmbiguousTagHiding: {
1875 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001876
John McCall6e247262009-10-10 05:48:19 +00001877 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1878
1879 LookupResult::iterator DI, DE = Result.end();
1880 for (DI = Result.begin(); DI != DE; ++DI)
1881 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1882 TagDecls.insert(TD);
1883 Diag(TD->getLocation(), diag::note_hidden_tag);
1884 }
1885
1886 for (DI = Result.begin(); DI != DE; ++DI)
1887 if (!isa<TagDecl>(*DI))
1888 Diag((*DI)->getLocation(), diag::note_hiding_object);
1889
1890 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001891 LookupResult::Filter F = Result.makeFilter();
1892 while (F.hasNext()) {
1893 if (TagDecls.count(F.next()))
1894 F.erase();
1895 }
1896 F.done();
Serge Pavlov8ed2f3a2013-08-29 07:23:24 +00001897 break;
John McCall6e247262009-10-10 05:48:19 +00001898 }
1899
1900 case LookupResult::AmbiguousReference: {
1901 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001902
John McCall6e247262009-10-10 05:48:19 +00001903 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1904 for (; DI != DE; ++DI)
1905 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
Serge Pavlov8ed2f3a2013-08-29 07:23:24 +00001906 break;
John McCall6e247262009-10-10 05:48:19 +00001907 }
Serge Pavlov8ed2f3a2013-08-29 07:23:24 +00001908 }
Douglas Gregor7176fff2009-01-15 00:26:24 +00001909}
Douglas Gregorfa047642009-02-04 00:32:51 +00001910
John McCallc7e04da2010-05-28 18:45:08 +00001911namespace {
1912 struct AssociatedLookup {
John McCall42f48fb2012-08-24 20:38:34 +00001913 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallc7e04da2010-05-28 18:45:08 +00001914 Sema::AssociatedNamespaceSet &Namespaces,
1915 Sema::AssociatedClassSet &Classes)
John McCall42f48fb2012-08-24 20:38:34 +00001916 : S(S), Namespaces(Namespaces), Classes(Classes),
1917 InstantiationLoc(InstantiationLoc) {
John McCallc7e04da2010-05-28 18:45:08 +00001918 }
1919
1920 Sema &S;
1921 Sema::AssociatedNamespaceSet &Namespaces;
1922 Sema::AssociatedClassSet &Classes;
John McCall42f48fb2012-08-24 20:38:34 +00001923 SourceLocation InstantiationLoc;
John McCallc7e04da2010-05-28 18:45:08 +00001924 };
1925}
1926
Mike Stump1eb44332009-09-09 15:08:12 +00001927static void
John McCallc7e04da2010-05-28 18:45:08 +00001928addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCall6ff07852009-08-07 22:18:02 +00001929
Douglas Gregor54022952010-04-30 07:08:38 +00001930static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1931 DeclContext *Ctx) {
1932 // Add the associated namespace for this class.
1933
1934 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1935 // be a locally scoped record.
1936
Sebastian Redl410c4f22010-08-31 20:53:31 +00001937 // We skip out of inline namespaces. The innermost non-inline namespace
1938 // contains all names of all its nested inline namespaces anyway, so we can
1939 // replace the entire inline namespace tree with its root.
1940 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1941 Ctx->isInlineNamespace())
Douglas Gregor54022952010-04-30 07:08:38 +00001942 Ctx = Ctx->getParent();
1943
John McCall6ff07852009-08-07 22:18:02 +00001944 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001945 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001946}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001947
Mike Stump1eb44332009-09-09 15:08:12 +00001948// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001949// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001950static void
John McCallc7e04da2010-05-28 18:45:08 +00001951addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1952 const TemplateArgument &Arg) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001953 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001954 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001955 switch (Arg.getKind()) {
1956 case TemplateArgument::Null:
1957 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001958
Douglas Gregor69be8d62009-07-08 07:51:57 +00001959 case TemplateArgument::Type:
1960 // [...] the namespaces and classes associated with the types of the
1961 // template arguments provided for template type parameters (excluding
1962 // template template parameters)
John McCallc7e04da2010-05-28 18:45:08 +00001963 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor69be8d62009-07-08 07:51:57 +00001964 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001965
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001966 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001967 case TemplateArgument::TemplateExpansion: {
Mike Stump1eb44332009-09-09 15:08:12 +00001968 // [...] the namespaces in which any template template arguments are
1969 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001970 // template template arguments are defined.
Douglas Gregora7fc9012011-01-05 18:58:31 +00001971 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump1eb44332009-09-09 15:08:12 +00001972 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001973 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001974 DeclContext *Ctx = ClassTemplate->getDeclContext();
1975 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001976 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001977 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001978 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001979 }
1980 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001981 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001982
Douglas Gregor788cd062009-11-11 01:00:40 +00001983 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001984 case TemplateArgument::Integral:
1985 case TemplateArgument::Expression:
Eli Friedmand7a6b162012-09-26 02:36:12 +00001986 case TemplateArgument::NullPtr:
Mike Stump1eb44332009-09-09 15:08:12 +00001987 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001988 // associated namespaces. ]
1989 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001990
Douglas Gregor69be8d62009-07-08 07:51:57 +00001991 case TemplateArgument::Pack:
1992 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1993 PEnd = Arg.pack_end();
1994 P != PEnd; ++P)
John McCallc7e04da2010-05-28 18:45:08 +00001995 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001996 break;
1997 }
1998}
1999
Douglas Gregorfa047642009-02-04 00:32:51 +00002000// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00002001// argument-dependent lookup with an argument of class type
2002// (C++ [basic.lookup.koenig]p2).
2003static void
John McCallc7e04da2010-05-28 18:45:08 +00002004addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2005 CXXRecordDecl *Class) {
2006
2007 // Just silently ignore anything whose name is __va_list_tag.
2008 if (Class->getDeclName() == Result.S.VAListTagName)
2009 return;
2010
Douglas Gregorfa047642009-02-04 00:32:51 +00002011 // C++ [basic.lookup.koenig]p2:
2012 // [...]
2013 // -- If T is a class type (including unions), its associated
2014 // classes are: the class itself; the class of which it is a
2015 // member, if any; and its direct and indirect base
2016 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00002017 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00002018
2019 // Add the class of which it is a member, if any.
2020 DeclContext *Ctx = Class->getDeclContext();
2021 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00002022 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00002023 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00002024 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00002025
Douglas Gregorfa047642009-02-04 00:32:51 +00002026 // Add the class itself. If we've already seen this class, we don't
2027 // need to visit base classes.
John McCallc7e04da2010-05-28 18:45:08 +00002028 if (!Result.Classes.insert(Class))
Douglas Gregorfa047642009-02-04 00:32:51 +00002029 return;
2030
Mike Stump1eb44332009-09-09 15:08:12 +00002031 // -- If T is a template-id, its associated namespaces and classes are
2032 // the namespace in which the template is defined; for member
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002033 // templates, the member template's class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00002034 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00002035 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00002036 // namespaces in which any template template arguments are defined; and
2037 // the classes in which any member templates used as template template
2038 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00002039 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00002040 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00002041 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2042 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2043 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00002044 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00002045 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00002046 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00002047
Douglas Gregor69be8d62009-07-08 07:51:57 +00002048 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2049 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallc7e04da2010-05-28 18:45:08 +00002050 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor69be8d62009-07-08 07:51:57 +00002051 }
Mike Stump1eb44332009-09-09 15:08:12 +00002052
John McCall86ff3082010-02-04 22:26:26 +00002053 // Only recurse into base classes for complete types.
2054 if (!Class->hasDefinition()) {
John McCall42f48fb2012-08-24 20:38:34 +00002055 QualType type = Result.S.Context.getTypeDeclType(Class);
2056 if (Result.S.RequireCompleteType(Result.InstantiationLoc, type,
2057 /*no diagnostic*/ 0))
2058 return;
John McCall86ff3082010-02-04 22:26:26 +00002059 }
2060
Douglas Gregorfa047642009-02-04 00:32:51 +00002061 // Add direct and indirect base classes along with their associated
2062 // namespaces.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002063 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregorfa047642009-02-04 00:32:51 +00002064 Bases.push_back(Class);
2065 while (!Bases.empty()) {
2066 // Pop this class off the stack.
Robert Wilhelm344472e2013-08-23 16:11:15 +00002067 Class = Bases.pop_back_val();
Douglas Gregorfa047642009-02-04 00:32:51 +00002068
2069 // Visit the base classes.
2070 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
2071 BaseEnd = Class->bases_end();
2072 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002073 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00002074 // In dependent contexts, we do ADL twice, and the first time around,
2075 // the base type might be a dependent TemplateSpecializationType, or a
2076 // TemplateTypeParmType. If that happens, simply ignore it.
2077 // FIXME: If we want to support export, we probably need to add the
2078 // namespace of the template in a TemplateSpecializationType, or even
2079 // the classes and namespaces of known non-dependent arguments.
2080 if (!BaseType)
2081 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00002082 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00002083 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002084 // Find the associated namespace for this base class.
2085 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallc7e04da2010-05-28 18:45:08 +00002086 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00002087
2088 // Make sure we visit the bases of this base class.
2089 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2090 Bases.push_back(BaseDecl);
2091 }
2092 }
2093 }
2094}
2095
2096// \brief Add the associated classes and namespaces for
2097// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00002098// (C++ [basic.lookup.koenig]p2).
2099static void
John McCallc7e04da2010-05-28 18:45:08 +00002100addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002101 // C++ [basic.lookup.koenig]p2:
2102 //
2103 // For each argument type T in the function call, there is a set
2104 // of zero or more associated namespaces and a set of zero or more
2105 // associated classes to be considered. The sets of namespaces and
2106 // classes is determined entirely by the types of the function
2107 // arguments (and the namespace of any template template
2108 // argument). Typedef names and using-declarations used to specify
2109 // the types do not contribute to this set. The sets of namespaces
2110 // and classes are determined in the following way:
Douglas Gregorfa047642009-02-04 00:32:51 +00002111
Chris Lattner5f9e2722011-07-23 10:55:15 +00002112 SmallVector<const Type *, 16> Queue;
John McCallfa4edcf2010-05-28 06:08:54 +00002113 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2114
Douglas Gregorfa047642009-02-04 00:32:51 +00002115 while (true) {
John McCallfa4edcf2010-05-28 06:08:54 +00002116 switch (T->getTypeClass()) {
2117
2118#define TYPE(Class, Base)
2119#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2120#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2121#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2122#define ABSTRACT_TYPE(Class, Base)
2123#include "clang/AST/TypeNodes.def"
2124 // T is canonical. We can also ignore dependent types because
2125 // we don't need to do ADL at the definition point, but if we
2126 // wanted to implement template export (or if we find some other
2127 // use for associated classes and namespaces...) this would be
2128 // wrong.
Douglas Gregorfa047642009-02-04 00:32:51 +00002129 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00002130
John McCallfa4edcf2010-05-28 06:08:54 +00002131 // -- If T is a pointer to U or an array of U, its associated
2132 // namespaces and classes are those associated with U.
2133 case Type::Pointer:
2134 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2135 continue;
2136 case Type::ConstantArray:
2137 case Type::IncompleteArray:
2138 case Type::VariableArray:
2139 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2140 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00002141
John McCallfa4edcf2010-05-28 06:08:54 +00002142 // -- If T is a fundamental type, its associated sets of
2143 // namespaces and classes are both empty.
2144 case Type::Builtin:
2145 break;
2146
2147 // -- If T is a class type (including unions), its associated
2148 // classes are: the class itself; the class of which it is a
2149 // member, if any; and its direct and indirect base
2150 // classes. Its associated namespaces are the namespaces in
2151 // which its associated classes are defined.
2152 case Type::Record: {
2153 CXXRecordDecl *Class
2154 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00002155 addAssociatedClassesAndNamespaces(Result, Class);
John McCallfa4edcf2010-05-28 06:08:54 +00002156 break;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002157 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00002158
John McCallfa4edcf2010-05-28 06:08:54 +00002159 // -- If T is an enumeration type, its associated namespace is
2160 // the namespace in which it is defined. If it is class
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002161 // member, its associated class is the member's class; else
John McCallfa4edcf2010-05-28 06:08:54 +00002162 // it has no associated class.
2163 case Type::Enum: {
2164 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002165
John McCallfa4edcf2010-05-28 06:08:54 +00002166 DeclContext *Ctx = Enum->getDeclContext();
2167 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00002168 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00002169
John McCallfa4edcf2010-05-28 06:08:54 +00002170 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00002171 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00002172
John McCallfa4edcf2010-05-28 06:08:54 +00002173 break;
2174 }
2175
2176 // -- If T is a function type, its associated namespaces and
2177 // classes are those associated with the function parameter
2178 // types and those associated with the return type.
2179 case Type::FunctionProto: {
2180 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2181 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
2182 ArgEnd = Proto->arg_type_end();
2183 Arg != ArgEnd; ++Arg)
2184 Queue.push_back(Arg->getTypePtr());
2185 // fallthrough
2186 }
2187 case Type::FunctionNoProto: {
2188 const FunctionType *FnType = cast<FunctionType>(T);
2189 T = FnType->getResultType().getTypePtr();
2190 continue;
2191 }
2192
2193 // -- If T is a pointer to a member function of a class X, its
2194 // associated namespaces and classes are those associated
2195 // with the function parameter types and return type,
2196 // together with those associated with X.
2197 //
2198 // -- If T is a pointer to a data member of class X, its
2199 // associated namespaces and classes are those associated
2200 // with the member type together with those associated with
2201 // X.
2202 case Type::MemberPointer: {
2203 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2204
2205 // Queue up the class type into which this points.
2206 Queue.push_back(MemberPtr->getClass());
2207
2208 // And directly continue with the pointee type.
2209 T = MemberPtr->getPointeeType().getTypePtr();
2210 continue;
2211 }
2212
2213 // As an extension, treat this like a normal pointer.
2214 case Type::BlockPointer:
2215 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2216 continue;
2217
2218 // References aren't covered by the standard, but that's such an
2219 // obvious defect that we cover them anyway.
2220 case Type::LValueReference:
2221 case Type::RValueReference:
2222 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2223 continue;
2224
2225 // These are fundamental types.
2226 case Type::Vector:
2227 case Type::ExtVector:
2228 case Type::Complex:
2229 break;
2230
Richard Smithdc7a4f52013-04-30 13:56:41 +00002231 // Non-deduced auto types only get here for error cases.
2232 case Type::Auto:
2233 break;
2234
Douglas Gregorf25760e2011-04-12 01:02:45 +00002235 // If T is an Objective-C object or interface type, or a pointer to an
2236 // object or interface type, the associated namespace is the global
2237 // namespace.
John McCallfa4edcf2010-05-28 06:08:54 +00002238 case Type::ObjCObject:
2239 case Type::ObjCInterface:
2240 case Type::ObjCObjectPointer:
Douglas Gregorf25760e2011-04-12 01:02:45 +00002241 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCallfa4edcf2010-05-28 06:08:54 +00002242 break;
Eli Friedmanb001de72011-10-06 23:00:33 +00002243
2244 // Atomic types are just wrappers; use the associations of the
2245 // contained type.
2246 case Type::Atomic:
2247 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2248 continue;
John McCallfa4edcf2010-05-28 06:08:54 +00002249 }
2250
Robert Wilhelm344472e2013-08-23 16:11:15 +00002251 if (Queue.empty())
2252 break;
2253 T = Queue.pop_back_val();
Douglas Gregorfa047642009-02-04 00:32:51 +00002254 }
Douglas Gregorfa047642009-02-04 00:32:51 +00002255}
2256
2257/// \brief Find the associated classes and namespaces for
2258/// argument-dependent lookup for a call with the given set of
2259/// arguments.
2260///
2261/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00002262/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00002263/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm834c0582013-08-09 18:02:13 +00002264void Sema::FindAssociatedClassesAndNamespaces(
2265 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2266 AssociatedNamespaceSet &AssociatedNamespaces,
2267 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002268 AssociatedNamespaces.clear();
2269 AssociatedClasses.clear();
2270
John McCall42f48fb2012-08-24 20:38:34 +00002271 AssociatedLookup Result(*this, InstantiationLoc,
2272 AssociatedNamespaces, AssociatedClasses);
John McCallc7e04da2010-05-28 18:45:08 +00002273
Douglas Gregorfa047642009-02-04 00:32:51 +00002274 // C++ [basic.lookup.koenig]p2:
2275 // For each argument type T in the function call, there is a set
2276 // of zero or more associated namespaces and a set of zero or more
2277 // associated classes to be considered. The sets of namespaces and
2278 // classes is determined entirely by the types of the function
2279 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00002280 // argument).
Ahmed Charles13a140c2012-02-25 11:00:22 +00002281 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002282 Expr *Arg = Args[ArgIdx];
2283
2284 if (Arg->getType() != Context.OverloadTy) {
John McCallc7e04da2010-05-28 18:45:08 +00002285 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002286 continue;
2287 }
2288
2289 // [...] In addition, if the argument is the name or address of a
2290 // set of overloaded functions and/or function templates, its
2291 // associated classes and namespaces are the union of those
2292 // associated with each of the members of the set: the namespace
2293 // in which the function or function template is defined and the
2294 // classes and namespaces associated with its (non-dependent)
2295 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00002296 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00002297 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCall2de56d12010-08-25 11:45:40 +00002298 if (unaryOp->getOpcode() == UO_AddrOf)
John McCallba135432009-11-21 08:51:07 +00002299 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002300
John McCallc7e04da2010-05-28 18:45:08 +00002301 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2302 if (!ULE) continue;
John McCallba135432009-11-21 08:51:07 +00002303
John McCallc7e04da2010-05-28 18:45:08 +00002304 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2305 I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00002306 // Look through any using declarations to find the underlying function.
2307 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002308
Chandler Carruthbd647292009-12-29 06:17:27 +00002309 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2310 if (!FDecl)
2311 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002312
2313 // Add the classes and namespaces associated with the parameter
2314 // types and return type of this function.
John McCallc7e04da2010-05-28 18:45:08 +00002315 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002316 }
2317 }
2318}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002319
2320/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2321/// an acceptable non-member overloaded operator for a call whose
2322/// arguments have types T1 (and, if non-empty, T2). This routine
2323/// implements the check in C++ [over.match.oper]p3b2 concerning
2324/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00002325static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002326IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2327 QualType T1, QualType T2,
2328 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00002329 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2330 return true;
2331
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002332 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2333 return true;
2334
John McCall183700f2009-09-21 23:43:11 +00002335 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002336 if (Proto->getNumArgs() < 1)
2337 return false;
2338
2339 if (T1->isEnumeralType()) {
2340 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002341 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002342 return true;
2343 }
2344
2345 if (Proto->getNumArgs() < 2)
2346 return false;
2347
2348 if (!T2.isNull() && T2->isEnumeralType()) {
2349 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002350 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002351 return true;
2352 }
2353
2354 return false;
2355}
2356
John McCall7d384dd2009-11-18 07:57:50 +00002357NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002358 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00002359 LookupNameKind NameKind,
2360 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002361 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00002362 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00002363 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00002364}
2365
Douglas Gregor6e378de2009-04-23 23:18:26 +00002366/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002367ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002368 SourceLocation IdLoc,
2369 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002370 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002371 LookupObjCProtocolName, Redecl);
Douglas Gregor6e378de2009-04-23 23:18:26 +00002372 return cast_or_null<ObjCProtocolDecl>(D);
2373}
2374
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002375void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00002376 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00002377 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002378 // C++ [over.match.oper]p3:
2379 // -- The set of non-member candidates is the result of the
2380 // unqualified lookup of operator@ in the context of the
2381 // expression according to the usual rules for name lookup in
2382 // unqualified function calls (3.4.2) except that all member
2383 // functions are ignored. However, if no operand has a class
2384 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00002385 // that have a first parameter of type T1 or "reference to
2386 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002387 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00002388 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002389 // when T2 is an enumeration type, are candidate functions.
2390 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00002391 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2392 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002393
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002394 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2395
John McCallf36e02d2009-10-09 21:13:30 +00002396 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002397 return;
2398
2399 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2400 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002401 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2402 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002403 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002404 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00002405 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002406 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00002407 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00002408 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00002409 // later?
2410 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002411 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00002412 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002413 }
2414}
2415
Sean Huntc39b6bc2011-06-24 02:11:39 +00002416Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Sean Hunt308742c2011-06-04 04:32:43 +00002417 CXXSpecialMember SM,
2418 bool ConstArg,
2419 bool VolatileArg,
2420 bool RValueThis,
2421 bool ConstThis,
2422 bool VolatileThis) {
Richard Smithd0adeb62012-11-27 21:20:31 +00002423 assert(CanDeclareSpecialMemberFunction(RD) &&
Sean Hunt308742c2011-06-04 04:32:43 +00002424 "doing special member lookup into record that isn't fully complete");
Richard Smithd0adeb62012-11-27 21:20:31 +00002425 RD = RD->getDefinition();
Sean Hunt308742c2011-06-04 04:32:43 +00002426 if (RValueThis || ConstThis || VolatileThis)
2427 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2428 "constructors and destructors always have unqualified lvalue this");
2429 if (ConstArg || VolatileArg)
2430 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2431 "parameter-less special members can't have qualified arguments");
2432
2433 llvm::FoldingSetNodeID ID;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002434 ID.AddPointer(RD);
Sean Hunt308742c2011-06-04 04:32:43 +00002435 ID.AddInteger(SM);
2436 ID.AddInteger(ConstArg);
2437 ID.AddInteger(VolatileArg);
2438 ID.AddInteger(RValueThis);
2439 ID.AddInteger(ConstThis);
2440 ID.AddInteger(VolatileThis);
2441
2442 void *InsertPoint;
2443 SpecialMemberOverloadResult *Result =
2444 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2445
2446 // This was already cached
2447 if (Result)
2448 return Result;
2449
Sean Hunt30543582011-06-07 00:11:58 +00002450 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2451 Result = new (Result) SpecialMemberOverloadResult(ID);
Sean Hunt308742c2011-06-04 04:32:43 +00002452 SpecialMemberCache.InsertNode(Result, InsertPoint);
2453
2454 if (SM == CXXDestructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00002455 if (RD->needsImplicitDestructor())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002456 DeclareImplicitDestructor(RD);
2457 CXXDestructorDecl *DD = RD->getDestructor();
Sean Hunt308742c2011-06-04 04:32:43 +00002458 assert(DD && "record without a destructor");
2459 Result->setMethod(DD);
Richard Smith6c4c36c2012-03-30 20:53:28 +00002460 Result->setKind(DD->isDeleted() ?
2461 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith704c8f72012-04-20 18:46:14 +00002462 SpecialMemberOverloadResult::Success);
Sean Hunt308742c2011-06-04 04:32:43 +00002463 return Result;
2464 }
2465
Sean Huntb320e0c2011-06-10 03:50:41 +00002466 // Prepare for overload resolution. Here we construct a synthetic argument
2467 // if necessary and make sure that implicit functions are declared.
Sean Huntc39b6bc2011-06-24 02:11:39 +00002468 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Sean Huntb320e0c2011-06-10 03:50:41 +00002469 DeclarationName Name;
2470 Expr *Arg = 0;
2471 unsigned NumArgs;
2472
Richard Smith704c8f72012-04-20 18:46:14 +00002473 QualType ArgType = CanTy;
2474 ExprValueKind VK = VK_LValue;
2475
Sean Huntb320e0c2011-06-10 03:50:41 +00002476 if (SM == CXXDefaultConstructor) {
2477 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2478 NumArgs = 0;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002479 if (RD->needsImplicitDefaultConstructor())
2480 DeclareImplicitDefaultConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002481 } else {
2482 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2483 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smithe5411b72012-12-01 02:35:44 +00002484 if (RD->needsImplicitCopyConstructor())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002485 DeclareImplicitCopyConstructor(RD);
Richard Smith80ad52f2013-01-02 11:42:31 +00002486 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002487 DeclareImplicitMoveConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002488 } else {
2489 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smithe5411b72012-12-01 02:35:44 +00002490 if (RD->needsImplicitCopyAssignment())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002491 DeclareImplicitCopyAssignment(RD);
Richard Smith80ad52f2013-01-02 11:42:31 +00002492 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002493 DeclareImplicitMoveAssignment(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002494 }
2495
Sean Huntb320e0c2011-06-10 03:50:41 +00002496 if (ConstArg)
2497 ArgType.addConst();
2498 if (VolatileArg)
2499 ArgType.addVolatile();
2500
2501 // This isn't /really/ specified by the standard, but it's implied
2502 // we should be working from an RValue in the case of move to ensure
2503 // that we prefer to bind to rvalue references, and an LValue in the
2504 // case of copy to ensure we don't bind to rvalue references.
2505 // Possibly an XValue is actually correct in the case of move, but
2506 // there is no semantic difference for class types in this restricted
2507 // case.
Sean Huntab183df2011-06-22 22:13:13 +00002508 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Sean Huntb320e0c2011-06-10 03:50:41 +00002509 VK = VK_LValue;
2510 else
2511 VK = VK_RValue;
Richard Smith704c8f72012-04-20 18:46:14 +00002512 }
Sean Huntb320e0c2011-06-10 03:50:41 +00002513
Richard Smith704c8f72012-04-20 18:46:14 +00002514 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2515
2516 if (SM != CXXDefaultConstructor) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002517 NumArgs = 1;
Richard Smith704c8f72012-04-20 18:46:14 +00002518 Arg = &FakeArg;
Sean Huntb320e0c2011-06-10 03:50:41 +00002519 }
2520
2521 // Create the object argument
2522 QualType ThisTy = CanTy;
2523 if (ConstThis)
2524 ThisTy.addConst();
2525 if (VolatileThis)
2526 ThisTy.addVolatile();
Sean Hunt4cc12c62011-06-23 00:26:20 +00002527 Expr::Classification Classification =
Richard Smith704c8f72012-04-20 18:46:14 +00002528 OpaqueValueExpr(SourceLocation(), ThisTy,
2529 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Sean Huntb320e0c2011-06-10 03:50:41 +00002530
2531 // Now we perform lookup on the name we computed earlier and do overload
2532 // resolution. Lookup is only performed directly into the class since there
2533 // will always be a (possibly implicit) declaration to shadow any others.
2534 OverloadCandidateSet OCS((SourceLocation()));
David Blaikie3bc93e32012-12-19 00:45:41 +00002535 DeclContext::lookup_result R = RD->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00002536 assert(!R.empty() &&
Sean Huntb320e0c2011-06-10 03:50:41 +00002537 "lookup for a constructor or assignment operator was empty");
Chandler Carruthab4e0c02013-08-18 07:20:52 +00002538
2539 // Copy the candidates as our processing of them may load new declarations
2540 // from an external source and invalidate lookup_result.
2541 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2542
2543 for (SmallVectorImpl<NamedDecl *>::iterator I = Candidates.begin(),
Richard Smithb60fae52013-09-09 16:55:27 +00002544 E = Candidates.end();
Chandler Carruthab4e0c02013-08-18 07:20:52 +00002545 I != E; ++I) {
2546 NamedDecl *Cand = *I;
Sean Hunt4cc12c62011-06-23 00:26:20 +00002547
Sean Huntc39b6bc2011-06-24 02:11:39 +00002548 if (Cand->isInvalidDecl())
Sean Huntb320e0c2011-06-10 03:50:41 +00002549 continue;
2550
Sean Huntc39b6bc2011-06-24 02:11:39 +00002551 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2552 // FIXME: [namespace.udecl]p15 says that we should only consider a
2553 // using declaration here if it does not match a declaration in the
2554 // derived class. We do not implement this correctly in other cases
2555 // either.
2556 Cand = U->getTargetDecl();
2557
2558 if (Cand->isInvalidDecl())
2559 continue;
2560 }
2561
2562 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002563 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Sean Huntc39b6bc2011-06-24 02:11:39 +00002564 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002565 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2566 OCS, true);
Sean Hunt4cc12c62011-06-23 00:26:20 +00002567 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00002568 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2569 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Sean Hunt431a1cb2011-06-22 02:58:46 +00002570 } else if (FunctionTemplateDecl *Tmpl =
Sean Huntc39b6bc2011-06-24 02:11:39 +00002571 dyn_cast<FunctionTemplateDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002572 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2573 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charles13a140c2012-02-25 11:00:22 +00002574 RD, 0, ThisTy, Classification,
2575 llvm::makeArrayRef(&Arg, NumArgs),
Sean Hunt4cc12c62011-06-23 00:26:20 +00002576 OCS, true);
2577 else
2578 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charles13a140c2012-02-25 11:00:22 +00002579 0, llvm::makeArrayRef(&Arg, NumArgs),
2580 OCS, true);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002581 } else {
2582 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Sean Huntb320e0c2011-06-10 03:50:41 +00002583 }
2584 }
2585
2586 OverloadCandidateSet::iterator Best;
2587 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2588 case OR_Success:
2589 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith704c8f72012-04-20 18:46:14 +00002590 Result->setKind(SpecialMemberOverloadResult::Success);
Sean Huntb320e0c2011-06-10 03:50:41 +00002591 break;
2592
2593 case OR_Deleted:
2594 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith6c4c36c2012-03-30 20:53:28 +00002595 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Sean Huntb320e0c2011-06-10 03:50:41 +00002596 break;
2597
2598 case OR_Ambiguous:
Richard Smith6c4c36c2012-03-30 20:53:28 +00002599 Result->setMethod(0);
2600 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2601 break;
2602
Sean Huntb320e0c2011-06-10 03:50:41 +00002603 case OR_No_Viable_Function:
2604 Result->setMethod(0);
Richard Smith6c4c36c2012-03-30 20:53:28 +00002605 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Sean Huntb320e0c2011-06-10 03:50:41 +00002606 break;
2607 }
2608
2609 return Result;
2610}
2611
2612/// \brief Look up the default constructor for the given class.
2613CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Sean Huntc530d172011-06-10 04:44:37 +00002614 SpecialMemberOverloadResult *Result =
Sean Huntb320e0c2011-06-10 03:50:41 +00002615 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2616 false, false);
2617
2618 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Sean Hunt308742c2011-06-04 04:32:43 +00002619}
2620
Sean Hunt661c67a2011-06-21 23:42:56 +00002621/// \brief Look up the copying constructor for the given class.
2622CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith704c8f72012-04-20 18:46:14 +00002623 unsigned Quals) {
Sean Huntc530d172011-06-10 04:44:37 +00002624 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2625 "non-const, non-volatile qualifiers for copy ctor arg");
2626 SpecialMemberOverloadResult *Result =
2627 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2628 Quals & Qualifiers::Volatile, false, false, false);
2629
Sean Huntc530d172011-06-10 04:44:37 +00002630 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2631}
2632
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002633/// \brief Look up the moving constructor for the given class.
Richard Smith6a06e5f2012-07-18 03:36:00 +00002634CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2635 unsigned Quals) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002636 SpecialMemberOverloadResult *Result =
Richard Smith6a06e5f2012-07-18 03:36:00 +00002637 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2638 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002639
2640 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2641}
2642
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002643/// \brief Look up the constructors for the given class.
2644DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002645 // If the implicit constructors have not yet been declared, do so now.
Richard Smithd0adeb62012-11-27 21:20:31 +00002646 if (CanDeclareSpecialMemberFunction(Class)) {
Sean Huntcdee3fe2011-05-11 22:34:38 +00002647 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002648 DeclareImplicitDefaultConstructor(Class);
Richard Smithe5411b72012-12-01 02:35:44 +00002649 if (Class->needsImplicitCopyConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002650 DeclareImplicitCopyConstructor(Class);
Richard Smith80ad52f2013-01-02 11:42:31 +00002651 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002652 DeclareImplicitMoveConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +00002653 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002654
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002655 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2656 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2657 return Class->lookup(Name);
2658}
2659
Sean Hunt661c67a2011-06-21 23:42:56 +00002660/// \brief Look up the copying assignment operator for the given class.
2661CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2662 unsigned Quals, bool RValueThis,
Richard Smith704c8f72012-04-20 18:46:14 +00002663 unsigned ThisQuals) {
Sean Hunt661c67a2011-06-21 23:42:56 +00002664 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2665 "non-const, non-volatile qualifiers for copy assignment arg");
2666 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2667 "non-const, non-volatile qualifiers for copy assignment this");
2668 SpecialMemberOverloadResult *Result =
2669 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2670 Quals & Qualifiers::Volatile, RValueThis,
2671 ThisQuals & Qualifiers::Const,
2672 ThisQuals & Qualifiers::Volatile);
2673
Sean Hunt661c67a2011-06-21 23:42:56 +00002674 return Result->getMethod();
2675}
2676
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002677/// \brief Look up the moving assignment operator for the given class.
2678CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith6a06e5f2012-07-18 03:36:00 +00002679 unsigned Quals,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002680 bool RValueThis,
2681 unsigned ThisQuals) {
2682 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2683 "non-const, non-volatile qualifiers for copy assignment this");
2684 SpecialMemberOverloadResult *Result =
Richard Smith6a06e5f2012-07-18 03:36:00 +00002685 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2686 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002687 ThisQuals & Qualifiers::Const,
2688 ThisQuals & Qualifiers::Volatile);
2689
2690 return Result->getMethod();
2691}
2692
Douglas Gregordb89f282010-07-01 22:47:18 +00002693/// \brief Look for the destructor of the given class.
2694///
Sean Huntc5c9b532011-06-03 21:10:40 +00002695/// During semantic analysis, this routine should be used in lieu of
2696/// CXXRecordDecl::getDestructor().
Douglas Gregordb89f282010-07-01 22:47:18 +00002697///
2698/// \returns The destructor for this class.
2699CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Sean Hunt308742c2011-06-04 04:32:43 +00002700 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2701 false, false, false,
2702 false, false)->getMethod());
Douglas Gregordb89f282010-07-01 22:47:18 +00002703}
2704
Richard Smith36f5cfe2012-03-09 08:00:36 +00002705/// LookupLiteralOperator - Determine which literal operator should be used for
2706/// a user-defined literal, per C++11 [lex.ext].
2707///
2708/// Normal overload resolution is not used to select which literal operator to
2709/// call for a user-defined literal. Look up the provided literal operator name,
2710/// and filter the results to the appropriate set for the given argument types.
2711Sema::LiteralOperatorLookupResult
2712Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2713 ArrayRef<QualType> ArgTys,
2714 bool AllowRawAndTemplate) {
2715 LookupName(R, S);
2716 assert(R.getResultKind() != LookupResult::Ambiguous &&
2717 "literal operator lookup can't be ambiguous");
2718
2719 // Filter the lookup results appropriately.
2720 LookupResult::Filter F = R.makeFilter();
2721
2722 bool FoundTemplate = false;
2723 bool FoundRaw = false;
2724 bool FoundExactMatch = false;
2725
2726 while (F.hasNext()) {
2727 Decl *D = F.next();
2728 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2729 D = USD->getTargetDecl();
2730
2731 bool IsTemplate = isa<FunctionTemplateDecl>(D);
2732 bool IsRaw = false;
2733 bool IsExactMatch = false;
2734
Douglas Gregor7e0c2272013-04-10 05:18:00 +00002735 // If the declaration we found is invalid, skip it.
2736 if (D->isInvalidDecl()) {
2737 F.erase();
2738 continue;
2739 }
2740
Richard Smith36f5cfe2012-03-09 08:00:36 +00002741 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2742 if (FD->getNumParams() == 1 &&
2743 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2744 IsRaw = true;
Richard Smitha121eb32013-01-15 07:12:59 +00002745 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smith36f5cfe2012-03-09 08:00:36 +00002746 IsExactMatch = true;
2747 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2748 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2749 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2750 IsExactMatch = false;
2751 break;
2752 }
2753 }
2754 }
2755 }
2756
2757 if (IsExactMatch) {
2758 FoundExactMatch = true;
2759 AllowRawAndTemplate = false;
2760 if (FoundRaw || FoundTemplate) {
2761 // Go through again and remove the raw and template decls we've
2762 // already found.
2763 F.restart();
2764 FoundRaw = FoundTemplate = false;
2765 }
2766 } else if (AllowRawAndTemplate && (IsTemplate || IsRaw)) {
2767 FoundTemplate |= IsTemplate;
2768 FoundRaw |= IsRaw;
2769 } else {
2770 F.erase();
2771 }
2772 }
2773
2774 F.done();
2775
2776 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2777 // parameter type, that is used in preference to a raw literal operator
2778 // or literal operator template.
2779 if (FoundExactMatch)
2780 return LOLR_Cooked;
2781
2782 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2783 // operator template, but not both.
2784 if (FoundRaw && FoundTemplate) {
2785 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
2786 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2787 Decl *D = *I;
2788 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2789 D = USD->getTargetDecl();
2790 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2791 D = FunTmpl->getTemplatedDecl();
2792 NoteOverloadCandidate(cast<FunctionDecl>(D));
2793 }
2794 return LOLR_Error;
2795 }
2796
2797 if (FoundRaw)
2798 return LOLR_Raw;
2799
2800 if (FoundTemplate)
2801 return LOLR_Template;
2802
2803 // Didn't find anything we could use.
2804 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2805 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
2806 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRawAndTemplate;
2807 return LOLR_Error;
2808}
2809
John McCall7edb5fd2010-01-26 07:16:45 +00002810void ADLResult::insert(NamedDecl *New) {
2811 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2812
2813 // If we haven't yet seen a decl for this key, or the last decl
2814 // was exactly this one, we're done.
2815 if (Old == 0 || Old == New) {
2816 Old = New;
2817 return;
2818 }
2819
2820 // Otherwise, decide which is a more recent redeclaration.
2821 FunctionDecl *OldFD, *NewFD;
2822 if (isa<FunctionTemplateDecl>(New)) {
2823 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2824 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2825 } else {
2826 OldFD = cast<FunctionDecl>(Old);
2827 NewFD = cast<FunctionDecl>(New);
2828 }
2829
2830 FunctionDecl *Cursor = NewFD;
2831 while (true) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002832 Cursor = Cursor->getPreviousDecl();
John McCall7edb5fd2010-01-26 07:16:45 +00002833
2834 // If we got to the end without finding OldFD, OldFD is the newer
2835 // declaration; leave things as they are.
2836 if (!Cursor) return;
2837
2838 // If we do find OldFD, then NewFD is newer.
2839 if (Cursor == OldFD) break;
2840
2841 // Otherwise, keep looking.
2842 }
2843
2844 Old = New;
2845}
2846
Sebastian Redl644be852009-10-23 19:23:15 +00002847void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Robert Wilhelm834c0582013-08-09 18:02:13 +00002848 SourceLocation Loc, ArrayRef<Expr *> Args,
Richard Smithb1502bc2012-10-18 17:56:02 +00002849 ADLResult &Result) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002850 // Find all of the associated namespaces and classes based on the
2851 // arguments we have.
2852 AssociatedNamespaceSet AssociatedNamespaces;
2853 AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00002854 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCall6ff07852009-08-07 22:18:02 +00002855 AssociatedNamespaces,
2856 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002857
Sebastian Redl644be852009-10-23 19:23:15 +00002858 QualType T1, T2;
2859 if (Operator) {
2860 T1 = Args[0]->getType();
Ahmed Charles13a140c2012-02-25 11:00:22 +00002861 if (Args.size() >= 2)
Sebastian Redl644be852009-10-23 19:23:15 +00002862 T2 = Args[1]->getType();
2863 }
2864
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002865 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002866 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2867 // and let Y be the lookup set produced by argument dependent
2868 // lookup (defined as follows). If X contains [...] then Y is
2869 // empty. Otherwise Y is the set of declarations found in the
2870 // namespaces associated with the argument types as described
2871 // below. The set of declarations found by the lookup of the name
2872 // is the union of X and Y.
2873 //
2874 // Here, we compute Y and add its members to the overloaded
2875 // candidate set.
2876 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002877 NSEnd = AssociatedNamespaces.end();
2878 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002879 // When considering an associated namespace, the lookup is the
2880 // same as the lookup performed when the associated namespace is
2881 // used as a qualifier (3.4.3.2) except that:
2882 //
2883 // -- Any using-directives in the associated namespace are
2884 // ignored.
2885 //
John McCall6ff07852009-08-07 22:18:02 +00002886 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002887 // associated classes are visible within their respective
2888 // namespaces even if they are not visible during an ordinary
2889 // lookup (11.4).
David Blaikie3bc93e32012-12-19 00:45:41 +00002890 DeclContext::lookup_result R = (*NS)->lookup(Name);
2891 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
2892 ++I) {
John McCall6e266892010-01-26 03:27:55 +00002893 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00002894 // If the only declaration here is an ordinary friend, consider
2895 // it only if it was declared in an associated classes.
Richard Smitha41c97a2013-09-20 01:15:31 +00002896 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) {
2897 // If it's neither ordinarily visible nor a friend, we can't find it.
2898 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0)
2899 continue;
2900
Richard Smith22050f22013-07-17 23:53:16 +00002901 bool DeclaredInAssociatedClass = false;
2902 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
2903 DeclContext *LexDC = DI->getLexicalDeclContext();
2904 if (isa<CXXRecordDecl>(LexDC) &&
2905 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) {
2906 DeclaredInAssociatedClass = true;
2907 break;
2908 }
2909 }
2910 if (!DeclaredInAssociatedClass)
John McCall3f9a8a62009-08-11 06:59:38 +00002911 continue;
2912 }
Mike Stump1eb44332009-09-09 15:08:12 +00002913
John McCalla113e722010-01-26 06:04:06 +00002914 if (isa<UsingShadowDecl>(D))
2915 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00002916
John McCalla113e722010-01-26 06:04:06 +00002917 if (isa<FunctionDecl>(D)) {
2918 if (Operator &&
2919 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2920 T1, T2, Context))
2921 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00002922 } else if (!isa<FunctionTemplateDecl>(D))
2923 continue;
2924
2925 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00002926 }
2927 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002928}
Douglas Gregor546be3c2009-12-30 17:04:44 +00002929
2930//----------------------------------------------------------------------------
2931// Search for all visible declarations.
2932//----------------------------------------------------------------------------
2933VisibleDeclConsumer::~VisibleDeclConsumer() { }
2934
Richard Smithd67679d2013-08-20 20:35:18 +00002935bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
2936
Douglas Gregor546be3c2009-12-30 17:04:44 +00002937namespace {
2938
2939class ShadowContextRAII;
2940
2941class VisibleDeclsRecord {
2942public:
2943 /// \brief An entry in the shadow map, which is optimized to store a
2944 /// single declaration (the common case) but can also store a list
2945 /// of declarations.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002946 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002947
2948private:
2949 /// \brief A mapping from declaration names to the declarations that have
2950 /// this name within a particular scope.
2951 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2952
2953 /// \brief A list of shadow maps, which is used to model name hiding.
2954 std::list<ShadowMap> ShadowMaps;
2955
2956 /// \brief The declaration contexts we have already visited.
2957 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2958
2959 friend class ShadowContextRAII;
2960
2961public:
2962 /// \brief Determine whether we have already visited this context
2963 /// (and, if not, note that we are going to visit that context now).
2964 bool visitedContext(DeclContext *Ctx) {
2965 return !VisitedContexts.insert(Ctx);
2966 }
2967
Douglas Gregor8071e422010-08-15 06:18:01 +00002968 bool alreadyVisitedContext(DeclContext *Ctx) {
2969 return VisitedContexts.count(Ctx);
2970 }
2971
Douglas Gregor546be3c2009-12-30 17:04:44 +00002972 /// \brief Determine whether the given declaration is hidden in the
2973 /// current scope.
2974 ///
2975 /// \returns the declaration that hides the given declaration, or
2976 /// NULL if no such declaration exists.
2977 NamedDecl *checkHidden(NamedDecl *ND);
2978
2979 /// \brief Add a declaration to the current shadow map.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002980 void add(NamedDecl *ND) {
2981 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2982 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002983};
2984
2985/// \brief RAII object that records when we've entered a shadow context.
2986class ShadowContextRAII {
2987 VisibleDeclsRecord &Visible;
2988
2989 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2990
2991public:
2992 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2993 Visible.ShadowMaps.push_back(ShadowMap());
2994 }
2995
2996 ~ShadowContextRAII() {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002997 Visible.ShadowMaps.pop_back();
2998 }
2999};
3000
3001} // end anonymous namespace
3002
Douglas Gregor546be3c2009-12-30 17:04:44 +00003003NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00003004 // Look through using declarations.
3005 ND = ND->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003006
Douglas Gregor546be3c2009-12-30 17:04:44 +00003007 unsigned IDNS = ND->getIdentifierNamespace();
3008 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
3009 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3010 SM != SMEnd; ++SM) {
3011 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
3012 if (Pos == SM->end())
3013 continue;
3014
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003015 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00003016 IEnd = Pos->second.end();
3017 I != IEnd; ++I) {
3018 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00003019 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003020 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor546be3c2009-12-30 17:04:44 +00003021 Decl::IDNS_ObjCProtocol)))
3022 continue;
3023
3024 // Protocols are in distinct namespaces from everything else.
3025 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
3026 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
3027 (*I)->getIdentifierNamespace() != IDNS)
3028 continue;
3029
Douglas Gregor0cc84042010-01-14 15:47:35 +00003030 // Functions and function templates in the same scope overload
3031 // rather than hide. FIXME: Look for hiding based on function
3032 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00003033 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00003034 ND->isFunctionOrFunctionTemplate() &&
3035 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00003036 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003037
Douglas Gregor546be3c2009-12-30 17:04:44 +00003038 // We've found a declaration that hides this one.
3039 return *I;
3040 }
3041 }
3042
3043 return 0;
3044}
3045
3046static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
3047 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003048 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00003049 VisibleDeclConsumer &Consumer,
3050 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00003051 if (!Ctx)
3052 return;
3053
Douglas Gregor546be3c2009-12-30 17:04:44 +00003054 // Make sure we don't visit the same context twice.
3055 if (Visited.visitedContext(Ctx->getPrimaryContext()))
3056 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003057
Douglas Gregor4923aa22010-07-02 20:37:36 +00003058 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3059 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3060
Douglas Gregor546be3c2009-12-30 17:04:44 +00003061 // Enumerate all of the results in this context.
Nick Lewycky173a37a2012-04-03 21:44:08 +00003062 for (DeclContext::all_lookups_iterator L = Ctx->lookups_begin(),
3063 LEnd = Ctx->lookups_end();
3064 L != LEnd; ++L) {
David Blaikie3bc93e32012-12-19 00:45:41 +00003065 DeclContext::lookup_result R = *L;
3066 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
3067 ++I) {
3068 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) {
Douglas Gregor55368912011-12-14 16:03:29 +00003069 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00003070 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003071 Visited.add(ND);
3072 }
Douglas Gregor70c23352010-12-09 21:44:02 +00003073 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003074 }
3075 }
3076
3077 // Traverse using directives for qualified name lookup.
3078 if (QualifiedNameLookup) {
3079 ShadowContextRAII Shadow(Visited);
3080 DeclContext::udir_iterator I, E;
3081 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003082 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003083 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003084 }
3085 }
3086
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003087 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003088 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00003089 if (!Record->hasDefinition())
3090 return;
3091
Douglas Gregor546be3c2009-12-30 17:04:44 +00003092 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
3093 BEnd = Record->bases_end();
3094 B != BEnd; ++B) {
3095 QualType BaseType = B->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003096
Douglas Gregor546be3c2009-12-30 17:04:44 +00003097 // Don't look into dependent bases, because name lookup can't look
3098 // there anyway.
3099 if (BaseType->isDependentType())
3100 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003101
Douglas Gregor546be3c2009-12-30 17:04:44 +00003102 const RecordType *Record = BaseType->getAs<RecordType>();
3103 if (!Record)
3104 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003105
Douglas Gregor546be3c2009-12-30 17:04:44 +00003106 // FIXME: It would be nice to be able to determine whether referencing
3107 // a particular member would be ambiguous. For example, given
3108 //
3109 // struct A { int member; };
3110 // struct B { int member; };
3111 // struct C : A, B { };
3112 //
3113 // void f(C *c) { c->### }
3114 //
3115 // accessing 'member' would result in an ambiguity. However, we
3116 // could be smart enough to qualify the member with the base
3117 // class, e.g.,
3118 //
3119 // c->B::member
3120 //
3121 // or
3122 //
3123 // c->A::member
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003124
Douglas Gregor546be3c2009-12-30 17:04:44 +00003125 // Find results in this base class (and its bases).
3126 ShadowContextRAII Shadow(Visited);
3127 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003128 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003129 }
3130 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003131
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003132 // Traverse the contexts of Objective-C classes.
3133 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3134 // Traverse categories.
Douglas Gregord3297242013-01-16 23:00:23 +00003135 for (ObjCInterfaceDecl::visible_categories_iterator
3136 Cat = IFace->visible_categories_begin(),
3137 CatEnd = IFace->visible_categories_end();
3138 Cat != CatEnd; ++Cat) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003139 ShadowContextRAII Shadow(Visited);
Douglas Gregord3297242013-01-16 23:00:23 +00003140 LookupVisibleDecls(*Cat, Result, QualifiedNameLookup, false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003141 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003142 }
3143
3144 // Traverse protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003145 for (ObjCInterfaceDecl::all_protocol_iterator
3146 I = IFace->all_referenced_protocol_begin(),
3147 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003148 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003149 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003150 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003151 }
3152
3153 // Traverse the superclass.
3154 if (IFace->getSuperClass()) {
3155 ShadowContextRAII Shadow(Visited);
3156 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003157 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003158 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003159
Douglas Gregorc220a182010-04-19 18:02:19 +00003160 // If there is an implementation, traverse it. We do this to find
3161 // synthesized ivars.
3162 if (IFace->getImplementation()) {
3163 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003164 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky893a6ea2012-04-03 20:26:45 +00003165 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregorc220a182010-04-19 18:02:19 +00003166 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003167 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
3168 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
3169 E = Protocol->protocol_end(); I != E; ++I) {
3170 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003171 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003172 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003173 }
3174 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
3175 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
3176 E = Category->protocol_end(); I != E; ++I) {
3177 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003178 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003179 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003180 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003181
Douglas Gregorc220a182010-04-19 18:02:19 +00003182 // If there is an implementation, traverse it.
3183 if (Category->getImplementation()) {
3184 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003185 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00003186 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003187 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003188 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003189}
3190
3191static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3192 UnqualUsingDirectiveSet &UDirs,
3193 VisibleDeclConsumer &Consumer,
3194 VisibleDeclsRecord &Visited) {
3195 if (!S)
3196 return;
3197
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003198 if (!S->getEntity() ||
3199 (!S->getParent() &&
Douglas Gregor8071e422010-08-15 06:18:01 +00003200 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor539c5c32010-01-07 00:31:29 +00003201 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
Richard Smitha41c97a2013-09-20 01:15:31 +00003202 FindLocalExternScope FindLocals(Result);
Douglas Gregor539c5c32010-01-07 00:31:29 +00003203 // Walk through the declarations in this Scope.
3204 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
3205 D != DEnd; ++D) {
John McCalld226f652010-08-21 09:40:31 +00003206 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor55368912011-12-14 16:03:29 +00003207 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00003208 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00003209 Visited.add(ND);
3210 }
3211 }
3212 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003213
Douglas Gregor711be1e2010-03-15 14:33:29 +00003214 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00003215 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00003216 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003217 // Look into this scope's declaration context, along with any of its
3218 // parent lookup contexts (e.g., enclosing classes), up to the point
3219 // where we hit the context stored in the next outer scope.
3220 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00003221 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003222
Douglas Gregordbdf5e72010-03-15 15:26:48 +00003223 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003224 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003225 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3226 if (Method->isInstanceMethod()) {
3227 // For instance methods, look for ivars in the method's interface.
3228 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3229 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregorca45da02010-11-02 20:36:02 +00003230 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003231 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Richard Smithd67679d2013-08-20 20:35:18 +00003232 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorca45da02010-11-02 20:36:02 +00003233 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003234 }
3235
3236 // We've already performed all of the name lookup that we need
3237 // to for Objective-C methods; the next context will be the
3238 // outer scope.
3239 break;
3240 }
3241
Douglas Gregor546be3c2009-12-30 17:04:44 +00003242 if (Ctx->isFunctionOrMethod())
3243 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003244
3245 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003246 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003247 }
3248 } else if (!S->getParent()) {
3249 // Look into the translation unit scope. We walk through the translation
3250 // unit's declaration context, because the Scope itself won't have all of
3251 // the declarations if we loaded a precompiled header.
3252 // FIXME: We would like the translation unit's Scope object to point to the
3253 // translation unit, so we don't need this special "if" branch. However,
3254 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003255 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003256 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00003257 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003258 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003259 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003260 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003261 }
3262
Douglas Gregor546be3c2009-12-30 17:04:44 +00003263 if (Entity) {
3264 // Lookup visible declarations in any namespaces found by using
3265 // directives.
3266 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
3267 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
3268 for (; UI != UEnd; ++UI)
3269 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003270 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003271 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003272 }
3273
3274 // Lookup names in the parent scope.
3275 ShadowContextRAII Shadow(Visited);
3276 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3277}
3278
3279void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00003280 VisibleDeclConsumer &Consumer,
3281 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003282 // Determine the set of using directives available during
3283 // unqualified name lookup.
3284 Scope *Initial = S;
3285 UnqualUsingDirectiveSet UDirs;
David Blaikie4e4d0842012-03-11 07:00:24 +00003286 if (getLangOpts().CPlusPlus) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003287 // Find the first namespace or translation-unit scope.
3288 while (S && !isNamespaceOrTranslationUnitScope(S))
3289 S = S->getParent();
3290
3291 UDirs.visitScopeChain(Initial, S);
3292 }
3293 UDirs.done();
3294
3295 // Look for visible declarations.
3296 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithd67679d2013-08-20 20:35:18 +00003297 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003298 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003299 if (!IncludeGlobalScope)
3300 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003301 ShadowContextRAII Shadow(Visited);
3302 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3303}
3304
3305void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00003306 VisibleDeclConsumer &Consumer,
3307 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003308 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithd67679d2013-08-20 20:35:18 +00003309 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003310 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003311 if (!IncludeGlobalScope)
3312 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003313 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003314 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003315 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003316}
3317
Chris Lattner4ae493c2011-02-18 02:08:43 +00003318/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara67843042011-03-05 18:21:20 +00003319/// If GnuLabelLoc is a valid source location, then this is a definition
3320/// of an __label__ label name, otherwise it is a normal label definition
3321/// or use.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003322LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara67843042011-03-05 18:21:20 +00003323 SourceLocation GnuLabelLoc) {
Chris Lattner337e5502011-02-18 01:27:55 +00003324 // Do a lookup to see if we have a label with this name already.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003325 NamedDecl *Res = 0;
Abramo Bagnara67843042011-03-05 18:21:20 +00003326
3327 if (GnuLabelLoc.isValid()) {
3328 // Local label definitions always shadow existing labels.
3329 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3330 Scope *S = CurScope;
3331 PushOnScopeChains(Res, S, true);
3332 return cast<LabelDecl>(Res);
3333 }
3334
3335 // Not a GNU local label.
3336 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3337 // If we found a label, check to see if it is in the same context as us.
3338 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattner337e5502011-02-18 01:27:55 +00003339 if (Res && Res->getDeclContext() != CurContext)
3340 Res = 0;
Chris Lattner337e5502011-02-18 01:27:55 +00003341 if (Res == 0) {
3342 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara67843042011-03-05 18:21:20 +00003343 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3344 Scope *S = CurScope->getFnParent();
Chris Lattnerfebb5b82011-02-18 21:16:39 +00003345 assert(S && "Not in a function?");
3346 PushOnScopeChains(Res, S, true);
Chris Lattner337e5502011-02-18 01:27:55 +00003347 }
Chris Lattner337e5502011-02-18 01:27:55 +00003348 return cast<LabelDecl>(Res);
3349}
3350
3351//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003352// Typo correction
Chris Lattner337e5502011-02-18 01:27:55 +00003353//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003354
3355namespace {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003356
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003357typedef SmallVector<TypoCorrection, 1> TypoResultList;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003358typedef llvm::StringMap<TypoResultList, llvm::BumpPtrAllocator> TypoResultsMap;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003359typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003360
3361static const unsigned MaxTypoDistanceResultSets = 5;
3362
Douglas Gregor546be3c2009-12-30 17:04:44 +00003363class TypoCorrectionConsumer : public VisibleDeclConsumer {
3364 /// \brief The name written that is a typo in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003365 StringRef Typo;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003366
3367 /// \brief The results found that have the smallest edit distance
3368 /// found (so far) with the typo name.
Douglas Gregore24b5752010-10-14 20:34:08 +00003369 ///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003370 /// The pointer value being set to the current DeclContext indicates
3371 /// whether there is a keyword with this name.
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003372 TypoEditDistanceMap CorrectionResults;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003373
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003374 Sema &SemaRef;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003375
Douglas Gregor546be3c2009-12-30 17:04:44 +00003376public:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003377 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003378 : Typo(Typo->getName()),
Richard Smithd67679d2013-08-20 20:35:18 +00003379 SemaRef(SemaRef) {}
3380
3381 bool includeHiddenDecls() const { return true; }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003382
Erik Verbruggend1205962011-10-06 07:27:49 +00003383 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3384 bool InBaseClass);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003385 void FoundName(StringRef Name);
3386 void addKeywordResult(StringRef Keyword);
3387 void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003388 NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003389 void addCorrection(TypoCorrection Correction);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003390
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003391 typedef TypoResultsMap::iterator result_iterator;
3392 typedef TypoEditDistanceMap::iterator distance_iterator;
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003393 distance_iterator begin() { return CorrectionResults.begin(); }
3394 distance_iterator end() { return CorrectionResults.end(); }
3395 void erase(distance_iterator I) { CorrectionResults.erase(I); }
3396 unsigned size() const { return CorrectionResults.size(); }
3397 bool empty() const { return CorrectionResults.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003398
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003399 TypoResultList &operator[](StringRef Name) {
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003400 return CorrectionResults.begin()->second[Name];
Douglas Gregor7b824e82010-10-15 13:35:25 +00003401 }
3402
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003403 unsigned getBestEditDistance(bool Normalized) {
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003404 if (CorrectionResults.empty())
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003405 return (std::numeric_limits<unsigned>::max)();
3406
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003407 unsigned BestED = CorrectionResults.begin()->first;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003408 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003409 }
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003410
3411 TypoResultsMap &getBestResults() {
3412 return CorrectionResults.begin()->second;
3413 }
3414
Douglas Gregor546be3c2009-12-30 17:04:44 +00003415};
3416
3417}
3418
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003419void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggend1205962011-10-06 07:27:49 +00003420 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003421 // Don't consider hidden names for typo correction.
3422 if (Hiding)
3423 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003424
Douglas Gregor546be3c2009-12-30 17:04:44 +00003425 // Only consider entities with identifiers for names, ignoring
3426 // special names (constructors, overloaded operators, selectors,
3427 // etc.).
3428 IdentifierInfo *Name = ND->getIdentifier();
3429 if (!Name)
3430 return;
3431
Richard Smithd67679d2013-08-20 20:35:18 +00003432 // Only consider visible declarations and declarations from modules with
3433 // names that exactly match.
3434 if (!LookupResult::isVisible(SemaRef, ND) && Name->getName() != Typo &&
3435 !findAcceptableDecl(SemaRef, ND))
3436 return;
3437
Douglas Gregor95f42922010-10-14 22:11:03 +00003438 FoundName(Name->getName());
3439}
3440
Chris Lattner5f9e2722011-07-23 10:55:15 +00003441void TypoCorrectionConsumer::FoundName(StringRef Name) {
Douglas Gregor362a8f22010-10-19 19:39:10 +00003442 // Use a simple length-based heuristic to determine the minimum possible
3443 // edit distance. If the minimum isn't good enough, bail out early.
3444 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003445 if (MinED && Typo.size() / MinED < 3)
Douglas Gregor362a8f22010-10-19 19:39:10 +00003446 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003447
Douglas Gregora1194772010-10-19 22:14:33 +00003448 // Compute an upper bound on the allowable edit distance, so that the
3449 // edit-distance algorithm can short-circuit.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003450 unsigned UpperBound = (Typo.size() + 2) / 3;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003451
Douglas Gregor546be3c2009-12-30 17:04:44 +00003452 // Compute the edit distance between the typo and the name of this
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003453 // entity, and add the identifier to the list of results.
3454 addName(Name, NULL, Typo.edit_distance(Name, true, UpperBound));
Douglas Gregor546be3c2009-12-30 17:04:44 +00003455}
3456
Chris Lattner5f9e2722011-07-23 10:55:15 +00003457void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003458 // Compute the edit distance between the typo and this keyword,
3459 // and add the keyword to the list of results.
3460 addName(Keyword, NULL, Typo.edit_distance(Keyword), NULL, true);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003461}
3462
Chris Lattner5f9e2722011-07-23 10:55:15 +00003463void TypoCorrectionConsumer::addName(StringRef Name,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003464 NamedDecl *ND,
3465 unsigned Distance,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003466 NestedNameSpecifier *NNS,
3467 bool isKeyword) {
3468 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
3469 if (isKeyword) TC.makeKeyword();
3470 addCorrection(TC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003471}
3472
3473void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003474 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003475 TypoResultList &CList =
3476 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth55620532011-06-28 22:48:40 +00003477
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003478 if (!CList.empty() && !CList.back().isResolved())
3479 CList.pop_back();
3480 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3481 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3482 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3483 RI != RIEnd; ++RI) {
3484 // If the Correction refers to a decl already in the result list,
3485 // replace the existing result if the string representation of Correction
3486 // comes before the current result alphabetically, then stop as there is
3487 // nothing more to be done to add Correction to the candidate set.
3488 if (RI->getCorrectionDecl() == NewND) {
3489 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3490 *RI = Correction;
3491 return;
3492 }
3493 }
3494 }
3495 if (CList.empty() || Correction.isResolved())
3496 CList.push_back(Correction);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003497
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003498 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
3499 erase(llvm::prior(CorrectionResults.end()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003500}
3501
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003502// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3503// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3504// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3505static void getNestedNameSpecifierIdentifiers(
3506 NestedNameSpecifier *NNS,
3507 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3508 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3509 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3510 else
3511 Identifiers.clear();
3512
3513 const IdentifierInfo *II = NULL;
3514
3515 switch (NNS->getKind()) {
3516 case NestedNameSpecifier::Identifier:
3517 II = NNS->getAsIdentifier();
3518 break;
3519
3520 case NestedNameSpecifier::Namespace:
3521 if (NNS->getAsNamespace()->isAnonymousNamespace())
3522 return;
3523 II = NNS->getAsNamespace()->getIdentifier();
3524 break;
3525
3526 case NestedNameSpecifier::NamespaceAlias:
3527 II = NNS->getAsNamespaceAlias()->getIdentifier();
3528 break;
3529
3530 case NestedNameSpecifier::TypeSpecWithTemplate:
3531 case NestedNameSpecifier::TypeSpec:
3532 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3533 break;
3534
3535 case NestedNameSpecifier::Global:
3536 return;
3537 }
3538
3539 if (II)
3540 Identifiers.push_back(II);
3541}
3542
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003543namespace {
3544
3545class SpecifierInfo {
3546 public:
3547 DeclContext* DeclCtx;
3548 NestedNameSpecifier* NameSpecifier;
3549 unsigned EditDistance;
3550
3551 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3552 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3553};
3554
Chris Lattner5f9e2722011-07-23 10:55:15 +00003555typedef SmallVector<DeclContext*, 4> DeclContextList;
3556typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003557
3558class NamespaceSpecifierSet {
3559 ASTContext &Context;
3560 DeclContextList CurContextChain;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003561 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3562 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003563 bool isSorted;
3564
3565 SpecifierInfoList Specifiers;
3566 llvm::SmallSetVector<unsigned, 4> Distances;
3567 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3568
3569 /// \brief Helper for building the list of DeclContexts between the current
3570 /// context and the top of the translation unit
3571 static DeclContextList BuildContextChain(DeclContext *Start);
3572
3573 void SortNamespaces();
3574
3575 public:
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003576 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3577 CXXScopeSpec *CurScopeSpec)
Benjamin Kramerc5bb9d42011-07-05 09:46:31 +00003578 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
Kaelyn Uhrain8d90b4a2013-06-24 17:49:03 +00003579 isSorted(false) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003580 if (CurScopeSpec && CurScopeSpec->getScopeRep())
3581 getNestedNameSpecifierIdentifiers(CurScopeSpec->getScopeRep(),
3582 CurNameSpecifierIdentifiers);
3583 // Build the list of identifiers that would be used for an absolute
Benjamin Kramer48d798c2012-06-02 10:20:41 +00003584 // (from the global context) NestedNameSpecifier referring to the current
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003585 // context.
3586 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3587 CEnd = CurContextChain.rend();
3588 C != CEnd; ++C) {
3589 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3590 CurContextIdentifiers.push_back(ND->getIdentifier());
3591 }
Kaelyn Uhrain8d90b4a2013-06-24 17:49:03 +00003592
3593 // Add the global context as a NestedNameSpecifier
3594 Distances.insert(1);
3595 DistanceMap[1].push_back(
3596 SpecifierInfo(cast<DeclContext>(Context.getTranslationUnitDecl()),
3597 NestedNameSpecifier::GlobalSpecifier(Context), 1));
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003598 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003599
3600 /// \brief Add the namespace to the set, computing the corresponding
3601 /// NestedNameSpecifier and its distance in the process.
3602 void AddNamespace(NamespaceDecl *ND);
3603
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00003604 /// \brief Add the record to the set, computing the corresponding
3605 /// NestedNameSpecifier and its distance in the process.
3606 void AddRecord(RecordDecl *RD);
3607
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003608 typedef SpecifierInfoList::iterator iterator;
3609 iterator begin() {
3610 if (!isSorted) SortNamespaces();
3611 return Specifiers.begin();
3612 }
3613 iterator end() { return Specifiers.end(); }
3614};
3615
3616}
3617
3618DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Nick Lewycky0db9d202013-04-08 21:55:21 +00003619 assert(Start && "Building a context chain from a null context");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003620 DeclContextList Chain;
3621 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3622 DC = DC->getLookupParent()) {
3623 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3624 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3625 !(ND && ND->isAnonymousNamespace()))
3626 Chain.push_back(DC->getPrimaryContext());
3627 }
3628 return Chain;
3629}
3630
3631void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003632 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003633 sortedDistances.append(Distances.begin(), Distances.end());
3634
3635 if (sortedDistances.size() > 1)
3636 std::sort(sortedDistances.begin(), sortedDistances.end());
3637
3638 Specifiers.clear();
Craig Topper09d19ef2013-07-04 03:08:24 +00003639 for (SmallVectorImpl<unsigned>::iterator DI = sortedDistances.begin(),
3640 DIEnd = sortedDistances.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003641 DI != DIEnd; ++DI) {
3642 SpecifierInfoList &SpecList = DistanceMap[*DI];
3643 Specifiers.append(SpecList.begin(), SpecList.end());
3644 }
3645
3646 isSorted = true;
3647}
3648
3649void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003650 DeclContext *Ctx = cast<DeclContext>(ND);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003651 NestedNameSpecifier *NNS = NULL;
3652 unsigned NumSpecifiers = 0;
3653 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003654 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003655
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003656 // Eliminate common elements from the two DeclContext chains.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003657 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3658 CEnd = CurContextChain.rend();
Chandler Carruth9af7e8e2011-06-28 21:43:34 +00003659 C != CEnd && !NamespaceDeclChain.empty() &&
3660 NamespaceDeclChain.back() == *C; ++C) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003661 NamespaceDeclChain.pop_back();
3662 }
3663
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003664 // Add an explicit leading '::' specifier if needed.
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00003665 if (NamespaceDeclChain.empty()) {
3666 NamespaceDeclChain = FullNamespaceDeclChain;
3667 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3668 } else if (NamespaceDecl *ND =
3669 dyn_cast_or_null<NamespaceDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003670 IdentifierInfo *Name = ND->getIdentifier();
3671 if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3672 Name) != CurContextIdentifiers.end() ||
3673 std::find(CurNameSpecifierIdentifiers.begin(),
3674 CurNameSpecifierIdentifiers.end(),
3675 Name) != CurNameSpecifierIdentifiers.end()) {
3676 NamespaceDeclChain = FullNamespaceDeclChain;
3677 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3678 }
3679 }
3680
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003681 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3682 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3683 CEnd = NamespaceDeclChain.rend();
3684 C != CEnd; ++C) {
3685 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3686 if (ND) {
3687 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3688 ++NumSpecifiers;
3689 }
3690 }
3691
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003692 // If the built NestedNameSpecifier would be replacing an existing
3693 // NestedNameSpecifier, use the number of component identifiers that
3694 // would need to be changed as the edit distance instead of the number
3695 // of components in the built NestedNameSpecifier.
3696 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3697 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3698 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3699 NumSpecifiers = llvm::ComputeEditDistance(
Robert Wilhelm834c0582013-08-09 18:02:13 +00003700 ArrayRef<const IdentifierInfo *>(CurNameSpecifierIdentifiers),
3701 ArrayRef<const IdentifierInfo *>(NewNameSpecifierIdentifiers));
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003702 }
3703
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003704 isSorted = false;
3705 Distances.insert(NumSpecifiers);
3706 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
Douglas Gregoraaf87162010-04-14 20:04:41 +00003707}
3708
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00003709void NamespaceSpecifierSet::AddRecord(RecordDecl *RD) {
3710 if (!RD->isBeingDefined() && !RD->isCompleteDefinition())
3711 return;
3712
3713 DeclContext *Ctx = cast<DeclContext>(RD);
3714 NestedNameSpecifier *NNS = NULL;
3715 unsigned NumSpecifiers = 0;
3716 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
3717 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
3718
3719 // Eliminate common elements from the two DeclContext chains.
3720 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3721 CEnd = CurContextChain.rend();
3722 C != CEnd && !NamespaceDeclChain.empty() &&
3723 NamespaceDeclChain.back() == *C; ++C) {
3724 NamespaceDeclChain.pop_back();
3725 }
3726
3727 // Add an explicit leading '::' specifier if needed.
3728 if (NamespaceDeclChain.empty()) {
3729 NamespaceDeclChain = FullNamespaceDeclChain;
3730 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3731 } else if (NamespaceDecl *ND =
3732 dyn_cast_or_null<NamespaceDecl>(NamespaceDeclChain.back())) {
3733 IdentifierInfo *Name = ND->getIdentifier();
3734 if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3735 Name) != CurContextIdentifiers.end() ||
3736 std::find(CurNameSpecifierIdentifiers.begin(),
3737 CurNameSpecifierIdentifiers.end(),
3738 Name) != CurNameSpecifierIdentifiers.end()) {
3739 NamespaceDeclChain = FullNamespaceDeclChain;
3740 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3741 }
3742 }
3743
3744 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3745 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3746 CEnd = NamespaceDeclChain.rend();
3747 C != CEnd; ++C) {
3748 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) {
3749 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3750 ++NumSpecifiers;
3751 } else if (RecordDecl *RD = dyn_cast_or_null<RecordDecl>(*C)) {
3752 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
3753 RD->getTypeForDecl());
3754 ++NumSpecifiers;
3755 }
3756 }
3757
3758 // If the built NestedNameSpecifier would be replacing an existing
3759 // NestedNameSpecifier, use the number of component identifiers that
3760 // would need to be changed as the edit distance instead of the number
3761 // of components in the built NestedNameSpecifier.
3762 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3763 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3764 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3765 NumSpecifiers = llvm::ComputeEditDistance(
3766 ArrayRef<const IdentifierInfo *>(CurNameSpecifierIdentifiers),
3767 ArrayRef<const IdentifierInfo *>(NewNameSpecifierIdentifiers));
3768 }
3769
3770 isSorted = false;
3771 Distances.insert(NumSpecifiers);
3772 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
3773}
3774
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003775/// \brief Perform name lookup for a possible result for typo correction.
3776static void LookupPotentialTypoResult(Sema &SemaRef,
3777 LookupResult &Res,
3778 IdentifierInfo *Name,
3779 Scope *S, CXXScopeSpec *SS,
3780 DeclContext *MemberContext,
3781 bool EnteringContext,
Richard Smithd67679d2013-08-20 20:35:18 +00003782 bool isObjCIvarLookup,
3783 bool FindHidden) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003784 Res.suppressDiagnostics();
3785 Res.clear();
3786 Res.setLookupName(Name);
Richard Smithd67679d2013-08-20 20:35:18 +00003787 Res.setAllowHidden(FindHidden);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003788 if (MemberContext) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003789 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003790 if (isObjCIvarLookup) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003791 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3792 Res.addDecl(Ivar);
3793 Res.resolveKind();
3794 return;
3795 }
3796 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003797
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003798 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3799 Res.addDecl(Prop);
3800 Res.resolveKind();
3801 return;
3802 }
3803 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003804
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003805 SemaRef.LookupQualifiedName(Res, MemberContext);
3806 return;
3807 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003808
3809 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003810 EnteringContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003811
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003812 // Fake ivar lookup; this should really be part of
3813 // LookupParsedName.
3814 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3815 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003816 (Res.empty() ||
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003817 (Res.isSingleResult() &&
3818 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003819 if (ObjCIvarDecl *IV
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003820 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3821 Res.addDecl(IV);
3822 Res.resolveKind();
3823 }
3824 }
3825 }
3826}
3827
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003828/// \brief Add keywords to the consumer as possible typo corrections.
3829static void AddKeywordsToConsumer(Sema &SemaRef,
3830 TypoCorrectionConsumer &Consumer,
Richard Smith0f4b5be2012-06-08 21:35:42 +00003831 Scope *S, CorrectionCandidateCallback &CCC,
3832 bool AfterNestedNameSpecifier) {
3833 if (AfterNestedNameSpecifier) {
3834 // For 'X::', we know exactly which keywords can appear next.
3835 Consumer.addKeywordResult("template");
3836 if (CCC.WantExpressionKeywords)
3837 Consumer.addKeywordResult("operator");
3838 return;
3839 }
3840
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003841 if (CCC.WantObjCSuper)
3842 Consumer.addKeywordResult("super");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003843
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003844 if (CCC.WantTypeSpecifiers) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003845 // Add type-specifier keywords to the set of results.
Craig Topper3aa29df2013-07-15 08:24:27 +00003846 static const char *const CTypeSpecs[] = {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003847 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor07f4a062011-07-01 21:27:45 +00003848 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003849 "_Complex", "_Imaginary",
3850 // storage-specifiers as well
3851 "extern", "inline", "static", "typedef"
3852 };
3853
Craig Topperb9602322013-07-15 03:38:40 +00003854 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003855 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3856 Consumer.addKeywordResult(CTypeSpecs[I]);
3857
David Blaikie4e4d0842012-03-11 07:00:24 +00003858 if (SemaRef.getLangOpts().C99)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003859 Consumer.addKeywordResult("restrict");
David Blaikie4e4d0842012-03-11 07:00:24 +00003860 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003861 Consumer.addKeywordResult("bool");
David Blaikie4e4d0842012-03-11 07:00:24 +00003862 else if (SemaRef.getLangOpts().C99)
Douglas Gregor07f4a062011-07-01 21:27:45 +00003863 Consumer.addKeywordResult("_Bool");
3864
David Blaikie4e4d0842012-03-11 07:00:24 +00003865 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003866 Consumer.addKeywordResult("class");
3867 Consumer.addKeywordResult("typename");
3868 Consumer.addKeywordResult("wchar_t");
3869
Richard Smith80ad52f2013-01-02 11:42:31 +00003870 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003871 Consumer.addKeywordResult("char16_t");
3872 Consumer.addKeywordResult("char32_t");
3873 Consumer.addKeywordResult("constexpr");
3874 Consumer.addKeywordResult("decltype");
3875 Consumer.addKeywordResult("thread_local");
3876 }
3877 }
3878
David Blaikie4e4d0842012-03-11 07:00:24 +00003879 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003880 Consumer.addKeywordResult("typeof");
3881 }
3882
David Blaikie4e4d0842012-03-11 07:00:24 +00003883 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003884 Consumer.addKeywordResult("const_cast");
3885 Consumer.addKeywordResult("dynamic_cast");
3886 Consumer.addKeywordResult("reinterpret_cast");
3887 Consumer.addKeywordResult("static_cast");
3888 }
3889
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003890 if (CCC.WantExpressionKeywords) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003891 Consumer.addKeywordResult("sizeof");
David Blaikie4e4d0842012-03-11 07:00:24 +00003892 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003893 Consumer.addKeywordResult("false");
3894 Consumer.addKeywordResult("true");
3895 }
3896
David Blaikie4e4d0842012-03-11 07:00:24 +00003897 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topper3aa29df2013-07-15 08:24:27 +00003898 static const char *const CXXExprs[] = {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003899 "delete", "new", "operator", "throw", "typeid"
3900 };
Craig Topperb9602322013-07-15 03:38:40 +00003901 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003902 for (unsigned I = 0; I != NumCXXExprs; ++I)
3903 Consumer.addKeywordResult(CXXExprs[I]);
3904
3905 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3906 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3907 Consumer.addKeywordResult("this");
3908
Richard Smith80ad52f2013-01-02 11:42:31 +00003909 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003910 Consumer.addKeywordResult("alignof");
3911 Consumer.addKeywordResult("nullptr");
3912 }
3913 }
Jordan Rosef70a8862012-06-30 21:33:57 +00003914
3915 if (SemaRef.getLangOpts().C11) {
3916 // FIXME: We should not suggest _Alignof if the alignof macro
3917 // is present.
3918 Consumer.addKeywordResult("_Alignof");
3919 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003920 }
3921
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003922 if (CCC.WantRemainingKeywords) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003923 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3924 // Statements.
Craig Topper3aa29df2013-07-15 08:24:27 +00003925 static const char *const CStmts[] = {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003926 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Topperb9602322013-07-15 03:38:40 +00003927 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003928 for (unsigned I = 0; I != NumCStmts; ++I)
3929 Consumer.addKeywordResult(CStmts[I]);
3930
David Blaikie4e4d0842012-03-11 07:00:24 +00003931 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003932 Consumer.addKeywordResult("catch");
3933 Consumer.addKeywordResult("try");
3934 }
3935
3936 if (S && S->getBreakParent())
3937 Consumer.addKeywordResult("break");
3938
3939 if (S && S->getContinueParent())
3940 Consumer.addKeywordResult("continue");
3941
3942 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3943 Consumer.addKeywordResult("case");
3944 Consumer.addKeywordResult("default");
3945 }
3946 } else {
David Blaikie4e4d0842012-03-11 07:00:24 +00003947 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003948 Consumer.addKeywordResult("namespace");
3949 Consumer.addKeywordResult("template");
3950 }
3951
3952 if (S && S->isClassScope()) {
3953 Consumer.addKeywordResult("explicit");
3954 Consumer.addKeywordResult("friend");
3955 Consumer.addKeywordResult("mutable");
3956 Consumer.addKeywordResult("private");
3957 Consumer.addKeywordResult("protected");
3958 Consumer.addKeywordResult("public");
3959 Consumer.addKeywordResult("virtual");
3960 }
3961 }
3962
David Blaikie4e4d0842012-03-11 07:00:24 +00003963 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003964 Consumer.addKeywordResult("using");
3965
Richard Smith80ad52f2013-01-02 11:42:31 +00003966 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003967 Consumer.addKeywordResult("static_assert");
3968 }
3969 }
3970}
3971
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003972static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3973 TypoCorrection &Candidate) {
3974 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3975 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3976}
3977
Richard Smithd67679d2013-08-20 20:35:18 +00003978/// \brief Check whether the declarations found for a typo correction are
3979/// visible, and if none of them are, convert the correction to an 'import
3980/// a module' correction.
3981static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC,
3982 DeclarationName TypoName) {
3983 if (TC.begin() == TC.end())
3984 return;
3985
3986 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3987
3988 for (/**/; DI != DE; ++DI)
3989 if (!LookupResult::isVisible(SemaRef, *DI))
3990 break;
3991 // Nothing to do if all decls are visible.
3992 if (DI == DE)
3993 return;
3994
3995 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3996 bool AnyVisibleDecls = !NewDecls.empty();
3997
3998 for (/**/; DI != DE; ++DI) {
3999 NamedDecl *VisibleDecl = *DI;
4000 if (!LookupResult::isVisible(SemaRef, *DI))
4001 VisibleDecl = findAcceptableDecl(SemaRef, *DI);
4002
4003 if (VisibleDecl) {
4004 if (!AnyVisibleDecls) {
4005 // Found a visible decl, discard all hidden ones.
4006 AnyVisibleDecls = true;
4007 NewDecls.clear();
4008 }
4009 NewDecls.push_back(VisibleDecl);
4010 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
4011 NewDecls.push_back(*DI);
4012 }
4013
4014 if (NewDecls.empty())
4015 TC = TypoCorrection();
4016 else {
4017 TC.setCorrectionDecls(NewDecls);
4018 TC.setRequiresImport(!AnyVisibleDecls);
4019 }
4020}
4021
Douglas Gregor546be3c2009-12-30 17:04:44 +00004022/// \brief Try to "correct" a typo in the source code by finding
4023/// visible declarations whose names are similar to the name that was
4024/// present in the source code.
4025///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004026/// \param TypoName the \c DeclarationNameInfo structure that contains
4027/// the name that was present in the source code along with its location.
4028///
4029/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor546be3c2009-12-30 17:04:44 +00004030///
4031/// \param S the scope in which name lookup occurs.
4032///
4033/// \param SS the nested-name-specifier that precedes the name we're
4034/// looking for, if present.
4035///
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004036/// \param CCC A CorrectionCandidateCallback object that provides further
4037/// validation of typo correction candidates. It also provides flags for
4038/// determining the set of keywords permitted.
4039///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00004040/// \param MemberContext if non-NULL, the context in which to look for
4041/// a member access expression.
4042///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004043/// \param EnteringContext whether we're entering the context described by
Douglas Gregorbb092ba2009-12-31 05:20:13 +00004044/// the nested-name-specifier SS.
4045///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00004046/// \param OPT when non-NULL, the search for visible declarations will
4047/// also walk the protocols in the qualified interfaces of \p OPT.
4048///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004049/// \returns a \c TypoCorrection containing the corrected name if the typo
4050/// along with information such as the \c NamedDecl where the corrected name
4051/// was declared, and any additional \c NestedNameSpecifier needed to access
4052/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
4053TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
4054 Sema::LookupNameKind LookupKind,
4055 Scope *S, CXXScopeSpec *SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00004056 CorrectionCandidateCallback &CCC,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004057 DeclContext *MemberContext,
4058 bool EnteringContext,
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004059 const ObjCObjectPointerType *OPT,
4060 bool RecordFailure) {
Kaelyn Uhrain70571f42013-08-12 19:54:38 +00004061 // Always let the ExternalSource have the first chance at correction, even
4062 // if we would otherwise have given up.
4063 if (ExternalSource) {
4064 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
4065 TypoName, LookupKind, S, SS, CCC, MemberContext, EnteringContext, OPT))
4066 return Correction;
4067 }
4068
Richard Smith9bd3cdc2013-09-12 23:28:08 +00004069 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4070 DisableTypoCorrection)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004071 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004072
Francois Pichet4d604d62011-12-03 15:55:29 +00004073 // In Microsoft mode, don't perform typo correction in a template member
4074 // function dependent context because it interferes with the "lookup into
4075 // dependent bases of class templates" feature.
David Blaikie4e4d0842012-03-11 07:00:24 +00004076 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichet4d604d62011-12-03 15:55:29 +00004077 isa<CXXMethodDecl>(CurContext))
4078 return TypoCorrection();
4079
Douglas Gregor546be3c2009-12-30 17:04:44 +00004080 // We only attempt to correct typos for identifiers.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004081 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor546be3c2009-12-30 17:04:44 +00004082 if (!Typo)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004083 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00004084
4085 // If the scope specifier itself was invalid, don't try to correct
4086 // typos.
4087 if (SS && SS->isInvalid())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004088 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00004089
4090 // Never try to correct typos during template deduction or
4091 // instantiation.
4092 if (!ActiveTemplateInstantiations.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004093 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004094
Argyrios Kyrtzidis57f8da52013-03-14 22:56:43 +00004095 // Don't try to correct 'super'.
4096 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4097 return TypoCorrection();
4098
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004099 // Abort if typo correction already failed for this specific typo.
4100 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4101 if (locs != TypoCorrectionFailures.end() &&
4102 locs->second.count(TypoName.getLoc()) > 0)
4103 return TypoCorrection();
4104
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004105 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004106
4107 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004108
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00004109 // If a callback object considers an empty typo correction candidate to be
4110 // viable, assume it does not do any actual validation of the candidates.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004111 TypoCorrection EmptyCorrection;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00004112 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004113
Douglas Gregoraaf87162010-04-14 20:04:41 +00004114 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004115 bool IsUnqualifiedLookup = false;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004116 DeclContext *QualifiedDC = MemberContext;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00004117 if (MemberContext) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004118 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00004119
4120 // Look in qualified interfaces.
4121 if (OPT) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004122 for (ObjCObjectPointerType::qual_iterator
4123 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00004124 I != E; ++I)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004125 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00004126 }
4127 } else if (SS && SS->isSet()) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004128 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4129 if (!QualifiedDC)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004130 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004131
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004132 // Provide a stop gap for files that are just seriously broken. Trying
4133 // to correct all typos can turn into a HUGE performance penalty, causing
4134 // some files to take minutes to get rejected by the parser.
4135 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004136 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004137 ++TyposCorrected;
4138
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004139 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
Douglas Gregor546be3c2009-12-30 17:04:44 +00004140 } else {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004141 IsUnqualifiedLookup = true;
4142 UnqualifiedTyposCorrectedMap::iterator Cached
4143 = UnqualifiedTyposCorrected.find(Typo);
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004144 if (Cached != UnqualifiedTyposCorrected.end()) {
4145 // Add the cached value, unless it's a keyword or fails validation. In the
4146 // keyword case, we'll end up adding the keyword below.
4147 if (Cached->second) {
4148 if (!Cached->second.isKeyword() &&
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00004149 isCandidateViable(CCC, Cached->second))
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004150 Consumer.addCorrection(Cached->second);
4151 } else {
4152 // Only honor no-correction cache hits when a callback that will validate
4153 // correction candidates is not being used.
4154 if (!ValidatingCallback)
4155 return TypoCorrection();
4156 }
4157 }
4158 if (Cached == UnqualifiedTyposCorrected.end()) {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004159 // Provide a stop gap for files that are just seriously broken. Trying
4160 // to correct all typos can turn into a HUGE performance penalty, causing
4161 // some files to take minutes to get rejected by the parser.
4162 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004163 return TypoCorrection();
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004164 }
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004165 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004166
Douglas Gregor01798682012-03-26 16:54:18 +00004167 // Determine whether we are going to search in the various namespaces for
4168 // corrections.
4169 bool SearchNamespaces
Kaelyn Uhrain6d858d92012-04-03 18:20:11 +00004170 = getLangOpts().CPlusPlus &&
Douglas Gregor01798682012-03-26 16:54:18 +00004171 (IsUnqualifiedLookup || (QualifiedDC && QualifiedDC->isNamespace()));
Richard Smithd67679d2013-08-20 20:35:18 +00004172 // In a few cases we *only* want to search for corrections based on just
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00004173 // adding or changing the nested name specifier.
4174 bool AllowOnlyNNSChanges = Typo->getName().size() < 3;
Douglas Gregor01798682012-03-26 16:54:18 +00004175
4176 if (IsUnqualifiedLookup || SearchNamespaces) {
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004177 // For unqualified lookup, look through all of the names that we have
4178 // seen in this translation unit.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00004179 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004180 for (IdentifierTable::iterator I = Context.Idents.begin(),
4181 IEnd = Context.Idents.end();
4182 I != IEnd; ++I)
4183 Consumer.FoundName(I->getKey());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004184
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004185 // Walk through identifiers in external identifier sources.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00004186 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004187 if (IdentifierInfoLookup *External
4188 = Context.Idents.getExternalIdentifierLookup()) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00004189 OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004190 do {
4191 StringRef Name = Iter->Next();
4192 if (Name.empty())
4193 break;
Douglas Gregor95f42922010-10-14 22:11:03 +00004194
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004195 Consumer.FoundName(Name);
4196 } while (true);
Douglas Gregor95f42922010-10-14 22:11:03 +00004197 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00004198 }
4199
Richard Smith0f4b5be2012-06-08 21:35:42 +00004200 AddKeywordsToConsumer(*this, Consumer, S, CCC, SS && SS->isNotEmpty());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004201
Douglas Gregoraaf87162010-04-14 20:04:41 +00004202 // If we haven't found anything, we're done.
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004203 if (Consumer.empty())
4204 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4205 IsUnqualifiedLookup);
Douglas Gregor546be3c2009-12-30 17:04:44 +00004206
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00004207 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4208 // is not more that about a third of the length of the typo's identifier.
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00004209 unsigned ED = Consumer.getBestEditDistance(true);
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004210 if (ED > 0 && Typo->getName().size() / ED < 3)
4211 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4212 IsUnqualifiedLookup);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004213
Douglas Gregor01798682012-03-26 16:54:18 +00004214 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4215 // to search those namespaces.
4216 if (SearchNamespaces) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004217 // Load any externally-known namespaces.
4218 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004219 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004220 LoadedExternalKnownNamespaces = true;
4221 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4222 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
4223 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
4224 }
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00004225
4226 for (llvm::MapVector<NamespaceDecl*, bool>::iterator
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004227 KNI = KnownNamespaces.begin(),
4228 KNIEnd = KnownNamespaces.end();
4229 KNI != KNIEnd; ++KNI)
4230 Namespaces.AddNamespace(KNI->first);
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00004231
4232 for (ASTContext::type_iterator TI = Context.types_begin(),
4233 TIEnd = Context.types_end();
4234 TI != TIEnd; ++TI) {
4235 if (CXXRecordDecl *CD = (*TI)->getAsCXXRecordDecl()) {
4236 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
4237 !CD->isUnion())
4238 Namespaces.AddRecord(CD);
4239 }
4240 }
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004241 }
Douglas Gregore24b5752010-10-14 20:34:08 +00004242
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004243 // Weed out any names that could not be found by name lookup or, if a
4244 // CorrectionCandidateCallback object was provided, failed validation.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004245 SmallVector<TypoCorrection, 16> QualifiedResults;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004246 LookupResult TmpRes(*this, TypoName, LookupKind);
4247 TmpRes.suppressDiagnostics();
4248 while (!Consumer.empty()) {
4249 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
4250 unsigned ED = DI->first;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004251 for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(),
4252 IEnd = DI->second.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004253 I != IEnd; /* Increment in loop. */) {
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00004254 // If we only want nested name specifier corrections, ignore potential
4255 // corrections that have a different base identifier from the typo.
4256 if (AllowOnlyNNSChanges &&
4257 I->second.front().getCorrectionAsIdentifierInfo() != Typo) {
4258 TypoCorrectionConsumer::result_iterator Prev = I;
4259 ++I;
4260 DI->second.erase(Prev);
4261 continue;
4262 }
4263
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004264 // If the item already has been looked up or is a keyword, keep it.
4265 // If a validator callback object was given, drop the correction
4266 // unless it passes validation.
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004267 bool Viable = false;
Benjamin Kramerb3996962012-07-27 10:21:08 +00004268 for (TypoResultList::iterator RI = I->second.begin();
4269 RI != I->second.end(); /* Increment in loop. */) {
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004270 TypoResultList::iterator Prev = RI;
4271 ++RI;
4272 if (Prev->isResolved()) {
4273 if (!isCandidateViable(CCC, *Prev))
Benjamin Kramerb3996962012-07-27 10:21:08 +00004274 RI = I->second.erase(Prev);
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004275 else
4276 Viable = true;
4277 }
4278 }
4279 if (Viable || I->second.empty()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004280 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004281 ++I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004282 if (!Viable)
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004283 DI->second.erase(Prev);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004284 continue;
Douglas Gregore24b5752010-10-14 20:34:08 +00004285 }
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004286 assert(I->second.size() == 1 && "Expected a single unresolved candidate");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004287
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004288 // Perform name lookup on this name.
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004289 TypoCorrection &Candidate = I->second.front();
4290 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00004291 DeclContext *TempMemberContext = MemberContext;
4292 CXXScopeSpec *TempSS = SS;
4293retry_lookup:
4294 LookupPotentialTypoResult(*this, TmpRes, Name, S, TempSS,
4295 TempMemberContext, EnteringContext,
Richard Smithd67679d2013-08-20 20:35:18 +00004296 CCC.IsObjCIvarLookup,
4297 Name == TypoName.getName() &&
4298 !Candidate.WillReplaceSpecifier());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004299
4300 switch (TmpRes.getResultKind()) {
4301 case LookupResult::NotFound:
4302 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00004303 case LookupResult::FoundUnresolvedValue:
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00004304 if (TempSS) {
4305 // Immediately retry the lookup without the given CXXScopeSpec
4306 TempSS = NULL;
4307 Candidate.WillReplaceSpecifier(true);
4308 goto retry_lookup;
4309 }
4310 if (TempMemberContext) {
4311 if (SS && !TempSS)
4312 TempSS = SS;
4313 TempMemberContext = NULL;
4314 goto retry_lookup;
4315 }
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004316 QualifiedResults.push_back(Candidate);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004317 // We didn't find this name in our scope, or didn't like what we found;
4318 // ignore it.
4319 {
4320 TypoCorrectionConsumer::result_iterator Next = I;
4321 ++Next;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004322 DI->second.erase(I);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004323 I = Next;
4324 }
4325 break;
4326
4327 case LookupResult::Ambiguous:
4328 // We don't deal with ambiguities.
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004329 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004330
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004331 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004332 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004333 // Store all of the Decls for overloaded symbols
4334 for (LookupResult::iterator TRD = TmpRes.begin(),
4335 TRDEnd = TmpRes.end();
4336 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004337 Candidate.addCorrectionDecl(*TRD);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004338 ++I;
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004339 if (!isCandidateViable(CCC, Candidate)) {
4340 QualifiedResults.push_back(Candidate);
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004341 DI->second.erase(Prev);
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004342 }
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004343 break;
4344 }
4345
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004346 case LookupResult::Found: {
4347 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004348 Candidate.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004349 ++I;
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004350 if (!isCandidateViable(CCC, Candidate)) {
4351 QualifiedResults.push_back(Candidate);
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004352 DI->second.erase(Prev);
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004353 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004354 break;
4355 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004356
4357 }
Douglas Gregore24b5752010-10-14 20:34:08 +00004358 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004359
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004360 if (DI->second.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004361 Consumer.erase(DI);
David Blaikie4e4d0842012-03-11 07:00:24 +00004362 else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !ED)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004363 // If there are results in the closest possible bucket, stop
4364 break;
4365
4366 // Only perform the qualified lookups for C++
Douglas Gregor01798682012-03-26 16:54:18 +00004367 if (SearchNamespaces) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004368 TmpRes.suppressDiagnostics();
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004369 for (SmallVector<TypoCorrection,
4370 16>::iterator QRI = QualifiedResults.begin(),
4371 QRIEnd = QualifiedResults.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004372 QRI != QRIEnd; ++QRI) {
4373 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
4374 NIEnd = Namespaces.end();
4375 NI != NIEnd; ++NI) {
4376 DeclContext *Ctx = NI->DeclCtx;
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00004377 const Type *NSType = NI->NameSpecifier->getAsType();
4378
4379 // If the current NestedNameSpecifier refers to a class and the
4380 // current correction candidate is the name of that class, then skip
4381 // it as it is unlikely a qualified version of the class' constructor
4382 // is an appropriate correction.
4383 if (CXXRecordDecl *NSDecl =
4384 NSType ? NSType->getAsCXXRecordDecl() : 0) {
4385 if (NSDecl->getIdentifier() == QRI->getCorrectionAsIdentifierInfo())
4386 continue;
4387 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004388
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00004389 // FIXME: Stop searching once the namespaces are too far away to create
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004390 // acceptable corrections for this identifier (since the namespaces
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00004391 // are sorted in ascending order by edit distance).
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004392
4393 TmpRes.clear();
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00004394 TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004395 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
4396
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004397 // Any corrections added below will be validated in subsequent
4398 // iterations of the main while() loop over the Consumer's contents.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004399 switch (TmpRes.getResultKind()) {
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004400 case LookupResult::Found:
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004401 case LookupResult::FoundOverloaded: {
4402 TypoCorrection TC(*QRI);
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00004403 TC.ClearCorrectionDecls();
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004404 TC.setCorrectionSpecifier(NI->NameSpecifier);
4405 TC.setQualifierDistance(NI->EditDistance);
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004406 TC.setCallbackDistance(0); // Reset the callback distance
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004407 for (LookupResult::iterator TRD = TmpRes.begin(),
4408 TRDEnd = TmpRes.end();
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00004409 TRD != TRDEnd; ++TRD) {
4410 if (CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4411 NSType ? NSType->getAsCXXRecordDecl() : 0,
Eli Friedman91d3f332013-10-01 02:44:48 +00004412 TRD.getPair()) == AR_accessible)
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00004413 TC.addCorrectionDecl(*TRD);
4414 }
4415 if (TC.isResolved())
4416 Consumer.addCorrection(TC);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004417 break;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004418 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004419 case LookupResult::NotFound:
4420 case LookupResult::NotFoundInCurrentInstantiation:
4421 case LookupResult::Ambiguous:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00004422 case LookupResult::FoundUnresolvedValue:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004423 break;
4424 }
4425 }
4426 }
4427 }
4428
4429 QualifiedResults.clear();
4430 }
4431
4432 // No corrections remain...
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004433 if (Consumer.empty())
4434 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004435
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00004436 TypoResultsMap &BestResults = Consumer.getBestResults();
4437 ED = Consumer.getBestEditDistance(true);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004438
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00004439 if (!AllowOnlyNNSChanges && ED > 0 && Typo->getName().size() / ED < 3) {
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004440 // If this was an unqualified lookup and we believe the callback
4441 // object wouldn't have filtered out possible corrections, note
4442 // that no correction was found.
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004443 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4444 IsUnqualifiedLookup && !ValidatingCallback);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004445 }
4446
Douglas Gregore24b5752010-10-14 20:34:08 +00004447 // If only a single name remains, return that result.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004448 if (BestResults.size() == 1) {
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004449 const TypoResultList &CorrectionList = BestResults.begin()->second;
4450 const TypoCorrection &Result = CorrectionList.front();
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004451 if (CorrectionList.size() != 1)
4452 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004453
Douglas Gregor53e4b552010-10-26 17:18:00 +00004454 // Don't correct to a keyword that's the same as the typo; the keyword
4455 // wasn't actually in scope.
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004456 if (ED == 0 && Result.isKeyword())
4457 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004458
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004459 // Record the correction for unqualified lookup.
4460 if (IsUnqualifiedLookup)
4461 UnqualifiedTyposCorrected[Typo] = Result;
4462
David Blaikie6952c012012-10-12 20:00:44 +00004463 TypoCorrection TC = Result;
4464 TC.setCorrectionRange(SS, TypoName);
Richard Smithd67679d2013-08-20 20:35:18 +00004465 checkCorrectionVisibility(*this, TC, TypoName.getName());
David Blaikie6952c012012-10-12 20:00:44 +00004466 return TC;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004467 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004468 else if (BestResults.size() > 1
4469 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4470 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4471 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4472 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00004473 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004474 && BestResults["super"].front().isKeyword()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004475 // Prefer 'super' when we're completing in a message-receiver
4476 // context.
4477
4478 // Don't correct to a keyword that's the same as the typo; the keyword
4479 // wasn't actually in scope.
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004480 if (ED == 0)
4481 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004482
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004483 // Record the correction for unqualified lookup.
4484 if (IsUnqualifiedLookup)
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004485 UnqualifiedTyposCorrected[Typo] = BestResults["super"].front();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004486
David Blaikie6952c012012-10-12 20:00:44 +00004487 TypoCorrection TC = BestResults["super"].front();
4488 TC.setCorrectionRange(SS, TypoName);
4489 return TC;
Douglas Gregor7b824e82010-10-15 13:35:25 +00004490 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004491
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004492 // If this was an unqualified lookup and we believe the callback object did
4493 // not filter out possible corrections, note that no correction was found.
4494 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004495 (void)UnqualifiedTyposCorrected[Typo];
4496
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004497 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004498}
4499
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004500void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4501 if (!CDecl) return;
4502
4503 if (isKeyword())
4504 CorrectionDecls.clear();
4505
Kaelyn Uhrain728948f2012-11-19 18:49:53 +00004506 CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004507
4508 if (!CorrectionName)
4509 CorrectionName = CDecl->getDeclName();
4510}
4511
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004512std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4513 if (CorrectionNameSpec) {
4514 std::string tmpBuffer;
4515 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4516 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikie17828ca2013-05-14 21:04:00 +00004517 PrefixOStream << CorrectionName;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004518 return PrefixOStream.str();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004519 }
4520
4521 return CorrectionName.getAsString();
Douglas Gregor546be3c2009-12-30 17:04:44 +00004522}
Kaelyn Uhrain20a7cf42013-04-03 16:59:49 +00004523
4524bool CorrectionCandidateCallback::ValidateCandidate(const TypoCorrection &candidate) {
4525 if (!candidate.isResolved())
4526 return true;
4527
4528 if (candidate.isKeyword())
4529 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4530 WantRemainingKeywords || WantObjCSuper;
4531
4532 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
4533 CDeclEnd = candidate.end();
4534 CDecl != CDeclEnd; ++CDecl) {
4535 if (!isa<TypeDecl>(*CDecl))
4536 return true;
4537 }
4538
4539 return WantTypeSpecifiers;
4540}
Kaelyn Uhrain761695f2013-07-08 23:13:39 +00004541
4542FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
4543 bool HasExplicitTemplateArgs)
4544 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
4545 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
4546 WantRemainingKeywords = false;
4547}
4548
4549bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4550 if (!candidate.getCorrectionDecl())
4551 return candidate.isKeyword();
4552
4553 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
4554 DIEnd = candidate.end();
4555 DI != DIEnd; ++DI) {
4556 FunctionDecl *FD = 0;
4557 NamedDecl *ND = (*DI)->getUnderlyingDecl();
4558 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4559 FD = FTD->getTemplatedDecl();
4560 if (!HasExplicitTemplateArgs && !FD) {
4561 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4562 // If the Decl is neither a function nor a template function,
4563 // determine if it is a pointer or reference to a function. If so,
4564 // check against the number of arguments expected for the pointee.
4565 QualType ValType = cast<ValueDecl>(ND)->getType();
4566 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4567 ValType = ValType->getPointeeType();
4568 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
4569 if (FPT->getNumArgs() == NumArgs)
4570 return true;
4571 }
4572 }
4573 if (FD && FD->getNumParams() >= NumArgs &&
4574 FD->getMinRequiredArguments() <= NumArgs)
4575 return true;
4576 }
4577 return false;
4578}
Richard Smith2d670972013-08-17 00:46:16 +00004579
4580void Sema::diagnoseTypo(const TypoCorrection &Correction,
4581 const PartialDiagnostic &TypoDiag,
4582 bool ErrorRecovery) {
4583 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
4584 ErrorRecovery);
4585}
4586
Richard Smithd67679d2013-08-20 20:35:18 +00004587/// Find which declaration we should import to provide the definition of
4588/// the given declaration.
4589static const NamedDecl *getDefinitionToImport(const NamedDecl *D) {
4590 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4591 return VD->getDefinition();
4592 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4593 return FD->isDefined(FD) ? FD : 0;
4594 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
4595 return TD->getDefinition();
4596 if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
4597 return ID->getDefinition();
4598 if (const ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
4599 return PD->getDefinition();
4600 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
4601 return getDefinitionToImport(TD->getTemplatedDecl());
4602 return 0;
4603}
4604
Richard Smith2d670972013-08-17 00:46:16 +00004605/// \brief Diagnose a successfully-corrected typo. Separated from the correction
4606/// itself to allow external validation of the result, etc.
4607///
4608/// \param Correction The result of performing typo correction.
4609/// \param TypoDiag The diagnostic to produce. This will have the corrected
4610/// string added to it (and usually also a fixit).
4611/// \param PrevNote A note to use when indicating the location of the entity to
4612/// which we are correcting. Will have the correction string added to it.
4613/// \param ErrorRecovery If \c true (the default), the caller is going to
4614/// recover from the typo as if the corrected string had been typed.
4615/// In this case, \c PDiag must be an error, and we will attach a fixit
4616/// to it.
4617void Sema::diagnoseTypo(const TypoCorrection &Correction,
4618 const PartialDiagnostic &TypoDiag,
4619 const PartialDiagnostic &PrevNote,
4620 bool ErrorRecovery) {
4621 std::string CorrectedStr = Correction.getAsString(getLangOpts());
4622 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
4623 FixItHint FixTypo = FixItHint::CreateReplacement(
4624 Correction.getCorrectionRange(), CorrectedStr);
4625
Richard Smithd67679d2013-08-20 20:35:18 +00004626 // Maybe we're just missing a module import.
4627 if (Correction.requiresImport()) {
4628 NamedDecl *Decl = Correction.getCorrectionDecl();
4629 assert(Decl && "import required but no declaration to import");
4630
4631 // Suggest importing a module providing the definition of this entity, if
4632 // possible.
4633 const NamedDecl *Def = getDefinitionToImport(Decl);
4634 if (!Def)
4635 Def = Decl;
4636 Module *Owner = Def->getOwningModule();
4637 assert(Owner && "definition of hidden declaration is not in a module");
4638
4639 Diag(Correction.getCorrectionRange().getBegin(),
4640 diag::err_module_private_declaration)
4641 << Def << Owner->getFullModuleName();
4642 Diag(Def->getLocation(), diag::note_previous_declaration);
4643
4644 // Recover by implicitly importing this module.
4645 if (!isSFINAEContext() && ErrorRecovery)
4646 createImplicitModuleImport(Correction.getCorrectionRange().getBegin(),
4647 Owner);
4648 return;
4649 }
4650
Richard Smith2d670972013-08-17 00:46:16 +00004651 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
4652 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
4653
4654 NamedDecl *ChosenDecl =
4655 Correction.isKeyword() ? 0 : Correction.getCorrectionDecl();
4656 if (PrevNote.getDiagID() && ChosenDecl)
4657 Diag(ChosenDecl->getLocation(), PrevNote)
4658 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
4659}