blob: 919c6ad61ab27d0393dfadd638cfa62721e1b6b0 [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.
Ted Kremenekf0d58612013-10-08 17:08:03 +0000105 DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
John McCalld7be78a2009-11-10 07:01:13 +0000106 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000107
John McCalld7be78a2009-11-10 07:01:13 +0000108 for (; S; S = S->getParent()) {
Nick Lewycky65daef12012-03-13 04:12:34 +0000109 // C++ [namespace.udir]p1:
110 // A using-directive shall not appear in class scope, but may
111 // appear in namespace scope or in block scope.
Ted Kremenekf0d58612013-10-08 17:08:03 +0000112 DeclContext *Ctx = S->getEntity();
Nick Lewycky65daef12012-03-13 04:12:34 +0000113 if (Ctx && Ctx->isFileContext()) {
114 visit(Ctx, Ctx);
115 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
John McCalld7be78a2009-11-10 07:01:13 +0000116 Scope::udir_iterator I = S->using_directives_begin(),
117 End = S->using_directives_end();
John McCalld7be78a2009-11-10 07:01:13 +0000118 for (; I != End; ++I)
John McCalld226f652010-08-21 09:40:31 +0000119 visit(*I, InnermostFileDC);
John McCalld7be78a2009-11-10 07:01:13 +0000120 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000121 }
122 }
John McCalld7be78a2009-11-10 07:01:13 +0000123
124 // Visits a context and collect all of its using directives
125 // recursively. Treats all using directives as if they were
126 // declared in the context.
127 //
128 // A given context is only every visited once, so it is important
129 // that contexts be visited from the inside out in order to get
130 // the effective DCs right.
131 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
132 if (!visited.insert(DC))
133 return;
134
135 addUsingDirectives(DC, EffectiveDC);
136 }
137
138 // Visits a using directive and collects all of its using
139 // directives recursively. Treats all using directives as if they
140 // were declared in the effective DC.
141 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
142 DeclContext *NS = UD->getNominatedNamespace();
143 if (!visited.insert(NS))
144 return;
145
146 addUsingDirective(UD, EffectiveDC);
147 addUsingDirectives(NS, EffectiveDC);
148 }
149
150 // Adds all the using directives in a context (and those nominated
151 // by its using directives, transitively) as if they appeared in
152 // the given effective context.
153 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000154 SmallVector<DeclContext*,4> queue;
John McCalld7be78a2009-11-10 07:01:13 +0000155 while (true) {
156 DeclContext::udir_iterator I, End;
157 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
158 UsingDirectiveDecl *UD = *I;
159 DeclContext *NS = UD->getNominatedNamespace();
160 if (visited.insert(NS)) {
161 addUsingDirective(UD, EffectiveDC);
162 queue.push_back(NS);
163 }
164 }
165
166 if (queue.empty())
167 return;
168
Robert Wilhelm344472e2013-08-23 16:11:15 +0000169 DC = queue.pop_back_val();
John McCalld7be78a2009-11-10 07:01:13 +0000170 }
171 }
172
173 // Add a using directive as if it had been declared in the given
174 // context. This helps implement C++ [namespace.udir]p3:
175 // The using-directive is transitive: if a scope contains a
176 // using-directive that nominates a second namespace that itself
177 // contains using-directives, the effect is as if the
178 // using-directives from the second namespace also appeared in
179 // the first.
180 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
181 // Find the common ancestor between the effective context and
182 // the nominated namespace.
183 DeclContext *Common = UD->getNominatedNamespace();
184 while (!Common->Encloses(EffectiveDC))
185 Common = Common->getParent();
John McCall12ea5782009-11-10 09:20:04 +0000186 Common = Common->getPrimaryContext();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000187
John McCalld7be78a2009-11-10 07:01:13 +0000188 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
189 }
190
191 void done() {
192 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
193 }
194
John McCalld7be78a2009-11-10 07:01:13 +0000195 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000196
John McCalld7be78a2009-11-10 07:01:13 +0000197 const_iterator begin() const { return list.begin(); }
198 const_iterator end() const { return list.end(); }
199
200 std::pair<const_iterator,const_iterator>
201 getNamespacesFor(DeclContext *DC) const {
John McCall12ea5782009-11-10 09:20:04 +0000202 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCalld7be78a2009-11-10 07:01:13 +0000203 UnqualUsingEntry::Comparator());
204 }
205 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000206}
207
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000208// Retrieve the set of identifier namespaces that correspond to a
209// specific kind of name lookup.
John McCall1d7c5282009-12-18 10:40:03 +0000210static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
211 bool CPlusPlus,
212 bool Redeclaration) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000213 unsigned IDNS = 0;
214 switch (NameKind) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +0000215 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000216 case Sema::LookupOrdinaryName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000217 case Sema::LookupRedeclarationWithLinkage:
Richard Smith4e9686b2013-08-09 04:35:01 +0000218 case Sema::LookupLocalFriendName:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000219 IDNS = Decl::IDNS_Ordinary;
John McCall1d7c5282009-12-18 10:40:03 +0000220 if (CPlusPlus) {
John McCall0d6b1642010-04-23 18:46:30 +0000221 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattner337e5502011-02-18 01:27:55 +0000222 if (Redeclaration)
223 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCall1d7c5282009-12-18 10:40:03 +0000224 }
Richard Smitha41c97a2013-09-20 01:15:31 +0000225 if (Redeclaration)
226 IDNS |= Decl::IDNS_LocalExtern;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000227 break;
228
John McCall76d32642010-04-24 01:30:58 +0000229 case Sema::LookupOperatorName:
230 // Operator lookup is its own crazy thing; it is not the same
231 // as (e.g.) looking up an operator name for redeclaration.
232 assert(!Redeclaration && "cannot do redeclaration operator lookup");
233 IDNS = Decl::IDNS_NonMemberOperator;
234 break;
235
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000236 case Sema::LookupTagName:
John McCall0d6b1642010-04-23 18:46:30 +0000237 if (CPlusPlus) {
238 IDNS = Decl::IDNS_Type;
239
240 // When looking for a redeclaration of a tag name, we add:
241 // 1) TagFriend to find undeclared friend decls
242 // 2) Namespace because they can't "overload" with tag decls.
243 // 3) Tag because it includes class templates, which can't
244 // "overload" with tag decls.
245 if (Redeclaration)
246 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
247 } else {
248 IDNS = Decl::IDNS_Tag;
249 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000250 break;
Chris Lattner337e5502011-02-18 01:27:55 +0000251 case Sema::LookupLabel:
252 IDNS = Decl::IDNS_Label;
253 break;
254
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000255 case Sema::LookupMemberName:
256 IDNS = Decl::IDNS_Member;
257 if (CPlusPlus)
Mike Stump1eb44332009-09-09 15:08:12 +0000258 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000259 break;
260
261 case Sema::LookupNestedNameSpecifierName:
John McCall0d6b1642010-04-23 18:46:30 +0000262 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
263 break;
264
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000265 case Sema::LookupNamespaceName:
John McCall0d6b1642010-04-23 18:46:30 +0000266 IDNS = Decl::IDNS_Namespace;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000267 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000268
John McCall9f54ad42009-12-10 09:41:52 +0000269 case Sema::LookupUsingDeclName:
270 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
271 | Decl::IDNS_Member | Decl::IDNS_Using;
272 break;
273
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000274 case Sema::LookupObjCProtocolName:
275 IDNS = Decl::IDNS_ObjCProtocol;
276 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000277
Douglas Gregor8071e422010-08-15 06:18:01 +0000278 case Sema::LookupAnyName:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000279 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor8071e422010-08-15 06:18:01 +0000280 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
281 | Decl::IDNS_Type;
282 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000283 }
284 return IDNS;
285}
286
John McCall1d7c5282009-12-18 10:40:03 +0000287void LookupResult::configure() {
David Blaikie4e4d0842012-03-11 07:00:24 +0000288 IDNS = getIDNS(LookupKind, SemaRef.getLangOpts().CPlusPlus,
John McCall1d7c5282009-12-18 10:40:03 +0000289 isForRedeclaration());
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000290
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000291 if (!isForRedeclaration()) {
Douglas Gregor96df3562013-04-03 23:06:26 +0000292 // If we're looking for one of the allocation or deallocation
293 // operators, make sure that the implicitly-declared new and delete
294 // operators can be found.
Abramo Bagnara25777432010-08-11 22:01:17 +0000295 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000296 case OO_New:
297 case OO_Delete:
298 case OO_Array_New:
299 case OO_Array_Delete:
300 SemaRef.DeclareGlobalNewDelete();
301 break;
302
303 default:
304 break;
305 }
Douglas Gregor96df3562013-04-03 23:06:26 +0000306
307 // Compiler builtins are always visible, regardless of where they end
308 // up being declared.
309 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
310 if (unsigned BuiltinID = Id->getBuiltinID()) {
311 if (!SemaRef.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
312 AllowHidden = true;
313 }
314 }
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000315 }
John McCall1d7c5282009-12-18 10:40:03 +0000316}
317
Daniel Dunbarc2bd73b2012-03-08 01:43:06 +0000318void LookupResult::sanityImpl() const {
319 // Note that this function is never called by NDEBUG builds. See
320 // LookupResult::sanity().
John McCall2a7fb272010-08-25 05:32:35 +0000321 assert(ResultKind != NotFound || Decls.size() == 0);
322 assert(ResultKind != Found || Decls.size() == 1);
323 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
324 (Decls.size() == 1 &&
325 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
326 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
327 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorf17b58c2010-10-22 22:08:47 +0000328 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
329 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall2a7fb272010-08-25 05:32:35 +0000330 assert((Paths != NULL) == (ResultKind == Ambiguous &&
331 (Ambiguity == AmbiguousBaseSubobjectTypes ||
332 Ambiguity == AmbiguousBaseSubobjects)));
333}
John McCall2a7fb272010-08-25 05:32:35 +0000334
John McCallf36e02d2009-10-09 21:13:30 +0000335// Necessary because CXXBasePaths is not complete in Sema.h
John McCall7d384dd2009-11-18 07:57:50 +0000336void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCallf36e02d2009-10-09 21:13:30 +0000337 delete Paths;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000338}
339
Richard Smith190d1af2013-10-30 01:02:04 +0000340/// Get a representative context for a declaration such that two declarations
341/// will have the same context if they were found within the same scope.
Benjamin Kramere28bdc32013-11-01 11:50:55 +0000342static DeclContext *getContextForScopeMatching(Decl *D) {
Richard Smith190d1af2013-10-30 01:02:04 +0000343 // For function-local declarations, use that function as the context. This
344 // doesn't account for scopes within the function; the caller must deal with
345 // those.
346 DeclContext *DC = D->getLexicalDeclContext();
347 if (DC->isFunctionOrMethod())
348 return DC;
349
350 // Otherwise, look at the semantic context of the declaration. The
351 // declaration must have been found there.
352 return D->getDeclContext()->getRedeclContext();
353}
354
John McCall7453ed42009-11-22 00:44:51 +0000355/// Resolves the result kind of this lookup.
John McCall7d384dd2009-11-18 07:57:50 +0000356void LookupResult::resolveKind() {
John McCallf36e02d2009-10-09 21:13:30 +0000357 unsigned N = Decls.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000358
John McCallf36e02d2009-10-09 21:13:30 +0000359 // Fast case: no possible ambiguity.
John McCall68263142009-11-18 22:49:29 +0000360 if (N == 0) {
John McCalldc5c7862010-01-15 21:27:01 +0000361 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall68263142009-11-18 22:49:29 +0000362 return;
363 }
364
John McCall7453ed42009-11-22 00:44:51 +0000365 // If there's a single decl, we need to examine it to decide what
366 // kind of lookup this is.
John McCall7ba107a2009-11-18 02:36:19 +0000367 if (N == 1) {
Douglas Gregor2b147f02010-04-25 21:15:30 +0000368 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
369 if (isa<FunctionTemplateDecl>(D))
John McCall7453ed42009-11-22 00:44:51 +0000370 ResultKind = FoundOverloaded;
Douglas Gregor2b147f02010-04-25 21:15:30 +0000371 else if (isa<UnresolvedUsingValueDecl>(D))
John McCall7ba107a2009-11-18 02:36:19 +0000372 ResultKind = FoundUnresolvedValue;
373 return;
374 }
John McCallf36e02d2009-10-09 21:13:30 +0000375
John McCall6e247262009-10-10 05:48:19 +0000376 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000377 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000378
John McCallf36e02d2009-10-09 21:13:30 +0000379 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000380 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000381
John McCallf36e02d2009-10-09 21:13:30 +0000382 bool Ambiguous = false;
383 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000384 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000385
386 unsigned UniqueTagIndex = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000387
John McCallf36e02d2009-10-09 21:13:30 +0000388 unsigned I = 0;
389 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000390 NamedDecl *D = Decls[I]->getUnderlyingDecl();
391 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000392
Argyrios Kyrtzidis745af1c2013-02-22 06:58:37 +0000393 // Ignore an invalid declaration unless it's the only one left.
394 if (D->isInvalidDecl() && I < N-1) {
395 Decls[I] = Decls[--N];
396 continue;
397 }
398
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000399 // Redeclarations of types via typedef can occur both within a scope
400 // and, through using declarations and directives, across scopes. There is
401 // no ambiguity if they all refer to the same type, so unique based on the
402 // canonical type.
403 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
404 if (!TD->getDeclContext()->isRecord()) {
405 QualType T = SemaRef.Context.getTypeDeclType(TD);
406 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
407 // The type is not unique; pull something off the back and continue
408 // at this index.
409 Decls[I] = Decls[--N];
410 continue;
411 }
412 }
413 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000414
John McCall314be4e2009-11-17 07:50:12 +0000415 if (!Unique.insert(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000416 // If it's not unique, pull something off the back (and
417 // continue at this index).
418 Decls[I] = Decls[--N];
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000419 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000420 }
421
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000422 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000423
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000424 if (isa<UnresolvedUsingValueDecl>(D)) {
425 HasUnresolved = true;
426 } else if (isa<TagDecl>(D)) {
427 if (HasTag)
428 Ambiguous = true;
429 UniqueTagIndex = I;
430 HasTag = true;
431 } else if (isa<FunctionTemplateDecl>(D)) {
432 HasFunction = true;
433 HasFunctionTemplate = true;
434 } else if (isa<FunctionDecl>(D)) {
435 HasFunction = true;
436 } else {
437 if (HasNonFunction)
438 Ambiguous = true;
439 HasNonFunction = true;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000440 }
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000441 I++;
Mike Stump1eb44332009-09-09 15:08:12 +0000442 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000443
John McCallf36e02d2009-10-09 21:13:30 +0000444 // C++ [basic.scope.hiding]p2:
445 // A class name or enumeration name can be hidden by the name of
446 // an object, function, or enumerator declared in the same
447 // scope. If a class or enumeration name and an object, function,
448 // or enumerator are declared in the same scope (in any order)
449 // with the same name, the class or enumeration name is hidden
450 // wherever the object, function, or enumerator name is visible.
451 // But it's still an error if there are distinct tag types found,
452 // even if they're not visible. (ref?)
John McCallfda8e122009-12-03 00:58:24 +0000453 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregor77a1a882010-10-23 16:06:17 +0000454 (HasFunction || HasNonFunction || HasUnresolved)) {
Richard Smith190d1af2013-10-30 01:02:04 +0000455 if (getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
456 getContextForScopeMatching(Decls[UniqueTagIndex ? 0 : N - 1])))
Douglas Gregor77a1a882010-10-23 16:06:17 +0000457 Decls[UniqueTagIndex] = Decls[--N];
458 else
459 Ambiguous = true;
460 }
Anders Carlsson8b50d012009-06-26 03:37:05 +0000461
John McCallf36e02d2009-10-09 21:13:30 +0000462 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000463
John McCallfda8e122009-12-03 00:58:24 +0000464 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000465 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000466
John McCallf36e02d2009-10-09 21:13:30 +0000467 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000468 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000469 else if (HasUnresolved)
470 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000471 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000472 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000473 else
John McCalla24dc2e2009-11-17 02:14:36 +0000474 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000475}
476
John McCall7d384dd2009-11-18 07:57:50 +0000477void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall6b2accb2010-02-10 09:31:12 +0000478 CXXBasePaths::const_paths_iterator I, E;
John McCallf36e02d2009-10-09 21:13:30 +0000479 for (I = P.begin(), E = P.end(); I != E; ++I)
David Blaikie3bc93e32012-12-19 00:45:41 +0000480 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
481 DE = I->Decls.end(); DI != DE; ++DI)
John McCallf36e02d2009-10-09 21:13:30 +0000482 addDecl(*DI);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000483}
484
John McCall7d384dd2009-11-18 07:57:50 +0000485void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000486 Paths = new CXXBasePaths;
487 Paths->swap(P);
488 addDeclsFromBasePaths(*Paths);
489 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000490 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000491}
492
John McCall7d384dd2009-11-18 07:57:50 +0000493void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000494 Paths = new CXXBasePaths;
495 Paths->swap(P);
496 addDeclsFromBasePaths(*Paths);
497 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000498 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000499}
500
Chris Lattner5f9e2722011-07-23 10:55:15 +0000501void LookupResult::print(raw_ostream &Out) {
John McCallf36e02d2009-10-09 21:13:30 +0000502 Out << Decls.size() << " result(s)";
503 if (isAmbiguous()) Out << ", ambiguous";
504 if (Paths) Out << ", base paths present";
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000505
John McCallf36e02d2009-10-09 21:13:30 +0000506 for (iterator I = begin(), E = end(); I != E; ++I) {
507 Out << "\n";
508 (*I)->print(Out, 2);
509 }
510}
511
Douglas Gregor85910982010-02-12 05:48:04 +0000512/// \brief Lookup a builtin function, when name lookup would otherwise
513/// fail.
514static bool LookupBuiltin(Sema &S, LookupResult &R) {
515 Sema::LookupNameKind NameKind = R.getLookupKind();
516
517 // If we didn't find a use of this identifier, and if the identifier
518 // corresponds to a compiler builtin, create the decl object for the builtin
519 // now, injecting it into translation unit scope, and return it.
520 if (NameKind == Sema::LookupOrdinaryName ||
521 NameKind == Sema::LookupRedeclarationWithLinkage) {
522 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
523 if (II) {
Nico Webercac18ad2013-06-20 21:44:55 +0000524 if (S.getLangOpts().CPlusPlus11 && S.getLangOpts().GNUMode &&
525 II == S.getFloat128Identifier()) {
526 // libstdc++4.7's type_traits expects type __float128 to exist, so
527 // insert a dummy type to make that header build in gnu++11 mode.
528 R.addDecl(S.getASTContext().getFloat128StubType());
529 return true;
530 }
531
Douglas Gregor85910982010-02-12 05:48:04 +0000532 // If this is a builtin on this (or all) targets, create the decl.
533 if (unsigned BuiltinID = II->getBuiltinID()) {
534 // In C++, we don't have any predefined library functions like
535 // 'malloc'. Instead, we'll just error.
David Blaikie4e4d0842012-03-11 07:00:24 +0000536 if (S.getLangOpts().CPlusPlus &&
Douglas Gregor85910982010-02-12 05:48:04 +0000537 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
538 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000539
540 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
541 BuiltinID, S.TUScope,
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000542 R.isForRedeclaration(),
543 R.getNameLoc())) {
Douglas Gregor85910982010-02-12 05:48:04 +0000544 R.addDecl(D);
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000545 return true;
546 }
547
548 if (R.isForRedeclaration()) {
549 // If we're redeclaring this function anyway, forget that
550 // this was a builtin at all.
551 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
552 }
553
554 return false;
Douglas Gregor85910982010-02-12 05:48:04 +0000555 }
556 }
557 }
558
559 return false;
560}
561
Douglas Gregor4923aa22010-07-02 20:37:36 +0000562/// \brief Determine whether we can declare a special member function within
563/// the class at this point.
Richard Smithd0adeb62012-11-27 21:20:31 +0000564static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor4923aa22010-07-02 20:37:36 +0000565 // We need to have a definition for the class.
566 if (!Class->getDefinition() || Class->isDependentContext())
567 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000568
Douglas Gregor4923aa22010-07-02 20:37:36 +0000569 // We can't be in the middle of defining the class.
Richard Smithd0adeb62012-11-27 21:20:31 +0000570 return !Class->isBeingDefined();
Douglas Gregor4923aa22010-07-02 20:37:36 +0000571}
572
573void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smithd0adeb62012-11-27 21:20:31 +0000574 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregor22584312010-07-02 23:41:54 +0000575 return;
Douglas Gregor18274032010-07-03 00:47:00 +0000576
577 // If the default constructor has not yet been declared, do so now.
Sean Huntcdee3fe2011-05-11 22:34:38 +0000578 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +0000579 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000580
Douglas Gregor22584312010-07-02 23:41:54 +0000581 // If the copy constructor has not yet been declared, do so now.
Richard Smithe5411b72012-12-01 02:35:44 +0000582 if (Class->needsImplicitCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +0000583 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000584
Douglas Gregora376d102010-07-02 21:50:04 +0000585 // If the copy assignment operator has not yet been declared, do so now.
Richard Smithe5411b72012-12-01 02:35:44 +0000586 if (Class->needsImplicitCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +0000587 DeclareImplicitCopyAssignment(Class);
588
Richard Smith80ad52f2013-01-02 11:42:31 +0000589 if (getLangOpts().CPlusPlus11) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000590 // If the move constructor has not yet been declared, do so now.
591 if (Class->needsImplicitMoveConstructor())
592 DeclareImplicitMoveConstructor(Class); // might not actually do it
593
594 // If the move assignment operator has not yet been declared, do so now.
595 if (Class->needsImplicitMoveAssignment())
596 DeclareImplicitMoveAssignment(Class); // might not actually do it
597 }
598
Douglas Gregor4923aa22010-07-02 20:37:36 +0000599 // If the destructor has not yet been declared, do so now.
Richard Smithe5411b72012-12-01 02:35:44 +0000600 if (Class->needsImplicitDestructor())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000601 DeclareImplicitDestructor(Class);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000602}
603
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000604/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregora376d102010-07-02 21:50:04 +0000605/// special member function.
606static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
607 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000608 case DeclarationName::CXXConstructorName:
Douglas Gregora376d102010-07-02 21:50:04 +0000609 case DeclarationName::CXXDestructorName:
610 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000611
Douglas Gregora376d102010-07-02 21:50:04 +0000612 case DeclarationName::CXXOperatorName:
613 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000614
Douglas Gregora376d102010-07-02 21:50:04 +0000615 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000616 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000617 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000618
Douglas Gregora376d102010-07-02 21:50:04 +0000619 return false;
620}
621
622/// \brief If there are any implicit member functions with the given name
623/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000624static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregora376d102010-07-02 21:50:04 +0000625 DeclarationName Name,
626 const DeclContext *DC) {
627 if (!DC)
628 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000629
Douglas Gregora376d102010-07-02 21:50:04 +0000630 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000631 case DeclarationName::CXXConstructorName:
632 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smithd0adeb62012-11-27 21:20:31 +0000633 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000634 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Sean Huntcdee3fe2011-05-11 22:34:38 +0000635 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000636 S.DeclareImplicitDefaultConstructor(Class);
Richard Smithe5411b72012-12-01 02:35:44 +0000637 if (Record->needsImplicitCopyConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000638 S.DeclareImplicitCopyConstructor(Class);
Richard Smith80ad52f2013-01-02 11:42:31 +0000639 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000640 Record->needsImplicitMoveConstructor())
641 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +0000642 }
Douglas Gregor22584312010-07-02 23:41:54 +0000643 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000644
Douglas Gregora376d102010-07-02 21:50:04 +0000645 case DeclarationName::CXXDestructorName:
646 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smithe5411b72012-12-01 02:35:44 +0000647 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smithd0adeb62012-11-27 21:20:31 +0000648 CanDeclareSpecialMemberFunction(Record))
Douglas Gregora376d102010-07-02 21:50:04 +0000649 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregora376d102010-07-02 21:50:04 +0000650 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000651
Douglas Gregora376d102010-07-02 21:50:04 +0000652 case DeclarationName::CXXOperatorName:
653 if (Name.getCXXOverloadedOperator() != OO_Equal)
654 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000655
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000656 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smithd0adeb62012-11-27 21:20:31 +0000657 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000658 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smithe5411b72012-12-01 02:35:44 +0000659 if (Record->needsImplicitCopyAssignment())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000660 S.DeclareImplicitCopyAssignment(Class);
Richard Smith80ad52f2013-01-02 11:42:31 +0000661 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000662 Record->needsImplicitMoveAssignment())
663 S.DeclareImplicitMoveAssignment(Class);
664 }
665 }
Douglas Gregora376d102010-07-02 21:50:04 +0000666 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000667
Douglas Gregora376d102010-07-02 21:50:04 +0000668 default:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000669 break;
Douglas Gregora376d102010-07-02 21:50:04 +0000670 }
671}
Douglas Gregor4923aa22010-07-02 20:37:36 +0000672
John McCallf36e02d2009-10-09 21:13:30 +0000673// Adds all qualifying matches for a name within a decl context to the
674// given lookup result. Returns true if any matches were found.
Douglas Gregor85910982010-02-12 05:48:04 +0000675static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000676 bool Found = false;
677
Douglas Gregor4923aa22010-07-02 20:37:36 +0000678 // Lazily declare C++ special member functions.
David Blaikie4e4d0842012-03-11 07:00:24 +0000679 if (S.getLangOpts().CPlusPlus)
Douglas Gregora376d102010-07-02 21:50:04 +0000680 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000681
Douglas Gregor4923aa22010-07-02 20:37:36 +0000682 // Perform lookup into this declaration context.
David Blaikie3bc93e32012-12-19 00:45:41 +0000683 DeclContext::lookup_const_result DR = DC->lookup(R.getLookupName());
684 for (DeclContext::lookup_const_iterator I = DR.begin(), E = DR.end(); I != E;
685 ++I) {
John McCall46460a62010-01-20 21:53:11 +0000686 NamedDecl *D = *I;
Douglas Gregor55368912011-12-14 16:03:29 +0000687 if ((D = R.getAcceptableDecl(D))) {
John McCall46460a62010-01-20 21:53:11 +0000688 R.addDecl(D);
Douglas Gregor48026d22010-01-11 18:40:55 +0000689 Found = true;
690 }
691 }
John McCallf36e02d2009-10-09 21:13:30 +0000692
Douglas Gregor85910982010-02-12 05:48:04 +0000693 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
694 return true;
695
Douglas Gregor48026d22010-01-11 18:40:55 +0000696 if (R.getLookupName().getNameKind()
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000697 != DeclarationName::CXXConversionFunctionName ||
698 R.getLookupName().getCXXNameType()->isDependentType() ||
699 !isa<CXXRecordDecl>(DC))
700 return Found;
701
702 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000703 // A specialization of a conversion function template is not found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000704 // name lookup. Instead, any conversion function templates visible in the
705 // context of the use are considered. [...]
706 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCall5e1cdac2011-10-07 06:10:15 +0000707 if (!Record->isCompleteDefinition())
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000708 return Found;
709
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +0000710 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
711 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000712 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
713 if (!ConvTemplate)
714 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000715
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000716 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000717 // add the conversion function template. When we deduce template
718 // arguments for specializations, we'll end up unifying the return
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000719 // type of the new declaration with the type of the function template.
720 if (R.isForRedeclaration()) {
721 R.addDecl(ConvTemplate);
722 Found = true;
723 continue;
724 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000725
Douglas Gregor48026d22010-01-11 18:40:55 +0000726 // C++ [temp.mem]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000727 // [...] For each such operator, if argument deduction succeeds
728 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000729 // name lookup.
730 //
731 // When referencing a conversion function for any purpose other than
732 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000733 // result), perform template argument deduction and place the
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000734 // specialization into the result set. We do this to avoid forcing all
735 // callers to perform special deduction for conversion functions.
Craig Topper93e45992012-09-19 02:26:47 +0000736 TemplateDeductionInfo Info(R.getNameLoc());
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000737 FunctionDecl *Specialization = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000738
739 const FunctionProtoType *ConvProto
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000740 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
741 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3f477a12010-01-12 01:17:50 +0000742
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000743 // Compute the type of the function that we would expect the conversion
744 // function to have, if it were to match the name given.
745 // FIXME: Calling convention!
John McCalle23cf432010-12-14 08:05:40 +0000746 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
Reid Kleckneref072032013-08-27 23:08:25 +0000747 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
Sebastian Redl8b5b4092011-03-06 10:52:04 +0000748 EPI.ExceptionSpecType = EST_None;
John McCalle23cf432010-12-14 08:05:40 +0000749 EPI.NumExceptions = 0;
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000750 QualType ExpectedType
751 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
Dmitri Gribenko55431692013-05-05 00:41:58 +0000752 None, EPI);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000753
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000754 // Perform template argument deduction against the type that we would
755 // expect the function to have.
756 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
757 Specialization, Info)
758 == Sema::TDK_Success) {
759 R.addDecl(Specialization);
760 Found = true;
Douglas Gregor48026d22010-01-11 18:40:55 +0000761 }
762 }
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000763
John McCallf36e02d2009-10-09 21:13:30 +0000764 return Found;
765}
766
John McCalld7be78a2009-11-10 07:01:13 +0000767// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000768static bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000769CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregor85910982010-02-12 05:48:04 +0000770 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000771
772 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
773
John McCalld7be78a2009-11-10 07:01:13 +0000774 // Perform direct name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +0000775 bool Found = LookupDirect(S, R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000776
John McCalld7be78a2009-11-10 07:01:13 +0000777 // Perform direct name lookup into the namespaces nominated by the
778 // using directives whose common ancestor is this namespace.
779 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
780 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000781
John McCalld7be78a2009-11-10 07:01:13 +0000782 for (; UI != UEnd; ++UI)
Douglas Gregor85910982010-02-12 05:48:04 +0000783 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000784 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000785
786 R.resolveKind();
787
788 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000789}
790
791static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Ted Kremenekf0d58612013-10-08 17:08:03 +0000792 if (DeclContext *Ctx = S->getEntity())
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000793 return Ctx->isFileContext();
794 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000795}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000796
Douglas Gregor711be1e2010-03-15 14:33:29 +0000797// Find the next outer declaration context from this scope. This
798// routine actually returns the semantic outer context, which may
799// differ from the lexical context (encoded directly in the Scope
800// stack) when we are parsing a member of a class template. In this
801// case, the second element of the pair will be true, to indicate that
802// name lookup should continue searching in this semantic context when
803// it leaves the current template parameter scope.
804static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
Ted Kremenekf0d58612013-10-08 17:08:03 +0000805 DeclContext *DC = S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +0000806 DeclContext *Lexical = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000807 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor711be1e2010-03-15 14:33:29 +0000808 OuterS = OuterS->getParent()) {
809 if (OuterS->getEntity()) {
Ted Kremenekf0d58612013-10-08 17:08:03 +0000810 Lexical = OuterS->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +0000811 break;
812 }
813 }
814
815 // C++ [temp.local]p8:
816 // In the definition of a member of a class template that appears
817 // outside of the namespace containing the class template
818 // definition, the name of a template-parameter hides the name of
819 // a member of this namespace.
820 //
821 // Example:
822 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000823 // namespace N {
824 // class C { };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000825 //
826 // template<class T> class B {
827 // void f(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000828 // };
Douglas Gregor711be1e2010-03-15 14:33:29 +0000829 // }
830 //
831 // template<class C> void N::B<C>::f(C) {
832 // C b; // C is the template parameter, not N::C
833 // }
834 //
835 // In this example, the lexical context we return is the
836 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000837 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor711be1e2010-03-15 14:33:29 +0000838 !S->getParent()->isTemplateParamScope())
839 return std::make_pair(Lexical, false);
840
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000841 // Find the outermost template parameter scope.
Douglas Gregor711be1e2010-03-15 14:33:29 +0000842 // For the example, this is the scope for the template parameters of
843 // template<class C>.
844 Scope *OutermostTemplateScope = S->getParent();
845 while (OutermostTemplateScope->getParent() &&
846 OutermostTemplateScope->getParent()->isTemplateParamScope())
847 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000848
Douglas Gregor711be1e2010-03-15 14:33:29 +0000849 // Find the namespace context in which the original scope occurs. In
850 // the example, this is namespace N.
851 DeclContext *Semantic = DC;
852 while (!Semantic->isFileContext())
853 Semantic = Semantic->getParent();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000854
Douglas Gregor711be1e2010-03-15 14:33:29 +0000855 // Find the declaration context just outside of the template
856 // parameter scope. This is the context in which the template is
857 // being lexically declaration (a namespace context). In the
858 // example, this is the global scope.
859 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
860 Lexical->Encloses(Semantic))
861 return std::make_pair(Semantic, true);
862
863 return std::make_pair(Lexical, false);
Douglas Gregore942bbe2009-09-10 16:57:35 +0000864}
865
Richard Smitha41c97a2013-09-20 01:15:31 +0000866namespace {
867/// An RAII object to specify that we want to find block scope extern
868/// declarations.
869struct FindLocalExternScope {
870 FindLocalExternScope(LookupResult &R)
871 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
872 Decl::IDNS_LocalExtern) {
873 R.setFindLocalExtern(R.getIdentifierNamespace() & Decl::IDNS_Ordinary);
874 }
875 void restore() {
876 R.setFindLocalExtern(OldFindLocalExtern);
877 }
878 ~FindLocalExternScope() {
879 restore();
880 }
881 LookupResult &R;
882 bool OldFindLocalExtern;
883};
884}
885
John McCalla24dc2e2009-11-17 02:14:36 +0000886bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000887 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000888
889 DeclarationName Name = R.getLookupName();
Richard Smithdd9459f2013-08-13 18:18:50 +0000890 Sema::LookupNameKind NameKind = R.getLookupKind();
John McCalla24dc2e2009-11-17 02:14:36 +0000891
Douglas Gregora376d102010-07-02 21:50:04 +0000892 // If this is the name of an implicitly-declared special member function,
893 // go through the scope stack to implicitly declare
894 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
895 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
Ted Kremenekf0d58612013-10-08 17:08:03 +0000896 if (DeclContext *DC = PreS->getEntity())
Douglas Gregora376d102010-07-02 21:50:04 +0000897 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
898 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000899
Douglas Gregora376d102010-07-02 21:50:04 +0000900 // Implicitly declare member functions with the name we're looking for, if in
901 // fact we are in a scope where it matters.
902
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000903 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000904 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000905 I = IdResolver.begin(Name),
906 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000907
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000908 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000909 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000910 // ...During unqualified name lookup (3.4.1), the names appear as if
911 // they were declared in the nearest enclosing namespace which contains
912 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000913 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000914 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000915 //
916 // For example:
917 // namespace A { int i; }
918 // void foo() {
919 // int i;
920 // {
921 // using namespace A;
922 // ++i; // finds local 'i', A::i appears at global scope
923 // }
924 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000925 //
Douglas Gregor44b2ea92013-04-08 23:11:25 +0000926 UnqualUsingDirectiveSet UDirs;
927 bool VisitedUsingDirectives = false;
Richard Smithdd9459f2013-08-13 18:18:50 +0000928 bool LeftStartingScope = false;
Douglas Gregor711be1e2010-03-15 14:33:29 +0000929 DeclContext *OutsideOfTemplateParamDC = 0;
Richard Smitha41c97a2013-09-20 01:15:31 +0000930
931 // When performing a scope lookup, we want to find local extern decls.
932 FindLocalExternScope FindLocals(R);
933
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000934 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Ted Kremenekf0d58612013-10-08 17:08:03 +0000935 DeclContext *Ctx = S->getEntity();
Douglas Gregord2235f62010-05-20 20:58:56 +0000936
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000937 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000938 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000939 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor55368912011-12-14 16:03:29 +0000940 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Richard Smithdd9459f2013-08-13 18:18:50 +0000941 if (NameKind == LookupRedeclarationWithLinkage) {
942 // Determine whether this (or a previous) declaration is
943 // out-of-scope.
944 if (!LeftStartingScope && !Initial->isDeclScope(*I))
945 LeftStartingScope = true;
946
947 // If we found something outside of our starting scope that
Richard Smith49ef4812013-10-16 21:12:00 +0000948 // does not have linkage, skip it. If it's a template parameter,
949 // we still find it, so we can diagnose the invalid redeclaration.
950 if (LeftStartingScope && !((*I)->hasLinkage()) &&
951 !(*I)->isTemplateParameter()) {
Richard Smithdd9459f2013-08-13 18:18:50 +0000952 R.setShadowed();
953 continue;
954 }
955 }
956
John McCallf36e02d2009-10-09 21:13:30 +0000957 Found = true;
Douglas Gregor55368912011-12-14 16:03:29 +0000958 R.addDecl(ND);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000959 }
960 }
John McCallf36e02d2009-10-09 21:13:30 +0000961 if (Found) {
962 R.resolveKind();
Douglas Gregord2235f62010-05-20 20:58:56 +0000963 if (S->isClassScope())
964 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
965 R.setNamingClass(Record);
John McCallf36e02d2009-10-09 21:13:30 +0000966 return true;
967 }
968
Richard Smithdd9459f2013-08-13 18:18:50 +0000969 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
Richard Smith4e9686b2013-08-09 04:35:01 +0000970 // C++11 [class.friend]p11:
971 // If a friend declaration appears in a local class and the name
972 // specified is an unqualified name, a prior declaration is
973 // looked up without considering scopes that are outside the
974 // innermost enclosing non-class scope.
975 return false;
976 }
977
Douglas Gregor711be1e2010-03-15 14:33:29 +0000978 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
979 S->getParent() && !S->getParent()->isTemplateParamScope()) {
980 // We've just searched the last template parameter scope and
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +0000981 // found nothing, so look into the contexts between the
Douglas Gregor711be1e2010-03-15 14:33:29 +0000982 // lexical and semantic declaration contexts returned by
983 // findOuterContext(). This implements the name lookup behavior
984 // of C++ [temp.local]p8.
985 Ctx = OutsideOfTemplateParamDC;
986 OutsideOfTemplateParamDC = 0;
987 }
988
989 if (Ctx) {
990 DeclContext *OuterCtx;
991 bool SearchAfterTemplateScope;
992 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
993 if (SearchAfterTemplateScope)
994 OutsideOfTemplateParamDC = OuterCtx;
995
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000996 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-02-19 16:08:35 +0000997 // We do not directly look into transparent contexts, since
998 // those entities will be found in the nearest enclosing
999 // non-transparent context.
1000 if (Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +00001001 continue;
Douglas Gregor36262b82010-02-19 16:08:35 +00001002
1003 // We do not look directly into function or method contexts,
1004 // since all of the local variables and parameters of the
1005 // function/method are present within the Scope.
1006 if (Ctx->isFunctionOrMethod()) {
1007 // If we have an Objective-C instance method, look for ivars
1008 // in the corresponding interface.
1009 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
1010 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1011 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1012 ObjCInterfaceDecl *ClassDeclared;
1013 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001014 Name.getAsIdentifierInfo(),
Douglas Gregor36262b82010-02-19 16:08:35 +00001015 ClassDeclared)) {
Douglas Gregor55368912011-12-14 16:03:29 +00001016 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1017 R.addDecl(ND);
Douglas Gregor36262b82010-02-19 16:08:35 +00001018 R.resolveKind();
1019 return true;
1020 }
1021 }
1022 }
1023 }
1024
1025 continue;
1026 }
1027
Douglas Gregor6bed88e2013-03-27 12:51:49 +00001028 // If this is a file context, we need to perform unqualified name
1029 // lookup considering using directives.
1030 if (Ctx->isFileContext()) {
Douglas Gregor44b2ea92013-04-08 23:11:25 +00001031 // If we haven't handled using directives yet, do so now.
1032 if (!VisitedUsingDirectives) {
1033 // Add using directives from this context up to the top level.
Douglas Gregor34366202013-04-09 01:49:26 +00001034 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1035 if (UCtx->isTransparentContext())
1036 continue;
1037
Douglas Gregor44b2ea92013-04-08 23:11:25 +00001038 UDirs.visit(UCtx, UCtx);
Douglas Gregor34366202013-04-09 01:49:26 +00001039 }
Douglas Gregor44b2ea92013-04-08 23:11:25 +00001040
1041 // Find the innermost file scope, so we can add using directives
1042 // from local scopes.
1043 Scope *InnermostFileScope = S;
1044 while (InnermostFileScope &&
1045 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1046 InnermostFileScope = InnermostFileScope->getParent();
1047 UDirs.visitScopeChain(Initial, InnermostFileScope);
1048
1049 UDirs.done();
1050
1051 VisitedUsingDirectives = true;
1052 }
Douglas Gregor6bed88e2013-03-27 12:51:49 +00001053
1054 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1055 R.resolveKind();
1056 return true;
1057 }
1058
1059 continue;
1060 }
1061
Douglas Gregore942bbe2009-09-10 16:57:35 +00001062 // Perform qualified name lookup into this context.
1063 // FIXME: In some cases, we know that every name that could be found by
1064 // this qualified name lookup will also be on the identifier chain. For
1065 // example, inside a class without any base classes, we never need to
1066 // perform qualified lookup because all of the members are on top of the
1067 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001068 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +00001069 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +00001070 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001071 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001072 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001073
John McCalld7be78a2009-11-10 07:01:13 +00001074 // Stop if we ran out of scopes.
1075 // FIXME: This really, really shouldn't be happening.
1076 if (!S) return false;
1077
Argyrios Kyrtzidis78f59112010-10-29 16:12:50 +00001078 // If we are looking for members, no need to look into global/namespace scope.
Richard Smithdd9459f2013-08-13 18:18:50 +00001079 if (NameKind == LookupMemberName)
Argyrios Kyrtzidis78f59112010-10-29 16:12:50 +00001080 return false;
1081
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001082 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001083 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +00001084 //
Mike Stump390b4cc2009-05-16 07:39:55 +00001085 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1086 // don't build it for each lookup!
Douglas Gregor44b2ea92013-04-08 23:11:25 +00001087 if (!VisitedUsingDirectives) {
1088 UDirs.visitScopeChain(Initial, S);
1089 UDirs.done();
1090 }
Richard Smitha41c97a2013-09-20 01:15:31 +00001091
1092 // If we're not performing redeclaration lookup, do not look for local
1093 // extern declarations outside of a function scope.
1094 if (!R.isForRedeclaration())
1095 FindLocals.restore();
1096
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001097 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001098 // Unqualified name lookup in C++ requires looking into scopes
1099 // that aren't strictly lexical, and therefore we walk through the
1100 // context as well as walking through the scopes.
1101 for (; S; S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001102 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +00001103 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +00001104 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor55368912011-12-14 16:03:29 +00001105 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001106 // We found something. Look for anything else in our scope
1107 // with this same name and in an acceptable identifier
1108 // namespace, so that we can construct an overload set if we
1109 // need to.
John McCallf36e02d2009-10-09 21:13:30 +00001110 Found = true;
Douglas Gregor55368912011-12-14 16:03:29 +00001111 R.addDecl(ND);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001112 }
1113 }
1114
Douglas Gregor00b4b032010-05-14 04:53:42 +00001115 if (Found && S->isTemplateParamScope()) {
John McCallf36e02d2009-10-09 21:13:30 +00001116 R.resolveKind();
1117 return true;
1118 }
1119
Ted Kremenekf0d58612013-10-08 17:08:03 +00001120 DeclContext *Ctx = S->getEntity();
Douglas Gregor00b4b032010-05-14 04:53:42 +00001121 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1122 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1123 // We've just searched the last template parameter scope and
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00001124 // found nothing, so look into the contexts between the
Douglas Gregor00b4b032010-05-14 04:53:42 +00001125 // lexical and semantic declaration contexts returned by
1126 // findOuterContext(). This implements the name lookup behavior
1127 // of C++ [temp.local]p8.
1128 Ctx = OutsideOfTemplateParamDC;
1129 OutsideOfTemplateParamDC = 0;
1130 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001131
Douglas Gregor00b4b032010-05-14 04:53:42 +00001132 if (Ctx) {
1133 DeclContext *OuterCtx;
1134 bool SearchAfterTemplateScope;
1135 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1136 if (SearchAfterTemplateScope)
1137 OutsideOfTemplateParamDC = OuterCtx;
1138
1139 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1140 // We do not directly look into transparent contexts, since
1141 // those entities will be found in the nearest enclosing
1142 // non-transparent context.
1143 if (Ctx->isTransparentContext())
1144 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001145
Douglas Gregor00b4b032010-05-14 04:53:42 +00001146 // If we have a context, and it's not a context stashed in the
1147 // template parameter scope for an out-of-line definition, also
1148 // look into that context.
1149 if (!(Found && S && S->isTemplateParamScope())) {
1150 assert(Ctx->isFileContext() &&
1151 "We should have been looking only at file context here already.");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001152
Douglas Gregor00b4b032010-05-14 04:53:42 +00001153 // Look into context considering using-directives.
1154 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1155 Found = true;
1156 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001157
Douglas Gregor00b4b032010-05-14 04:53:42 +00001158 if (Found) {
1159 R.resolveKind();
1160 return true;
1161 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001162
Douglas Gregor00b4b032010-05-14 04:53:42 +00001163 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1164 return false;
1165 }
1166 }
1167
Douglas Gregor1df0ee92010-02-05 07:07:10 +00001168 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +00001169 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001170 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001171
John McCallf36e02d2009-10-09 21:13:30 +00001172 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001173}
1174
Richard Smithb7751002013-07-25 23:08:39 +00001175/// \brief Find the declaration that a class temploid member specialization was
1176/// instantiated from, or the member itself if it is an explicit specialization.
1177static Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) {
1178 return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom();
1179}
1180
1181/// \brief Find the module in which the given declaration was defined.
1182static Module *getDefiningModule(Decl *Entity) {
1183 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1184 // If this function was instantiated from a template, the defining module is
1185 // the module containing the pattern.
1186 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1187 Entity = Pattern;
1188 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
1189 // If it's a class template specialization, find the template or partial
1190 // specialization from which it was instantiated.
1191 if (ClassTemplateSpecializationDecl *SpecRD =
1192 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
1193 llvm::PointerUnion<ClassTemplateDecl*,
1194 ClassTemplatePartialSpecializationDecl*> From =
1195 SpecRD->getInstantiatedFrom();
1196 if (ClassTemplateDecl *FromTemplate = From.dyn_cast<ClassTemplateDecl*>())
1197 Entity = FromTemplate->getTemplatedDecl();
1198 else if (From)
1199 Entity = From.get<ClassTemplatePartialSpecializationDecl*>();
1200 // Otherwise, it's an explicit specialization.
1201 } else if (MemberSpecializationInfo *MSInfo =
1202 RD->getMemberSpecializationInfo())
1203 Entity = getInstantiatedFrom(RD, MSInfo);
1204 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1205 if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo())
1206 Entity = getInstantiatedFrom(ED, MSInfo);
1207 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1208 // FIXME: Map from variable template specializations back to the template.
1209 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo())
1210 Entity = getInstantiatedFrom(VD, MSInfo);
1211 }
1212
1213 // Walk up to the containing context. That might also have been instantiated
1214 // from a template.
1215 DeclContext *Context = Entity->getDeclContext();
1216 if (Context->isFileContext())
1217 return Entity->getOwningModule();
1218 return getDefiningModule(cast<Decl>(Context));
1219}
1220
1221llvm::DenseSet<Module*> &Sema::getLookupModules() {
1222 unsigned N = ActiveTemplateInstantiations.size();
1223 for (unsigned I = ActiveTemplateInstantiationLookupModules.size();
1224 I != N; ++I) {
1225 Module *M = getDefiningModule(ActiveTemplateInstantiations[I].Entity);
1226 if (M && !LookupModulesCache.insert(M).second)
1227 M = 0;
1228 ActiveTemplateInstantiationLookupModules.push_back(M);
1229 }
1230 return LookupModulesCache;
1231}
1232
1233/// \brief Determine whether a declaration is visible to name lookup.
1234///
1235/// This routine determines whether the declaration D is visible in the current
1236/// lookup context, taking into account the current template instantiation
1237/// stack. During template instantiation, a declaration is visible if it is
1238/// visible from a module containing any entity on the template instantiation
1239/// path (by instantiating a template, you allow it to see the declarations that
1240/// your module can see, including those later on in your module).
1241bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
1242 assert(D->isHidden() && !SemaRef.ActiveTemplateInstantiations.empty() &&
1243 "should not call this: not in slow case");
1244 Module *DeclModule = D->getOwningModule();
1245 assert(DeclModule && "hidden decl not from a module");
1246
1247 // Find the extra places where we need to look.
1248 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
1249 if (LookupModules.empty())
1250 return false;
1251
1252 // If our lookup set contains the decl's module, it's visible.
1253 if (LookupModules.count(DeclModule))
1254 return true;
1255
1256 // If the declaration isn't exported, it's not visible in any other module.
1257 if (D->isModulePrivate())
1258 return false;
1259
1260 // Check whether DeclModule is transitively exported to an import of
1261 // the lookup set.
1262 for (llvm::DenseSet<Module *>::iterator I = LookupModules.begin(),
1263 E = LookupModules.end();
1264 I != E; ++I)
1265 if ((*I)->isModuleVisible(DeclModule))
1266 return true;
1267 return false;
1268}
1269
Douglas Gregor55368912011-12-14 16:03:29 +00001270/// \brief Retrieve the visible declaration corresponding to D, if any.
1271///
1272/// This routine determines whether the declaration D is visible in the current
1273/// module, with the current imports. If not, it checks whether any
1274/// redeclaration of D is visible, and if so, returns that declaration.
Richard Smithb7751002013-07-25 23:08:39 +00001275///
Douglas Gregor55368912011-12-14 16:03:29 +00001276/// \returns D, or a visible previous declaration of D, whichever is more recent
1277/// and visible. If no declaration of D is visible, returns null.
Richard Smithd67679d2013-08-20 20:35:18 +00001278static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
1279 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
Richard Smithb7751002013-07-25 23:08:39 +00001280
Douglas Gregor0782ef22012-01-06 22:05:37 +00001281 for (Decl::redecl_iterator RD = D->redecls_begin(), RDEnd = D->redecls_end();
1282 RD != RDEnd; ++RD) {
David Blaikie581deb32012-06-06 20:45:41 +00001283 if (NamedDecl *ND = dyn_cast<NamedDecl>(*RD)) {
Richard Smithd67679d2013-08-20 20:35:18 +00001284 if (LookupResult::isVisible(SemaRef, ND))
Douglas Gregor0782ef22012-01-06 22:05:37 +00001285 return ND;
1286 }
Douglas Gregor55368912011-12-14 16:03:29 +00001287 }
Richard Smithb7751002013-07-25 23:08:39 +00001288
Douglas Gregor55368912011-12-14 16:03:29 +00001289 return 0;
1290}
1291
Richard Smithd67679d2013-08-20 20:35:18 +00001292NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
1293 return findAcceptableDecl(SemaRef, D);
1294}
1295
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001296/// @brief Perform unqualified name lookup starting from a given
1297/// scope.
1298///
1299/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1300/// used to find names within the current scope. For example, 'x' in
1301/// @code
1302/// int x;
1303/// int f() {
1304/// return x; // unqualified name look finds 'x' in the global scope
1305/// }
1306/// @endcode
1307///
1308/// Different lookup criteria can find different names. For example, a
1309/// particular scope can have both a struct and a function of the same
1310/// name, and each can be found by certain lookup criteria. For more
1311/// information about lookup criteria, see the documentation for the
1312/// class LookupCriteria.
1313///
1314/// @param S The scope from which unqualified name lookup will
1315/// begin. If the lookup criteria permits, name lookup may also search
1316/// in the parent scopes.
1317///
James Dennett8da16872012-06-22 10:32:46 +00001318/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1319/// look up and the lookup kind), and is updated with the results of lookup
1320/// including zero or more declarations and possibly additional information
1321/// used to diagnose ambiguities.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001322///
James Dennett8da16872012-06-22 10:32:46 +00001323/// @returns \c true if lookup succeeded and false otherwise.
John McCalla24dc2e2009-11-17 02:14:36 +00001324bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1325 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +00001326 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001327
John McCalla24dc2e2009-11-17 02:14:36 +00001328 LookupNameKind NameKind = R.getLookupKind();
1329
David Blaikie4e4d0842012-03-11 07:00:24 +00001330 if (!getLangOpts().CPlusPlus) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001331 // Unqualified name lookup in C/Objective-C is purely lexical, so
1332 // search in the declarations attached to the name.
John McCall1d7c5282009-12-18 10:40:03 +00001333 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001334 // Find the nearest non-transparent declaration scope.
1335 while (!(S->getFlags() & Scope::DeclScope) ||
Ted Kremenekf0d58612013-10-08 17:08:03 +00001336 (S->getEntity() && S->getEntity()->isTransparentContext()))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001337 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001338 }
1339
Richard Smitha41c97a2013-09-20 01:15:31 +00001340 // When performing a scope lookup, we want to find local extern decls.
1341 FindLocalExternScope FindLocals(R);
1342
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001343 // Scan up the scope chain looking for a decl that matches this
1344 // identifier that is in the appropriate namespace. This search
1345 // should not take long, as shadowing of names is uncommon, and
1346 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001347 bool LeftStartingScope = false;
1348
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001349 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +00001350 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001351 I != IEnd; ++I)
Richard Smithb7751002013-07-25 23:08:39 +00001352 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001353 if (NameKind == LookupRedeclarationWithLinkage) {
1354 // Determine whether this (or a previous) declaration is
1355 // out-of-scope.
John McCalld226f652010-08-21 09:40:31 +00001356 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001357 LeftStartingScope = true;
1358
1359 // If we found something outside of our starting scope that
1360 // does not have linkage, skip it.
Richard Smithdd9459f2013-08-13 18:18:50 +00001361 if (LeftStartingScope && !((*I)->hasLinkage())) {
1362 R.setShadowed();
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001363 continue;
Richard Smithdd9459f2013-08-13 18:18:50 +00001364 }
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001365 }
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001366 else if (NameKind == LookupObjCImplicitSelfParam &&
1367 !isa<ImplicitParamDecl>(*I))
1368 continue;
Richard Smithb7751002013-07-25 23:08:39 +00001369
Douglas Gregor55368912011-12-14 16:03:29 +00001370 R.addDecl(D);
John McCallf36e02d2009-10-09 21:13:30 +00001371
Douglas Gregor7a537402012-01-03 23:26:26 +00001372 // Check whether there are any other declarations with the same name
1373 // and in the same scope.
Douglas Gregorda795b42012-01-04 16:44:10 +00001374 if (I != IEnd) {
Douglas Gregor117c4562012-01-13 23:06:53 +00001375 // Find the scope in which this declaration was declared (if it
1376 // actually exists in a Scope).
1377 while (S && !S->isDeclScope(D))
1378 S = S->getParent();
1379
1380 // If the scope containing the declaration is the translation unit,
1381 // then we'll need to perform our checks based on the matching
1382 // DeclContexts rather than matching scopes.
1383 if (S && isNamespaceOrTranslationUnitScope(S))
1384 S = 0;
1385
1386 // Compute the DeclContext, if we need it.
1387 DeclContext *DC = 0;
1388 if (!S)
1389 DC = (*I)->getDeclContext()->getRedeclContext();
1390
Douglas Gregorda795b42012-01-04 16:44:10 +00001391 IdentifierResolver::iterator LastI = I;
1392 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor117c4562012-01-13 23:06:53 +00001393 if (S) {
1394 // Match based on scope.
1395 if (!S->isDeclScope(*LastI))
1396 break;
1397 } else {
1398 // Match based on DeclContext.
1399 DeclContext *LastDC
1400 = (*LastI)->getDeclContext()->getRedeclContext();
1401 if (!LastDC->Equals(DC))
1402 break;
1403 }
Richard Smithb7751002013-07-25 23:08:39 +00001404
1405 // If the declaration is in the right namespace and visible, add it.
1406 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1407 R.addDecl(LastD);
Douglas Gregorda795b42012-01-04 16:44:10 +00001408 }
Douglas Gregorf9201e02009-02-11 23:02:49 +00001409
Douglas Gregorda795b42012-01-04 16:44:10 +00001410 R.resolveKind();
Douglas Gregorf9201e02009-02-11 23:02:49 +00001411 }
Richard Smitha41c97a2013-09-20 01:15:31 +00001412
John McCallf36e02d2009-10-09 21:13:30 +00001413 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +00001414 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001415 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001416 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +00001417 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +00001418 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001419 }
1420
1421 // If we didn't find a use of this identifier, and if the identifier
1422 // corresponds to a compiler builtin, create the decl object for the builtin
1423 // now, injecting it into translation unit scope, and return it.
Axel Naumann42151d52011-04-13 13:19:46 +00001424 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1425 return true;
Douglas Gregor3e41d602009-02-13 23:20:09 +00001426
Axel Naumannf8291a12011-02-24 16:47:47 +00001427 // If we didn't find a use of this identifier, the ExternalSource
1428 // may be able to handle the situation.
1429 // Note: some lookup failures are expected!
1430 // See e.g. R.isForRedeclaration().
1431 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001432}
1433
John McCall6e247262009-10-10 05:48:19 +00001434/// @brief Perform qualified name lookup in the namespaces nominated by
1435/// using directives by the given context.
1436///
1437/// C++98 [namespace.qual]p2:
James Dennett7ba75922012-06-19 21:05:49 +00001438/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6e247262009-10-10 05:48:19 +00001439/// (where X is the global namespace), let S be the set of all
1440/// declarations of m in X and in the transitive closure of all
1441/// namespaces nominated by using-directives in X and its used
1442/// namespaces, except that using-directives are ignored in any
1443/// namespace, including X, directly containing one or more
1444/// declarations of m. No namespace is searched more than once in
1445/// the lookup of a name. If S is the empty set, the program is
1446/// ill-formed. Otherwise, if S has exactly one member, or if the
1447/// context of the reference is a using-declaration
1448/// (namespace.udecl), S is the required set of declarations of
1449/// m. Otherwise if the use of m is not one that allows a unique
1450/// declaration to be chosen from S, the program is ill-formed.
James Dennett7ba75922012-06-19 21:05:49 +00001451///
John McCall6e247262009-10-10 05:48:19 +00001452/// C++98 [namespace.qual]p5:
1453/// During the lookup of a qualified namespace member name, if the
1454/// lookup finds more than one declaration of the member, and if one
1455/// declaration introduces a class name or enumeration name and the
1456/// other declarations either introduce the same object, the same
1457/// enumerator or a set of functions, the non-type name hides the
1458/// class or enumeration name if and only if the declarations are
1459/// from the same namespace; otherwise (the declarations are from
1460/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +00001461static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +00001462 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +00001463 assert(StartDC->isFileContext() && "start context is not a file context");
1464
1465 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1466 DeclContext::udir_iterator E = StartDC->using_directives_end();
1467
1468 if (I == E) return false;
1469
1470 // We have at least added all these contexts to the queue.
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001471 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6e247262009-10-10 05:48:19 +00001472 Visited.insert(StartDC);
1473
1474 // We have not yet looked into these namespaces, much less added
1475 // their "using-children" to the queue.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001476 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6e247262009-10-10 05:48:19 +00001477
1478 // We have already looked into the initial namespace; seed the queue
1479 // with its using-children.
1480 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001481 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001482 if (Visited.insert(ND))
John McCall6e247262009-10-10 05:48:19 +00001483 Queue.push_back(ND);
1484 }
1485
1486 // The easiest way to implement the restriction in [namespace.qual]p5
1487 // is to check whether any of the individual results found a tag
1488 // and, if so, to declare an ambiguity if the final result is not
1489 // a tag.
1490 bool FoundTag = false;
1491 bool FoundNonTag = false;
1492
John McCall7d384dd2009-11-18 07:57:50 +00001493 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001494
1495 bool Found = false;
1496 while (!Queue.empty()) {
Robert Wilhelm344472e2013-08-23 16:11:15 +00001497 NamespaceDecl *ND = Queue.pop_back_val();
John McCall6e247262009-10-10 05:48:19 +00001498
1499 // We go through some convolutions here to avoid copying results
1500 // between LookupResults.
1501 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001502 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001503 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001504
1505 if (FoundDirect) {
1506 // First do any local hiding.
1507 DirectR.resolveKind();
1508
1509 // If the local result is a tag, remember that.
1510 if (DirectR.isSingleTagDecl())
1511 FoundTag = true;
1512 else
1513 FoundNonTag = true;
1514
1515 // Append the local results to the total results if necessary.
1516 if (UseLocal) {
1517 R.addAllDecls(LocalR);
1518 LocalR.clear();
1519 }
1520 }
1521
1522 // If we find names in this namespace, ignore its using directives.
1523 if (FoundDirect) {
1524 Found = true;
1525 continue;
1526 }
1527
1528 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1529 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00001530 if (Visited.insert(Nom))
John McCall6e247262009-10-10 05:48:19 +00001531 Queue.push_back(Nom);
1532 }
1533 }
1534
1535 if (Found) {
1536 if (FoundTag && FoundNonTag)
1537 R.setAmbiguousQualifiedTagHiding();
1538 else
1539 R.resolveKind();
1540 }
1541
1542 return Found;
1543}
1544
Douglas Gregor8071e422010-08-15 06:18:01 +00001545/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001546static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor8071e422010-08-15 06:18:01 +00001547 CXXBasePath &Path,
1548 void *Name) {
1549 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001550
Douglas Gregor8071e422010-08-15 06:18:01 +00001551 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1552 Path.Decls = BaseRecord->lookup(N);
David Blaikie3bc93e32012-12-19 00:45:41 +00001553 return !Path.Decls.empty();
Douglas Gregor8071e422010-08-15 06:18:01 +00001554}
1555
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001556/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001557/// static members, nested types, and enumerators.
1558template<typename InputIterator>
1559static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1560 Decl *D = (*First)->getUnderlyingDecl();
1561 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1562 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001563
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001564 if (isa<CXXMethodDecl>(D)) {
1565 // Determine whether all of the methods are static.
1566 bool AllMethodsAreStatic = true;
1567 for(; First != Last; ++First) {
1568 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001569
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001570 if (!isa<CXXMethodDecl>(D)) {
1571 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1572 break;
1573 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001574
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001575 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1576 AllMethodsAreStatic = false;
1577 break;
1578 }
1579 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001580
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001581 if (AllMethodsAreStatic)
1582 return true;
1583 }
1584
1585 return false;
1586}
1587
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001588/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001589///
1590/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1591/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001592/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001593///
1594/// Different lookup criteria can find different names. For example, a
1595/// particular scope can have both a struct and a function of the same
1596/// name, and each can be found by certain lookup criteria. For more
1597/// information about lookup criteria, see the documentation for the
1598/// class LookupCriteria.
1599///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001600/// \param R captures both the lookup criteria and any lookup results found.
1601///
1602/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001603/// search. If the lookup criteria permits, name lookup may also search
1604/// in the parent contexts or (for C++ classes) base classes.
1605///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001606/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001607/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001608///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001609/// \returns true if lookup succeeded, false if it failed.
1610bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1611 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001612 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001613
John McCalla24dc2e2009-11-17 02:14:36 +00001614 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001615 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001616
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001617 // Make sure that the declaration context is complete.
1618 assert((!isa<TagDecl>(LookupCtx) ||
1619 LookupCtx->isDependentContext() ||
John McCall5e1cdac2011-10-07 06:10:15 +00001620 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith1af83c42012-03-23 03:33:32 +00001621 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001622 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001623
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001624 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001625 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001626 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001627 if (isa<CXXRecordDecl>(LookupCtx))
1628 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001629 return true;
1630 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001631
John McCall6e247262009-10-10 05:48:19 +00001632 // Don't descend into implied contexts for redeclarations.
1633 // C++98 [namespace.qual]p6:
1634 // In a declaration for a namespace member in which the
1635 // declarator-id is a qualified-id, given that the qualified-id
1636 // for the namespace member has the form
1637 // nested-name-specifier unqualified-id
1638 // the unqualified-id shall name a member of the namespace
1639 // designated by the nested-name-specifier.
1640 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001641 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001642 return false;
1643
John McCalla24dc2e2009-11-17 02:14:36 +00001644 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001645 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001646 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001647
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001648 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001649 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001650 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor025291b2010-07-01 00:21:21 +00001651 if (!LookupRec || !LookupRec->getDefinition())
John McCallf36e02d2009-10-09 21:13:30 +00001652 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001653
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001654 // If we're performing qualified name lookup into a dependent class,
1655 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001656 // dependent base classes, then we either have to delay lookup until
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001657 // template instantiation time (at which point all bases will be available)
1658 // or we have to fail.
1659 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1660 LookupRec->hasAnyDependentBases()) {
1661 R.setNotFoundInCurrentInstantiation();
1662 return false;
1663 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001664
Douglas Gregor7176fff2009-01-15 00:26:24 +00001665 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001666 CXXBasePaths Paths;
1667 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001668
1669 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001670 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001671 switch (R.getLookupKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001672 case LookupObjCImplicitSelfParam:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001673 case LookupOrdinaryName:
1674 case LookupMemberName:
1675 case LookupRedeclarationWithLinkage:
Richard Smith4e9686b2013-08-09 04:35:01 +00001676 case LookupLocalFriendName:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001677 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1678 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001679
Douglas Gregora8f32e02009-10-06 17:59:45 +00001680 case LookupTagName:
1681 BaseCallback = &CXXRecordDecl::FindTagMember;
1682 break;
John McCall9f54ad42009-12-10 09:41:52 +00001683
Douglas Gregor8071e422010-08-15 06:18:01 +00001684 case LookupAnyName:
1685 BaseCallback = &LookupAnyMember;
1686 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001687
John McCall9f54ad42009-12-10 09:41:52 +00001688 case LookupUsingDeclName:
1689 // This lookup is for redeclarations only.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001690
Douglas Gregora8f32e02009-10-06 17:59:45 +00001691 case LookupOperatorName:
1692 case LookupNamespaceName:
1693 case LookupObjCProtocolName:
Chris Lattner337e5502011-02-18 01:27:55 +00001694 case LookupLabel:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001695 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001696 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001697
Douglas Gregora8f32e02009-10-06 17:59:45 +00001698 case LookupNestedNameSpecifierName:
1699 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1700 break;
1701 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001702
John McCalla24dc2e2009-11-17 02:14:36 +00001703 if (!LookupRec->lookupInBases(BaseCallback,
1704 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001705 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001706
John McCall92f88312010-01-23 00:46:32 +00001707 R.setNamingClass(LookupRec);
1708
Douglas Gregor7176fff2009-01-15 00:26:24 +00001709 // C++ [class.member.lookup]p2:
1710 // [...] If the resulting set of declarations are not all from
1711 // sub-objects of the same type, or the set has a nonstatic member
1712 // and includes members from distinct sub-objects, there is an
1713 // ambiguity and the program is ill-formed. Otherwise that set is
1714 // the result of the lookup.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001715 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001716 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001717 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001718
Douglas Gregora8f32e02009-10-06 17:59:45 +00001719 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001720 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001721 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001722
John McCall46460a62010-01-20 21:53:11 +00001723 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1724 // across all paths.
1725 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001726
Douglas Gregor7176fff2009-01-15 00:26:24 +00001727 // Determine whether we're looking at a distinct sub-object or not.
1728 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001729 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001730 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1731 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001732 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001733 }
1734
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001735 if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001736 != Context.getCanonicalType(PathElement.Base->getType())) {
1737 // We found members of the given name in two subobjects of
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001738 // different types. If the declaration sets aren't the same, this
1739 // this lookup is ambiguous.
David Blaikie3bc93e32012-12-19 00:45:41 +00001740 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001741 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikie3bc93e32012-12-19 00:45:41 +00001742 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
1743 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001744
David Blaikie3bc93e32012-12-19 00:45:41 +00001745 while (FirstD != FirstPath->Decls.end() &&
1746 CurrentD != Path->Decls.end()) {
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001747 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1748 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1749 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001750
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001751 ++FirstD;
1752 ++CurrentD;
1753 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001754
David Blaikie3bc93e32012-12-19 00:45:41 +00001755 if (FirstD == FirstPath->Decls.end() &&
1756 CurrentD == Path->Decls.end())
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001757 continue;
1758 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001759
John McCallf36e02d2009-10-09 21:13:30 +00001760 R.setAmbiguousBaseSubobjectTypes(Paths);
1761 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001762 }
1763
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001764 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001765 // We have a different subobject of the same type.
1766
1767 // C++ [class.member.lookup]p5:
1768 // A static member, a nested type or an enumerator defined in
1769 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001770 // has more than one base class subobject of type T.
David Blaikie3bc93e32012-12-19 00:45:41 +00001771 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor7176fff2009-01-15 00:26:24 +00001772 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001773
Douglas Gregor7176fff2009-01-15 00:26:24 +00001774 // We have found a nonstatic member name in multiple, distinct
1775 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001776 R.setAmbiguousBaseSubobjects(Paths);
1777 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001778 }
1779 }
1780
1781 // Lookup in a base class succeeded; return these results.
1782
David Blaikie3bc93e32012-12-19 00:45:41 +00001783 DeclContext::lookup_result DR = Paths.front().Decls;
1784 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E; ++I) {
John McCall92f88312010-01-23 00:46:32 +00001785 NamedDecl *D = *I;
1786 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1787 D->getAccess());
1788 R.addDecl(D, AS);
1789 }
John McCallf36e02d2009-10-09 21:13:30 +00001790 R.resolveKind();
1791 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001792}
1793
1794/// @brief Performs name lookup for a name that was parsed in the
1795/// source code, and may contain a C++ scope specifier.
1796///
1797/// This routine is a convenience routine meant to be called from
1798/// contexts that receive a name and an optional C++ scope specifier
1799/// (e.g., "N::M::x"). It will then perform either qualified or
1800/// unqualified name lookup (with LookupQualifiedName or LookupName,
1801/// respectively) on the given name and return those results.
1802///
1803/// @param S The scope from which unqualified name lookup will
1804/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001805///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001806/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001807///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001808/// @param EnteringContext Indicates whether we are going to enter the
1809/// context of the scope-specifier SS (if present).
1810///
John McCallf36e02d2009-10-09 21:13:30 +00001811/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001812bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001813 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001814 if (SS && SS->isInvalid()) {
1815 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001816 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001817 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001818 }
Mike Stump1eb44332009-09-09 15:08:12 +00001819
Douglas Gregor495c35d2009-08-25 22:51:20 +00001820 if (SS && SS->isSet()) {
1821 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001822 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001823 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001824 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001825 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001826
John McCalla24dc2e2009-11-17 02:14:36 +00001827 R.setContextRange(SS->getRange());
John McCalla24dc2e2009-11-17 02:14:36 +00001828 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001829 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001830
Douglas Gregor495c35d2009-08-25 22:51:20 +00001831 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001832 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001833 // Name lookup can't find anything in this case.
Douglas Gregor3eafbb82011-10-24 22:24:50 +00001834 R.setNotFoundInCurrentInstantiation();
1835 R.setContextRange(SS->getRange());
John McCallf36e02d2009-10-09 21:13:30 +00001836 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001837 }
1838
Mike Stump1eb44332009-09-09 15:08:12 +00001839 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001840 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001841}
1842
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001843
James Dennett16ae9de2012-06-22 10:16:05 +00001844/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor7176fff2009-01-15 00:26:24 +00001845/// from name lookup.
1846///
James Dennett16ae9de2012-06-22 10:16:05 +00001847/// \param Result The result of the ambiguous lookup to be diagnosed.
Serge Pavlov8ed2f3a2013-08-29 07:23:24 +00001848void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001849 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1850
John McCalla24dc2e2009-11-17 02:14:36 +00001851 DeclarationName Name = Result.getLookupName();
1852 SourceLocation NameLoc = Result.getNameLoc();
1853 SourceRange LookupRange = Result.getContextRange();
1854
John McCall6e247262009-10-10 05:48:19 +00001855 switch (Result.getAmbiguityKind()) {
1856 case LookupResult::AmbiguousBaseSubobjects: {
1857 CXXBasePaths *Paths = Result.getBasePaths();
1858 QualType SubobjectType = Paths->front().back().Base->getType();
1859 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1860 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1861 << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001862
David Blaikie3bc93e32012-12-19 00:45:41 +00001863 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6e247262009-10-10 05:48:19 +00001864 while (isa<CXXMethodDecl>(*Found) &&
1865 cast<CXXMethodDecl>(*Found)->isStatic())
1866 ++Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001867
John McCall6e247262009-10-10 05:48:19 +00001868 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
Serge Pavlov8ed2f3a2013-08-29 07:23:24 +00001869 break;
John McCall6e247262009-10-10 05:48:19 +00001870 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001871
John McCall6e247262009-10-10 05:48:19 +00001872 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001873 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1874 << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001875
John McCall6e247262009-10-10 05:48:19 +00001876 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001877 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001878 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1879 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001880 Path != PathEnd; ++Path) {
David Blaikie3bc93e32012-12-19 00:45:41 +00001881 Decl *D = Path->Decls.front();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001882 if (DeclsPrinted.insert(D).second)
1883 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1884 }
Serge Pavlov8ed2f3a2013-08-29 07:23:24 +00001885 break;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001886 }
1887
John McCall6e247262009-10-10 05:48:19 +00001888 case LookupResult::AmbiguousTagHiding: {
1889 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001890
John McCall6e247262009-10-10 05:48:19 +00001891 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1892
1893 LookupResult::iterator DI, DE = Result.end();
1894 for (DI = Result.begin(); DI != DE; ++DI)
1895 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1896 TagDecls.insert(TD);
1897 Diag(TD->getLocation(), diag::note_hidden_tag);
1898 }
1899
1900 for (DI = Result.begin(); DI != DE; ++DI)
1901 if (!isa<TagDecl>(*DI))
1902 Diag((*DI)->getLocation(), diag::note_hiding_object);
1903
1904 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001905 LookupResult::Filter F = Result.makeFilter();
1906 while (F.hasNext()) {
1907 if (TagDecls.count(F.next()))
1908 F.erase();
1909 }
1910 F.done();
Serge Pavlov8ed2f3a2013-08-29 07:23:24 +00001911 break;
John McCall6e247262009-10-10 05:48:19 +00001912 }
1913
1914 case LookupResult::AmbiguousReference: {
1915 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001916
John McCall6e247262009-10-10 05:48:19 +00001917 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1918 for (; DI != DE; ++DI)
1919 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
Serge Pavlov8ed2f3a2013-08-29 07:23:24 +00001920 break;
John McCall6e247262009-10-10 05:48:19 +00001921 }
Serge Pavlov8ed2f3a2013-08-29 07:23:24 +00001922 }
Douglas Gregor7176fff2009-01-15 00:26:24 +00001923}
Douglas Gregorfa047642009-02-04 00:32:51 +00001924
John McCallc7e04da2010-05-28 18:45:08 +00001925namespace {
1926 struct AssociatedLookup {
John McCall42f48fb2012-08-24 20:38:34 +00001927 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallc7e04da2010-05-28 18:45:08 +00001928 Sema::AssociatedNamespaceSet &Namespaces,
1929 Sema::AssociatedClassSet &Classes)
John McCall42f48fb2012-08-24 20:38:34 +00001930 : S(S), Namespaces(Namespaces), Classes(Classes),
1931 InstantiationLoc(InstantiationLoc) {
John McCallc7e04da2010-05-28 18:45:08 +00001932 }
1933
1934 Sema &S;
1935 Sema::AssociatedNamespaceSet &Namespaces;
1936 Sema::AssociatedClassSet &Classes;
John McCall42f48fb2012-08-24 20:38:34 +00001937 SourceLocation InstantiationLoc;
John McCallc7e04da2010-05-28 18:45:08 +00001938 };
1939}
1940
Mike Stump1eb44332009-09-09 15:08:12 +00001941static void
John McCallc7e04da2010-05-28 18:45:08 +00001942addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCall6ff07852009-08-07 22:18:02 +00001943
Douglas Gregor54022952010-04-30 07:08:38 +00001944static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1945 DeclContext *Ctx) {
1946 // Add the associated namespace for this class.
1947
1948 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1949 // be a locally scoped record.
1950
Sebastian Redl410c4f22010-08-31 20:53:31 +00001951 // We skip out of inline namespaces. The innermost non-inline namespace
1952 // contains all names of all its nested inline namespaces anyway, so we can
1953 // replace the entire inline namespace tree with its root.
1954 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1955 Ctx->isInlineNamespace())
Douglas Gregor54022952010-04-30 07:08:38 +00001956 Ctx = Ctx->getParent();
1957
John McCall6ff07852009-08-07 22:18:02 +00001958 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001959 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001960}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001961
Mike Stump1eb44332009-09-09 15:08:12 +00001962// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001963// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001964static void
John McCallc7e04da2010-05-28 18:45:08 +00001965addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1966 const TemplateArgument &Arg) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001967 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001968 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001969 switch (Arg.getKind()) {
1970 case TemplateArgument::Null:
1971 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001972
Douglas Gregor69be8d62009-07-08 07:51:57 +00001973 case TemplateArgument::Type:
1974 // [...] the namespaces and classes associated with the types of the
1975 // template arguments provided for template type parameters (excluding
1976 // template template parameters)
John McCallc7e04da2010-05-28 18:45:08 +00001977 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor69be8d62009-07-08 07:51:57 +00001978 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001979
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001980 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001981 case TemplateArgument::TemplateExpansion: {
Mike Stump1eb44332009-09-09 15:08:12 +00001982 // [...] the namespaces in which any template template arguments are
1983 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001984 // template template arguments are defined.
Douglas Gregora7fc9012011-01-05 18:58:31 +00001985 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump1eb44332009-09-09 15:08:12 +00001986 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001987 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001988 DeclContext *Ctx = ClassTemplate->getDeclContext();
1989 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001990 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001991 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001992 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001993 }
1994 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001995 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001996
Douglas Gregor788cd062009-11-11 01:00:40 +00001997 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001998 case TemplateArgument::Integral:
1999 case TemplateArgument::Expression:
Eli Friedmand7a6b162012-09-26 02:36:12 +00002000 case TemplateArgument::NullPtr:
Mike Stump1eb44332009-09-09 15:08:12 +00002001 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00002002 // associated namespaces. ]
2003 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002004
Douglas Gregor69be8d62009-07-08 07:51:57 +00002005 case TemplateArgument::Pack:
2006 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
2007 PEnd = Arg.pack_end();
2008 P != PEnd; ++P)
John McCallc7e04da2010-05-28 18:45:08 +00002009 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor69be8d62009-07-08 07:51:57 +00002010 break;
2011 }
2012}
2013
Douglas Gregorfa047642009-02-04 00:32:51 +00002014// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00002015// argument-dependent lookup with an argument of class type
2016// (C++ [basic.lookup.koenig]p2).
2017static void
John McCallc7e04da2010-05-28 18:45:08 +00002018addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2019 CXXRecordDecl *Class) {
2020
2021 // Just silently ignore anything whose name is __va_list_tag.
2022 if (Class->getDeclName() == Result.S.VAListTagName)
2023 return;
2024
Douglas Gregorfa047642009-02-04 00:32:51 +00002025 // C++ [basic.lookup.koenig]p2:
2026 // [...]
2027 // -- If T is a class type (including unions), its associated
2028 // classes are: the class itself; the class of which it is a
2029 // member, if any; and its direct and indirect base
2030 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00002031 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00002032
2033 // Add the class of which it is a member, if any.
2034 DeclContext *Ctx = Class->getDeclContext();
2035 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00002036 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00002037 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00002038 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00002039
Douglas Gregorfa047642009-02-04 00:32:51 +00002040 // Add the class itself. If we've already seen this class, we don't
2041 // need to visit base classes.
John McCallc7e04da2010-05-28 18:45:08 +00002042 if (!Result.Classes.insert(Class))
Douglas Gregorfa047642009-02-04 00:32:51 +00002043 return;
2044
Mike Stump1eb44332009-09-09 15:08:12 +00002045 // -- If T is a template-id, its associated namespaces and classes are
2046 // the namespace in which the template is defined; for member
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002047 // templates, the member template's class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00002048 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00002049 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00002050 // namespaces in which any template template arguments are defined; and
2051 // the classes in which any member templates used as template template
2052 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00002053 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00002054 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00002055 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2056 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2057 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00002058 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00002059 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00002060 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00002061
Douglas Gregor69be8d62009-07-08 07:51:57 +00002062 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2063 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallc7e04da2010-05-28 18:45:08 +00002064 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor69be8d62009-07-08 07:51:57 +00002065 }
Mike Stump1eb44332009-09-09 15:08:12 +00002066
John McCall86ff3082010-02-04 22:26:26 +00002067 // Only recurse into base classes for complete types.
2068 if (!Class->hasDefinition()) {
John McCall42f48fb2012-08-24 20:38:34 +00002069 QualType type = Result.S.Context.getTypeDeclType(Class);
2070 if (Result.S.RequireCompleteType(Result.InstantiationLoc, type,
2071 /*no diagnostic*/ 0))
2072 return;
John McCall86ff3082010-02-04 22:26:26 +00002073 }
2074
Douglas Gregorfa047642009-02-04 00:32:51 +00002075 // Add direct and indirect base classes along with their associated
2076 // namespaces.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002077 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregorfa047642009-02-04 00:32:51 +00002078 Bases.push_back(Class);
2079 while (!Bases.empty()) {
2080 // Pop this class off the stack.
Robert Wilhelm344472e2013-08-23 16:11:15 +00002081 Class = Bases.pop_back_val();
Douglas Gregorfa047642009-02-04 00:32:51 +00002082
2083 // Visit the base classes.
2084 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
2085 BaseEnd = Class->bases_end();
2086 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002087 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00002088 // In dependent contexts, we do ADL twice, and the first time around,
2089 // the base type might be a dependent TemplateSpecializationType, or a
2090 // TemplateTypeParmType. If that happens, simply ignore it.
2091 // FIXME: If we want to support export, we probably need to add the
2092 // namespace of the template in a TemplateSpecializationType, or even
2093 // the classes and namespaces of known non-dependent arguments.
2094 if (!BaseType)
2095 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00002096 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00002097 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002098 // Find the associated namespace for this base class.
2099 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallc7e04da2010-05-28 18:45:08 +00002100 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00002101
2102 // Make sure we visit the bases of this base class.
2103 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2104 Bases.push_back(BaseDecl);
2105 }
2106 }
2107 }
2108}
2109
2110// \brief Add the associated classes and namespaces for
2111// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00002112// (C++ [basic.lookup.koenig]p2).
2113static void
John McCallc7e04da2010-05-28 18:45:08 +00002114addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002115 // C++ [basic.lookup.koenig]p2:
2116 //
2117 // For each argument type T in the function call, there is a set
2118 // of zero or more associated namespaces and a set of zero or more
2119 // associated classes to be considered. The sets of namespaces and
2120 // classes is determined entirely by the types of the function
2121 // arguments (and the namespace of any template template
2122 // argument). Typedef names and using-declarations used to specify
2123 // the types do not contribute to this set. The sets of namespaces
2124 // and classes are determined in the following way:
Douglas Gregorfa047642009-02-04 00:32:51 +00002125
Chris Lattner5f9e2722011-07-23 10:55:15 +00002126 SmallVector<const Type *, 16> Queue;
John McCallfa4edcf2010-05-28 06:08:54 +00002127 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2128
Douglas Gregorfa047642009-02-04 00:32:51 +00002129 while (true) {
John McCallfa4edcf2010-05-28 06:08:54 +00002130 switch (T->getTypeClass()) {
2131
2132#define TYPE(Class, Base)
2133#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2134#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2135#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2136#define ABSTRACT_TYPE(Class, Base)
2137#include "clang/AST/TypeNodes.def"
2138 // T is canonical. We can also ignore dependent types because
2139 // we don't need to do ADL at the definition point, but if we
2140 // wanted to implement template export (or if we find some other
2141 // use for associated classes and namespaces...) this would be
2142 // wrong.
Douglas Gregorfa047642009-02-04 00:32:51 +00002143 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00002144
John McCallfa4edcf2010-05-28 06:08:54 +00002145 // -- If T is a pointer to U or an array of U, its associated
2146 // namespaces and classes are those associated with U.
2147 case Type::Pointer:
2148 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2149 continue;
2150 case Type::ConstantArray:
2151 case Type::IncompleteArray:
2152 case Type::VariableArray:
2153 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2154 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00002155
John McCallfa4edcf2010-05-28 06:08:54 +00002156 // -- If T is a fundamental type, its associated sets of
2157 // namespaces and classes are both empty.
2158 case Type::Builtin:
2159 break;
2160
2161 // -- If T is a class type (including unions), its associated
2162 // classes are: the class itself; the class of which it is a
2163 // member, if any; and its direct and indirect base
2164 // classes. Its associated namespaces are the namespaces in
2165 // which its associated classes are defined.
2166 case Type::Record: {
2167 CXXRecordDecl *Class
2168 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00002169 addAssociatedClassesAndNamespaces(Result, Class);
John McCallfa4edcf2010-05-28 06:08:54 +00002170 break;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002171 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00002172
John McCallfa4edcf2010-05-28 06:08:54 +00002173 // -- If T is an enumeration type, its associated namespace is
2174 // the namespace in which it is defined. If it is class
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002175 // member, its associated class is the member's class; else
John McCallfa4edcf2010-05-28 06:08:54 +00002176 // it has no associated class.
2177 case Type::Enum: {
2178 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002179
John McCallfa4edcf2010-05-28 06:08:54 +00002180 DeclContext *Ctx = Enum->getDeclContext();
2181 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00002182 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00002183
John McCallfa4edcf2010-05-28 06:08:54 +00002184 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00002185 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00002186
John McCallfa4edcf2010-05-28 06:08:54 +00002187 break;
2188 }
2189
2190 // -- If T is a function type, its associated namespaces and
2191 // classes are those associated with the function parameter
2192 // types and those associated with the return type.
2193 case Type::FunctionProto: {
2194 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2195 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
2196 ArgEnd = Proto->arg_type_end();
2197 Arg != ArgEnd; ++Arg)
2198 Queue.push_back(Arg->getTypePtr());
2199 // fallthrough
2200 }
2201 case Type::FunctionNoProto: {
2202 const FunctionType *FnType = cast<FunctionType>(T);
2203 T = FnType->getResultType().getTypePtr();
2204 continue;
2205 }
2206
2207 // -- If T is a pointer to a member function of a class X, its
2208 // associated namespaces and classes are those associated
2209 // with the function parameter types and return type,
2210 // together with those associated with X.
2211 //
2212 // -- If T is a pointer to a data member of class X, its
2213 // associated namespaces and classes are those associated
2214 // with the member type together with those associated with
2215 // X.
2216 case Type::MemberPointer: {
2217 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2218
2219 // Queue up the class type into which this points.
2220 Queue.push_back(MemberPtr->getClass());
2221
2222 // And directly continue with the pointee type.
2223 T = MemberPtr->getPointeeType().getTypePtr();
2224 continue;
2225 }
2226
2227 // As an extension, treat this like a normal pointer.
2228 case Type::BlockPointer:
2229 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2230 continue;
2231
2232 // References aren't covered by the standard, but that's such an
2233 // obvious defect that we cover them anyway.
2234 case Type::LValueReference:
2235 case Type::RValueReference:
2236 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2237 continue;
2238
2239 // These are fundamental types.
2240 case Type::Vector:
2241 case Type::ExtVector:
2242 case Type::Complex:
2243 break;
2244
Richard Smithdc7a4f52013-04-30 13:56:41 +00002245 // Non-deduced auto types only get here for error cases.
2246 case Type::Auto:
2247 break;
2248
Douglas Gregorf25760e2011-04-12 01:02:45 +00002249 // If T is an Objective-C object or interface type, or a pointer to an
2250 // object or interface type, the associated namespace is the global
2251 // namespace.
John McCallfa4edcf2010-05-28 06:08:54 +00002252 case Type::ObjCObject:
2253 case Type::ObjCInterface:
2254 case Type::ObjCObjectPointer:
Douglas Gregorf25760e2011-04-12 01:02:45 +00002255 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCallfa4edcf2010-05-28 06:08:54 +00002256 break;
Eli Friedmanb001de72011-10-06 23:00:33 +00002257
2258 // Atomic types are just wrappers; use the associations of the
2259 // contained type.
2260 case Type::Atomic:
2261 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2262 continue;
John McCallfa4edcf2010-05-28 06:08:54 +00002263 }
2264
Robert Wilhelm344472e2013-08-23 16:11:15 +00002265 if (Queue.empty())
2266 break;
2267 T = Queue.pop_back_val();
Douglas Gregorfa047642009-02-04 00:32:51 +00002268 }
Douglas Gregorfa047642009-02-04 00:32:51 +00002269}
2270
2271/// \brief Find the associated classes and namespaces for
2272/// argument-dependent lookup for a call with the given set of
2273/// arguments.
2274///
2275/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00002276/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00002277/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm834c0582013-08-09 18:02:13 +00002278void Sema::FindAssociatedClassesAndNamespaces(
2279 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2280 AssociatedNamespaceSet &AssociatedNamespaces,
2281 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002282 AssociatedNamespaces.clear();
2283 AssociatedClasses.clear();
2284
John McCall42f48fb2012-08-24 20:38:34 +00002285 AssociatedLookup Result(*this, InstantiationLoc,
2286 AssociatedNamespaces, AssociatedClasses);
John McCallc7e04da2010-05-28 18:45:08 +00002287
Douglas Gregorfa047642009-02-04 00:32:51 +00002288 // C++ [basic.lookup.koenig]p2:
2289 // For each argument type T in the function call, there is a set
2290 // of zero or more associated namespaces and a set of zero or more
2291 // associated classes to be considered. The sets of namespaces and
2292 // classes is determined entirely by the types of the function
2293 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00002294 // argument).
Ahmed Charles13a140c2012-02-25 11:00:22 +00002295 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002296 Expr *Arg = Args[ArgIdx];
2297
2298 if (Arg->getType() != Context.OverloadTy) {
John McCallc7e04da2010-05-28 18:45:08 +00002299 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002300 continue;
2301 }
2302
2303 // [...] In addition, if the argument is the name or address of a
2304 // set of overloaded functions and/or function templates, its
2305 // associated classes and namespaces are the union of those
2306 // associated with each of the members of the set: the namespace
2307 // in which the function or function template is defined and the
2308 // classes and namespaces associated with its (non-dependent)
2309 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00002310 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00002311 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCall2de56d12010-08-25 11:45:40 +00002312 if (unaryOp->getOpcode() == UO_AddrOf)
John McCallba135432009-11-21 08:51:07 +00002313 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002314
John McCallc7e04da2010-05-28 18:45:08 +00002315 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2316 if (!ULE) continue;
John McCallba135432009-11-21 08:51:07 +00002317
John McCallc7e04da2010-05-28 18:45:08 +00002318 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2319 I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00002320 // Look through any using declarations to find the underlying function.
2321 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002322
Chandler Carruthbd647292009-12-29 06:17:27 +00002323 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2324 if (!FDecl)
2325 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002326
2327 // Add the classes and namespaces associated with the parameter
2328 // types and return type of this function.
John McCallc7e04da2010-05-28 18:45:08 +00002329 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002330 }
2331 }
2332}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002333
2334/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2335/// an acceptable non-member overloaded operator for a call whose
2336/// arguments have types T1 (and, if non-empty, T2). This routine
2337/// implements the check in C++ [over.match.oper]p3b2 concerning
2338/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00002339static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002340IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2341 QualType T1, QualType T2,
2342 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00002343 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2344 return true;
2345
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002346 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2347 return true;
2348
John McCall183700f2009-09-21 23:43:11 +00002349 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002350 if (Proto->getNumArgs() < 1)
2351 return false;
2352
2353 if (T1->isEnumeralType()) {
2354 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002355 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002356 return true;
2357 }
2358
2359 if (Proto->getNumArgs() < 2)
2360 return false;
2361
2362 if (!T2.isNull() && T2->isEnumeralType()) {
2363 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002364 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002365 return true;
2366 }
2367
2368 return false;
2369}
2370
John McCall7d384dd2009-11-18 07:57:50 +00002371NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002372 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00002373 LookupNameKind NameKind,
2374 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002375 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00002376 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00002377 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00002378}
2379
Douglas Gregor6e378de2009-04-23 23:18:26 +00002380/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002381ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002382 SourceLocation IdLoc,
2383 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002384 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002385 LookupObjCProtocolName, Redecl);
Douglas Gregor6e378de2009-04-23 23:18:26 +00002386 return cast_or_null<ObjCProtocolDecl>(D);
2387}
2388
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002389void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00002390 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00002391 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002392 // C++ [over.match.oper]p3:
2393 // -- The set of non-member candidates is the result of the
2394 // unqualified lookup of operator@ in the context of the
2395 // expression according to the usual rules for name lookup in
2396 // unqualified function calls (3.4.2) except that all member
2397 // functions are ignored. However, if no operand has a class
2398 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00002399 // that have a first parameter of type T1 or "reference to
2400 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002401 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00002402 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002403 // when T2 is an enumeration type, are candidate functions.
2404 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00002405 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2406 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002407
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002408 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2409
John McCallf36e02d2009-10-09 21:13:30 +00002410 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002411 return;
2412
2413 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2414 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002415 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2416 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002417 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002418 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00002419 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002420 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00002421 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00002422 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00002423 // later?
2424 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002425 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00002426 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002427 }
2428}
2429
Sean Huntc39b6bc2011-06-24 02:11:39 +00002430Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Sean Hunt308742c2011-06-04 04:32:43 +00002431 CXXSpecialMember SM,
2432 bool ConstArg,
2433 bool VolatileArg,
2434 bool RValueThis,
2435 bool ConstThis,
2436 bool VolatileThis) {
Richard Smithd0adeb62012-11-27 21:20:31 +00002437 assert(CanDeclareSpecialMemberFunction(RD) &&
Sean Hunt308742c2011-06-04 04:32:43 +00002438 "doing special member lookup into record that isn't fully complete");
Richard Smithd0adeb62012-11-27 21:20:31 +00002439 RD = RD->getDefinition();
Sean Hunt308742c2011-06-04 04:32:43 +00002440 if (RValueThis || ConstThis || VolatileThis)
2441 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2442 "constructors and destructors always have unqualified lvalue this");
2443 if (ConstArg || VolatileArg)
2444 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2445 "parameter-less special members can't have qualified arguments");
2446
2447 llvm::FoldingSetNodeID ID;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002448 ID.AddPointer(RD);
Sean Hunt308742c2011-06-04 04:32:43 +00002449 ID.AddInteger(SM);
2450 ID.AddInteger(ConstArg);
2451 ID.AddInteger(VolatileArg);
2452 ID.AddInteger(RValueThis);
2453 ID.AddInteger(ConstThis);
2454 ID.AddInteger(VolatileThis);
2455
2456 void *InsertPoint;
2457 SpecialMemberOverloadResult *Result =
2458 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2459
2460 // This was already cached
2461 if (Result)
2462 return Result;
2463
Sean Hunt30543582011-06-07 00:11:58 +00002464 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2465 Result = new (Result) SpecialMemberOverloadResult(ID);
Sean Hunt308742c2011-06-04 04:32:43 +00002466 SpecialMemberCache.InsertNode(Result, InsertPoint);
2467
2468 if (SM == CXXDestructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00002469 if (RD->needsImplicitDestructor())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002470 DeclareImplicitDestructor(RD);
2471 CXXDestructorDecl *DD = RD->getDestructor();
Sean Hunt308742c2011-06-04 04:32:43 +00002472 assert(DD && "record without a destructor");
2473 Result->setMethod(DD);
Richard Smith6c4c36c2012-03-30 20:53:28 +00002474 Result->setKind(DD->isDeleted() ?
2475 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith704c8f72012-04-20 18:46:14 +00002476 SpecialMemberOverloadResult::Success);
Sean Hunt308742c2011-06-04 04:32:43 +00002477 return Result;
2478 }
2479
Sean Huntb320e0c2011-06-10 03:50:41 +00002480 // Prepare for overload resolution. Here we construct a synthetic argument
2481 // if necessary and make sure that implicit functions are declared.
Sean Huntc39b6bc2011-06-24 02:11:39 +00002482 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Sean Huntb320e0c2011-06-10 03:50:41 +00002483 DeclarationName Name;
2484 Expr *Arg = 0;
2485 unsigned NumArgs;
2486
Richard Smith704c8f72012-04-20 18:46:14 +00002487 QualType ArgType = CanTy;
2488 ExprValueKind VK = VK_LValue;
2489
Sean Huntb320e0c2011-06-10 03:50:41 +00002490 if (SM == CXXDefaultConstructor) {
2491 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2492 NumArgs = 0;
Sean Huntc39b6bc2011-06-24 02:11:39 +00002493 if (RD->needsImplicitDefaultConstructor())
2494 DeclareImplicitDefaultConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002495 } else {
2496 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2497 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smithe5411b72012-12-01 02:35:44 +00002498 if (RD->needsImplicitCopyConstructor())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002499 DeclareImplicitCopyConstructor(RD);
Richard Smith80ad52f2013-01-02 11:42:31 +00002500 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002501 DeclareImplicitMoveConstructor(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002502 } else {
2503 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smithe5411b72012-12-01 02:35:44 +00002504 if (RD->needsImplicitCopyAssignment())
Sean Huntc39b6bc2011-06-24 02:11:39 +00002505 DeclareImplicitCopyAssignment(RD);
Richard Smith80ad52f2013-01-02 11:42:31 +00002506 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002507 DeclareImplicitMoveAssignment(RD);
Sean Huntb320e0c2011-06-10 03:50:41 +00002508 }
2509
Sean Huntb320e0c2011-06-10 03:50:41 +00002510 if (ConstArg)
2511 ArgType.addConst();
2512 if (VolatileArg)
2513 ArgType.addVolatile();
2514
2515 // This isn't /really/ specified by the standard, but it's implied
2516 // we should be working from an RValue in the case of move to ensure
2517 // that we prefer to bind to rvalue references, and an LValue in the
2518 // case of copy to ensure we don't bind to rvalue references.
2519 // Possibly an XValue is actually correct in the case of move, but
2520 // there is no semantic difference for class types in this restricted
2521 // case.
Sean Huntab183df2011-06-22 22:13:13 +00002522 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Sean Huntb320e0c2011-06-10 03:50:41 +00002523 VK = VK_LValue;
2524 else
2525 VK = VK_RValue;
Richard Smith704c8f72012-04-20 18:46:14 +00002526 }
Sean Huntb320e0c2011-06-10 03:50:41 +00002527
Richard Smith704c8f72012-04-20 18:46:14 +00002528 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2529
2530 if (SM != CXXDefaultConstructor) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002531 NumArgs = 1;
Richard Smith704c8f72012-04-20 18:46:14 +00002532 Arg = &FakeArg;
Sean Huntb320e0c2011-06-10 03:50:41 +00002533 }
2534
2535 // Create the object argument
2536 QualType ThisTy = CanTy;
2537 if (ConstThis)
2538 ThisTy.addConst();
2539 if (VolatileThis)
2540 ThisTy.addVolatile();
Sean Hunt4cc12c62011-06-23 00:26:20 +00002541 Expr::Classification Classification =
Richard Smith704c8f72012-04-20 18:46:14 +00002542 OpaqueValueExpr(SourceLocation(), ThisTy,
2543 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Sean Huntb320e0c2011-06-10 03:50:41 +00002544
2545 // Now we perform lookup on the name we computed earlier and do overload
2546 // resolution. Lookup is only performed directly into the class since there
2547 // will always be a (possibly implicit) declaration to shadow any others.
2548 OverloadCandidateSet OCS((SourceLocation()));
David Blaikie3bc93e32012-12-19 00:45:41 +00002549 DeclContext::lookup_result R = RD->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00002550 assert(!R.empty() &&
Sean Huntb320e0c2011-06-10 03:50:41 +00002551 "lookup for a constructor or assignment operator was empty");
Chandler Carruthab4e0c02013-08-18 07:20:52 +00002552
2553 // Copy the candidates as our processing of them may load new declarations
2554 // from an external source and invalidate lookup_result.
2555 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2556
2557 for (SmallVectorImpl<NamedDecl *>::iterator I = Candidates.begin(),
Richard Smithb60fae52013-09-09 16:55:27 +00002558 E = Candidates.end();
Chandler Carruthab4e0c02013-08-18 07:20:52 +00002559 I != E; ++I) {
2560 NamedDecl *Cand = *I;
Sean Hunt4cc12c62011-06-23 00:26:20 +00002561
Sean Huntc39b6bc2011-06-24 02:11:39 +00002562 if (Cand->isInvalidDecl())
Sean Huntb320e0c2011-06-10 03:50:41 +00002563 continue;
2564
Sean Huntc39b6bc2011-06-24 02:11:39 +00002565 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2566 // FIXME: [namespace.udecl]p15 says that we should only consider a
2567 // using declaration here if it does not match a declaration in the
2568 // derived class. We do not implement this correctly in other cases
2569 // either.
2570 Cand = U->getTargetDecl();
2571
2572 if (Cand->isInvalidDecl())
2573 continue;
2574 }
2575
2576 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002577 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Sean Huntc39b6bc2011-06-24 02:11:39 +00002578 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002579 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2580 OCS, true);
Sean Hunt4cc12c62011-06-23 00:26:20 +00002581 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00002582 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2583 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Sean Hunt431a1cb2011-06-22 02:58:46 +00002584 } else if (FunctionTemplateDecl *Tmpl =
Sean Huntc39b6bc2011-06-24 02:11:39 +00002585 dyn_cast<FunctionTemplateDecl>(Cand)) {
Sean Hunt4cc12c62011-06-23 00:26:20 +00002586 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2587 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charles13a140c2012-02-25 11:00:22 +00002588 RD, 0, ThisTy, Classification,
2589 llvm::makeArrayRef(&Arg, NumArgs),
Sean Hunt4cc12c62011-06-23 00:26:20 +00002590 OCS, true);
2591 else
2592 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charles13a140c2012-02-25 11:00:22 +00002593 0, llvm::makeArrayRef(&Arg, NumArgs),
2594 OCS, true);
Sean Huntc39b6bc2011-06-24 02:11:39 +00002595 } else {
2596 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Sean Huntb320e0c2011-06-10 03:50:41 +00002597 }
2598 }
2599
2600 OverloadCandidateSet::iterator Best;
2601 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2602 case OR_Success:
2603 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith704c8f72012-04-20 18:46:14 +00002604 Result->setKind(SpecialMemberOverloadResult::Success);
Sean Huntb320e0c2011-06-10 03:50:41 +00002605 break;
2606
2607 case OR_Deleted:
2608 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith6c4c36c2012-03-30 20:53:28 +00002609 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Sean Huntb320e0c2011-06-10 03:50:41 +00002610 break;
2611
2612 case OR_Ambiguous:
Richard Smith6c4c36c2012-03-30 20:53:28 +00002613 Result->setMethod(0);
2614 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2615 break;
2616
Sean Huntb320e0c2011-06-10 03:50:41 +00002617 case OR_No_Viable_Function:
2618 Result->setMethod(0);
Richard Smith6c4c36c2012-03-30 20:53:28 +00002619 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Sean Huntb320e0c2011-06-10 03:50:41 +00002620 break;
2621 }
2622
2623 return Result;
2624}
2625
2626/// \brief Look up the default constructor for the given class.
2627CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Sean Huntc530d172011-06-10 04:44:37 +00002628 SpecialMemberOverloadResult *Result =
Sean Huntb320e0c2011-06-10 03:50:41 +00002629 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2630 false, false);
2631
2632 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Sean Hunt308742c2011-06-04 04:32:43 +00002633}
2634
Sean Hunt661c67a2011-06-21 23:42:56 +00002635/// \brief Look up the copying constructor for the given class.
2636CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith704c8f72012-04-20 18:46:14 +00002637 unsigned Quals) {
Sean Huntc530d172011-06-10 04:44:37 +00002638 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2639 "non-const, non-volatile qualifiers for copy ctor arg");
2640 SpecialMemberOverloadResult *Result =
2641 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2642 Quals & Qualifiers::Volatile, false, false, false);
2643
Sean Huntc530d172011-06-10 04:44:37 +00002644 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2645}
2646
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002647/// \brief Look up the moving constructor for the given class.
Richard Smith6a06e5f2012-07-18 03:36:00 +00002648CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2649 unsigned Quals) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002650 SpecialMemberOverloadResult *Result =
Richard Smith6a06e5f2012-07-18 03:36:00 +00002651 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2652 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002653
2654 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2655}
2656
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002657/// \brief Look up the constructors for the given class.
2658DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Sean Huntb320e0c2011-06-10 03:50:41 +00002659 // If the implicit constructors have not yet been declared, do so now.
Richard Smithd0adeb62012-11-27 21:20:31 +00002660 if (CanDeclareSpecialMemberFunction(Class)) {
Sean Huntcdee3fe2011-05-11 22:34:38 +00002661 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002662 DeclareImplicitDefaultConstructor(Class);
Richard Smithe5411b72012-12-01 02:35:44 +00002663 if (Class->needsImplicitCopyConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002664 DeclareImplicitCopyConstructor(Class);
Richard Smith80ad52f2013-01-02 11:42:31 +00002665 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002666 DeclareImplicitMoveConstructor(Class);
Douglas Gregor18274032010-07-03 00:47:00 +00002667 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002668
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002669 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2670 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2671 return Class->lookup(Name);
2672}
2673
Sean Hunt661c67a2011-06-21 23:42:56 +00002674/// \brief Look up the copying assignment operator for the given class.
2675CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2676 unsigned Quals, bool RValueThis,
Richard Smith704c8f72012-04-20 18:46:14 +00002677 unsigned ThisQuals) {
Sean Hunt661c67a2011-06-21 23:42:56 +00002678 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2679 "non-const, non-volatile qualifiers for copy assignment arg");
2680 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2681 "non-const, non-volatile qualifiers for copy assignment this");
2682 SpecialMemberOverloadResult *Result =
2683 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2684 Quals & Qualifiers::Volatile, RValueThis,
2685 ThisQuals & Qualifiers::Const,
2686 ThisQuals & Qualifiers::Volatile);
2687
Sean Hunt661c67a2011-06-21 23:42:56 +00002688 return Result->getMethod();
2689}
2690
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002691/// \brief Look up the moving assignment operator for the given class.
2692CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith6a06e5f2012-07-18 03:36:00 +00002693 unsigned Quals,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002694 bool RValueThis,
2695 unsigned ThisQuals) {
2696 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2697 "non-const, non-volatile qualifiers for copy assignment this");
2698 SpecialMemberOverloadResult *Result =
Richard Smith6a06e5f2012-07-18 03:36:00 +00002699 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2700 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002701 ThisQuals & Qualifiers::Const,
2702 ThisQuals & Qualifiers::Volatile);
2703
2704 return Result->getMethod();
2705}
2706
Douglas Gregordb89f282010-07-01 22:47:18 +00002707/// \brief Look for the destructor of the given class.
2708///
Sean Huntc5c9b532011-06-03 21:10:40 +00002709/// During semantic analysis, this routine should be used in lieu of
2710/// CXXRecordDecl::getDestructor().
Douglas Gregordb89f282010-07-01 22:47:18 +00002711///
2712/// \returns The destructor for this class.
2713CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Sean Hunt308742c2011-06-04 04:32:43 +00002714 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2715 false, false, false,
2716 false, false)->getMethod());
Douglas Gregordb89f282010-07-01 22:47:18 +00002717}
2718
Richard Smith36f5cfe2012-03-09 08:00:36 +00002719/// LookupLiteralOperator - Determine which literal operator should be used for
2720/// a user-defined literal, per C++11 [lex.ext].
2721///
2722/// Normal overload resolution is not used to select which literal operator to
2723/// call for a user-defined literal. Look up the provided literal operator name,
2724/// and filter the results to the appropriate set for the given argument types.
2725Sema::LiteralOperatorLookupResult
2726Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2727 ArrayRef<QualType> ArgTys,
Richard Smithb328e292013-10-07 19:57:58 +00002728 bool AllowRaw, bool AllowTemplate,
2729 bool AllowStringTemplate) {
Richard Smith36f5cfe2012-03-09 08:00:36 +00002730 LookupName(R, S);
2731 assert(R.getResultKind() != LookupResult::Ambiguous &&
2732 "literal operator lookup can't be ambiguous");
2733
2734 // Filter the lookup results appropriately.
2735 LookupResult::Filter F = R.makeFilter();
2736
Richard Smith36f5cfe2012-03-09 08:00:36 +00002737 bool FoundRaw = false;
Richard Smithb328e292013-10-07 19:57:58 +00002738 bool FoundTemplate = false;
2739 bool FoundStringTemplate = false;
Richard Smith36f5cfe2012-03-09 08:00:36 +00002740 bool FoundExactMatch = false;
2741
2742 while (F.hasNext()) {
2743 Decl *D = F.next();
2744 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2745 D = USD->getTargetDecl();
2746
Douglas Gregor7e0c2272013-04-10 05:18:00 +00002747 // If the declaration we found is invalid, skip it.
2748 if (D->isInvalidDecl()) {
2749 F.erase();
2750 continue;
2751 }
2752
Richard Smithb328e292013-10-07 19:57:58 +00002753 bool IsRaw = false;
2754 bool IsTemplate = false;
2755 bool IsStringTemplate = false;
2756 bool IsExactMatch = false;
2757
Richard Smith36f5cfe2012-03-09 08:00:36 +00002758 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2759 if (FD->getNumParams() == 1 &&
2760 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2761 IsRaw = true;
Richard Smitha121eb32013-01-15 07:12:59 +00002762 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smith36f5cfe2012-03-09 08:00:36 +00002763 IsExactMatch = true;
2764 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2765 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2766 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2767 IsExactMatch = false;
2768 break;
2769 }
2770 }
2771 }
2772 }
Richard Smithb328e292013-10-07 19:57:58 +00002773 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
2774 TemplateParameterList *Params = FD->getTemplateParameters();
2775 if (Params->size() == 1)
2776 IsTemplate = true;
2777 else
2778 IsStringTemplate = true;
2779 }
Richard Smith36f5cfe2012-03-09 08:00:36 +00002780
2781 if (IsExactMatch) {
2782 FoundExactMatch = true;
Richard Smithb328e292013-10-07 19:57:58 +00002783 AllowRaw = false;
2784 AllowTemplate = false;
2785 AllowStringTemplate = false;
2786 if (FoundRaw || FoundTemplate || FoundStringTemplate) {
Richard Smith36f5cfe2012-03-09 08:00:36 +00002787 // Go through again and remove the raw and template decls we've
2788 // already found.
2789 F.restart();
Richard Smithb328e292013-10-07 19:57:58 +00002790 FoundRaw = FoundTemplate = FoundStringTemplate = false;
Richard Smith36f5cfe2012-03-09 08:00:36 +00002791 }
Richard Smithb328e292013-10-07 19:57:58 +00002792 } else if (AllowRaw && IsRaw) {
2793 FoundRaw = true;
2794 } else if (AllowTemplate && IsTemplate) {
2795 FoundTemplate = true;
2796 } else if (AllowStringTemplate && IsStringTemplate) {
2797 FoundStringTemplate = true;
Richard Smith36f5cfe2012-03-09 08:00:36 +00002798 } else {
2799 F.erase();
2800 }
2801 }
2802
2803 F.done();
2804
2805 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2806 // parameter type, that is used in preference to a raw literal operator
2807 // or literal operator template.
2808 if (FoundExactMatch)
2809 return LOLR_Cooked;
2810
2811 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2812 // operator template, but not both.
2813 if (FoundRaw && FoundTemplate) {
2814 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
2815 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2816 Decl *D = *I;
2817 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2818 D = USD->getTargetDecl();
2819 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2820 D = FunTmpl->getTemplatedDecl();
2821 NoteOverloadCandidate(cast<FunctionDecl>(D));
2822 }
2823 return LOLR_Error;
2824 }
2825
2826 if (FoundRaw)
2827 return LOLR_Raw;
2828
2829 if (FoundTemplate)
2830 return LOLR_Template;
2831
Richard Smithb328e292013-10-07 19:57:58 +00002832 if (FoundStringTemplate)
2833 return LOLR_StringTemplate;
2834
Richard Smith36f5cfe2012-03-09 08:00:36 +00002835 // Didn't find anything we could use.
2836 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2837 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
Richard Smithb328e292013-10-07 19:57:58 +00002838 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
2839 << (AllowTemplate || AllowStringTemplate);
Richard Smith36f5cfe2012-03-09 08:00:36 +00002840 return LOLR_Error;
2841}
2842
John McCall7edb5fd2010-01-26 07:16:45 +00002843void ADLResult::insert(NamedDecl *New) {
2844 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2845
2846 // If we haven't yet seen a decl for this key, or the last decl
2847 // was exactly this one, we're done.
2848 if (Old == 0 || Old == New) {
2849 Old = New;
2850 return;
2851 }
2852
2853 // Otherwise, decide which is a more recent redeclaration.
2854 FunctionDecl *OldFD, *NewFD;
2855 if (isa<FunctionTemplateDecl>(New)) {
2856 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2857 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2858 } else {
2859 OldFD = cast<FunctionDecl>(Old);
2860 NewFD = cast<FunctionDecl>(New);
2861 }
2862
2863 FunctionDecl *Cursor = NewFD;
2864 while (true) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002865 Cursor = Cursor->getPreviousDecl();
John McCall7edb5fd2010-01-26 07:16:45 +00002866
2867 // If we got to the end without finding OldFD, OldFD is the newer
2868 // declaration; leave things as they are.
2869 if (!Cursor) return;
2870
2871 // If we do find OldFD, then NewFD is newer.
2872 if (Cursor == OldFD) break;
2873
2874 // Otherwise, keep looking.
2875 }
2876
2877 Old = New;
2878}
2879
Sebastian Redl644be852009-10-23 19:23:15 +00002880void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Robert Wilhelm834c0582013-08-09 18:02:13 +00002881 SourceLocation Loc, ArrayRef<Expr *> Args,
Richard Smithb1502bc2012-10-18 17:56:02 +00002882 ADLResult &Result) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002883 // Find all of the associated namespaces and classes based on the
2884 // arguments we have.
2885 AssociatedNamespaceSet AssociatedNamespaces;
2886 AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00002887 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCall6ff07852009-08-07 22:18:02 +00002888 AssociatedNamespaces,
2889 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002890
Sebastian Redl644be852009-10-23 19:23:15 +00002891 QualType T1, T2;
2892 if (Operator) {
2893 T1 = Args[0]->getType();
Ahmed Charles13a140c2012-02-25 11:00:22 +00002894 if (Args.size() >= 2)
Sebastian Redl644be852009-10-23 19:23:15 +00002895 T2 = Args[1]->getType();
2896 }
2897
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002898 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002899 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2900 // and let Y be the lookup set produced by argument dependent
2901 // lookup (defined as follows). If X contains [...] then Y is
2902 // empty. Otherwise Y is the set of declarations found in the
2903 // namespaces associated with the argument types as described
2904 // below. The set of declarations found by the lookup of the name
2905 // is the union of X and Y.
2906 //
2907 // Here, we compute Y and add its members to the overloaded
2908 // candidate set.
2909 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002910 NSEnd = AssociatedNamespaces.end();
2911 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002912 // When considering an associated namespace, the lookup is the
2913 // same as the lookup performed when the associated namespace is
2914 // used as a qualifier (3.4.3.2) except that:
2915 //
2916 // -- Any using-directives in the associated namespace are
2917 // ignored.
2918 //
John McCall6ff07852009-08-07 22:18:02 +00002919 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002920 // associated classes are visible within their respective
2921 // namespaces even if they are not visible during an ordinary
2922 // lookup (11.4).
David Blaikie3bc93e32012-12-19 00:45:41 +00002923 DeclContext::lookup_result R = (*NS)->lookup(Name);
2924 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
2925 ++I) {
John McCall6e266892010-01-26 03:27:55 +00002926 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00002927 // If the only declaration here is an ordinary friend, consider
2928 // it only if it was declared in an associated classes.
Richard Smitha41c97a2013-09-20 01:15:31 +00002929 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) {
2930 // If it's neither ordinarily visible nor a friend, we can't find it.
2931 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0)
2932 continue;
2933
Richard Smith22050f22013-07-17 23:53:16 +00002934 bool DeclaredInAssociatedClass = false;
2935 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
2936 DeclContext *LexDC = DI->getLexicalDeclContext();
2937 if (isa<CXXRecordDecl>(LexDC) &&
2938 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) {
2939 DeclaredInAssociatedClass = true;
2940 break;
2941 }
2942 }
2943 if (!DeclaredInAssociatedClass)
John McCall3f9a8a62009-08-11 06:59:38 +00002944 continue;
2945 }
Mike Stump1eb44332009-09-09 15:08:12 +00002946
John McCalla113e722010-01-26 06:04:06 +00002947 if (isa<UsingShadowDecl>(D))
2948 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00002949
John McCalla113e722010-01-26 06:04:06 +00002950 if (isa<FunctionDecl>(D)) {
2951 if (Operator &&
2952 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2953 T1, T2, Context))
2954 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00002955 } else if (!isa<FunctionTemplateDecl>(D))
2956 continue;
2957
2958 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00002959 }
2960 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002961}
Douglas Gregor546be3c2009-12-30 17:04:44 +00002962
2963//----------------------------------------------------------------------------
2964// Search for all visible declarations.
2965//----------------------------------------------------------------------------
2966VisibleDeclConsumer::~VisibleDeclConsumer() { }
2967
Richard Smithd67679d2013-08-20 20:35:18 +00002968bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
2969
Douglas Gregor546be3c2009-12-30 17:04:44 +00002970namespace {
2971
2972class ShadowContextRAII;
2973
2974class VisibleDeclsRecord {
2975public:
2976 /// \brief An entry in the shadow map, which is optimized to store a
2977 /// single declaration (the common case) but can also store a list
2978 /// of declarations.
Chris Lattnerb5f65472011-07-18 01:54:02 +00002979 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002980
2981private:
2982 /// \brief A mapping from declaration names to the declarations that have
2983 /// this name within a particular scope.
2984 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2985
2986 /// \brief A list of shadow maps, which is used to model name hiding.
2987 std::list<ShadowMap> ShadowMaps;
2988
2989 /// \brief The declaration contexts we have already visited.
2990 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2991
2992 friend class ShadowContextRAII;
2993
2994public:
2995 /// \brief Determine whether we have already visited this context
2996 /// (and, if not, note that we are going to visit that context now).
2997 bool visitedContext(DeclContext *Ctx) {
2998 return !VisitedContexts.insert(Ctx);
2999 }
3000
Douglas Gregor8071e422010-08-15 06:18:01 +00003001 bool alreadyVisitedContext(DeclContext *Ctx) {
3002 return VisitedContexts.count(Ctx);
3003 }
3004
Douglas Gregor546be3c2009-12-30 17:04:44 +00003005 /// \brief Determine whether the given declaration is hidden in the
3006 /// current scope.
3007 ///
3008 /// \returns the declaration that hides the given declaration, or
3009 /// NULL if no such declaration exists.
3010 NamedDecl *checkHidden(NamedDecl *ND);
3011
3012 /// \brief Add a declaration to the current shadow map.
Chris Lattnerb5f65472011-07-18 01:54:02 +00003013 void add(NamedDecl *ND) {
3014 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
3015 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003016};
3017
3018/// \brief RAII object that records when we've entered a shadow context.
3019class ShadowContextRAII {
3020 VisibleDeclsRecord &Visible;
3021
3022 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
3023
3024public:
3025 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
3026 Visible.ShadowMaps.push_back(ShadowMap());
3027 }
3028
3029 ~ShadowContextRAII() {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003030 Visible.ShadowMaps.pop_back();
3031 }
3032};
3033
3034} // end anonymous namespace
3035
Douglas Gregor546be3c2009-12-30 17:04:44 +00003036NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00003037 // Look through using declarations.
3038 ND = ND->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003039
Douglas Gregor546be3c2009-12-30 17:04:44 +00003040 unsigned IDNS = ND->getIdentifierNamespace();
3041 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
3042 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3043 SM != SMEnd; ++SM) {
3044 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
3045 if (Pos == SM->end())
3046 continue;
3047
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003048 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor546be3c2009-12-30 17:04:44 +00003049 IEnd = Pos->second.end();
3050 I != IEnd; ++I) {
3051 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00003052 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003053 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor546be3c2009-12-30 17:04:44 +00003054 Decl::IDNS_ObjCProtocol)))
3055 continue;
3056
3057 // Protocols are in distinct namespaces from everything else.
3058 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
3059 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
3060 (*I)->getIdentifierNamespace() != IDNS)
3061 continue;
3062
Douglas Gregor0cc84042010-01-14 15:47:35 +00003063 // Functions and function templates in the same scope overload
3064 // rather than hide. FIXME: Look for hiding based on function
3065 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00003066 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00003067 ND->isFunctionOrFunctionTemplate() &&
3068 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00003069 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003070
Douglas Gregor546be3c2009-12-30 17:04:44 +00003071 // We've found a declaration that hides this one.
3072 return *I;
3073 }
3074 }
3075
3076 return 0;
3077}
3078
3079static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
3080 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003081 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00003082 VisibleDeclConsumer &Consumer,
3083 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00003084 if (!Ctx)
3085 return;
3086
Douglas Gregor546be3c2009-12-30 17:04:44 +00003087 // Make sure we don't visit the same context twice.
3088 if (Visited.visitedContext(Ctx->getPrimaryContext()))
3089 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003090
Douglas Gregor4923aa22010-07-02 20:37:36 +00003091 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3092 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3093
Douglas Gregor546be3c2009-12-30 17:04:44 +00003094 // Enumerate all of the results in this context.
Nick Lewycky173a37a2012-04-03 21:44:08 +00003095 for (DeclContext::all_lookups_iterator L = Ctx->lookups_begin(),
3096 LEnd = Ctx->lookups_end();
3097 L != LEnd; ++L) {
David Blaikie3bc93e32012-12-19 00:45:41 +00003098 DeclContext::lookup_result R = *L;
3099 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
3100 ++I) {
3101 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) {
Douglas Gregor55368912011-12-14 16:03:29 +00003102 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00003103 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003104 Visited.add(ND);
3105 }
Douglas Gregor70c23352010-12-09 21:44:02 +00003106 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003107 }
3108 }
3109
3110 // Traverse using directives for qualified name lookup.
3111 if (QualifiedNameLookup) {
3112 ShadowContextRAII Shadow(Visited);
3113 DeclContext::udir_iterator I, E;
3114 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003115 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003116 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003117 }
3118 }
3119
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003120 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003121 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00003122 if (!Record->hasDefinition())
3123 return;
3124
Douglas Gregor546be3c2009-12-30 17:04:44 +00003125 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
3126 BEnd = Record->bases_end();
3127 B != BEnd; ++B) {
3128 QualType BaseType = B->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003129
Douglas Gregor546be3c2009-12-30 17:04:44 +00003130 // Don't look into dependent bases, because name lookup can't look
3131 // there anyway.
3132 if (BaseType->isDependentType())
3133 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003134
Douglas Gregor546be3c2009-12-30 17:04:44 +00003135 const RecordType *Record = BaseType->getAs<RecordType>();
3136 if (!Record)
3137 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003138
Douglas Gregor546be3c2009-12-30 17:04:44 +00003139 // FIXME: It would be nice to be able to determine whether referencing
3140 // a particular member would be ambiguous. For example, given
3141 //
3142 // struct A { int member; };
3143 // struct B { int member; };
3144 // struct C : A, B { };
3145 //
3146 // void f(C *c) { c->### }
3147 //
3148 // accessing 'member' would result in an ambiguity. However, we
3149 // could be smart enough to qualify the member with the base
3150 // class, e.g.,
3151 //
3152 // c->B::member
3153 //
3154 // or
3155 //
3156 // c->A::member
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003157
Douglas Gregor546be3c2009-12-30 17:04:44 +00003158 // Find results in this base class (and its bases).
3159 ShadowContextRAII Shadow(Visited);
3160 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003161 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003162 }
3163 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003164
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003165 // Traverse the contexts of Objective-C classes.
3166 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3167 // Traverse categories.
Douglas Gregord3297242013-01-16 23:00:23 +00003168 for (ObjCInterfaceDecl::visible_categories_iterator
3169 Cat = IFace->visible_categories_begin(),
3170 CatEnd = IFace->visible_categories_end();
3171 Cat != CatEnd; ++Cat) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003172 ShadowContextRAII Shadow(Visited);
Douglas Gregord3297242013-01-16 23:00:23 +00003173 LookupVisibleDecls(*Cat, Result, QualifiedNameLookup, false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003174 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003175 }
3176
3177 // Traverse protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003178 for (ObjCInterfaceDecl::all_protocol_iterator
3179 I = IFace->all_referenced_protocol_begin(),
3180 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003181 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003182 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003183 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003184 }
3185
3186 // Traverse the superclass.
3187 if (IFace->getSuperClass()) {
3188 ShadowContextRAII Shadow(Visited);
3189 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003190 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003191 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003192
Douglas Gregorc220a182010-04-19 18:02:19 +00003193 // If there is an implementation, traverse it. We do this to find
3194 // synthesized ivars.
3195 if (IFace->getImplementation()) {
3196 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003197 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky893a6ea2012-04-03 20:26:45 +00003198 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregorc220a182010-04-19 18:02:19 +00003199 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003200 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
3201 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
3202 E = Protocol->protocol_end(); I != E; ++I) {
3203 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003204 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003205 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003206 }
3207 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
3208 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
3209 E = Category->protocol_end(); I != E; ++I) {
3210 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003211 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003212 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003213 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003214
Douglas Gregorc220a182010-04-19 18:02:19 +00003215 // If there is an implementation, traverse it.
3216 if (Category->getImplementation()) {
3217 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003218 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregorc220a182010-04-19 18:02:19 +00003219 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003220 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003221 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003222}
3223
3224static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3225 UnqualUsingDirectiveSet &UDirs,
3226 VisibleDeclConsumer &Consumer,
3227 VisibleDeclsRecord &Visited) {
3228 if (!S)
3229 return;
3230
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003231 if (!S->getEntity() ||
3232 (!S->getParent() &&
Ted Kremenekf0d58612013-10-08 17:08:03 +00003233 !Visited.alreadyVisitedContext(S->getEntity())) ||
3234 (S->getEntity())->isFunctionOrMethod()) {
Richard Smitha41c97a2013-09-20 01:15:31 +00003235 FindLocalExternScope FindLocals(Result);
Douglas Gregor539c5c32010-01-07 00:31:29 +00003236 // Walk through the declarations in this Scope.
3237 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
3238 D != DEnd; ++D) {
John McCalld226f652010-08-21 09:40:31 +00003239 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor55368912011-12-14 16:03:29 +00003240 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggend1205962011-10-06 07:27:49 +00003241 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00003242 Visited.add(ND);
3243 }
3244 }
3245 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003246
Douglas Gregor711be1e2010-03-15 14:33:29 +00003247 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00003248 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00003249 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003250 // Look into this scope's declaration context, along with any of its
3251 // parent lookup contexts (e.g., enclosing classes), up to the point
3252 // where we hit the context stored in the next outer scope.
Ted Kremenekf0d58612013-10-08 17:08:03 +00003253 Entity = S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00003254 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003255
Douglas Gregordbdf5e72010-03-15 15:26:48 +00003256 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003257 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003258 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3259 if (Method->isInstanceMethod()) {
3260 // For instance methods, look for ivars in the method's interface.
3261 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3262 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregorca45da02010-11-02 20:36:02 +00003263 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003264 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Richard Smithd67679d2013-08-20 20:35:18 +00003265 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorca45da02010-11-02 20:36:02 +00003266 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003267 }
3268
3269 // We've already performed all of the name lookup that we need
3270 // to for Objective-C methods; the next context will be the
3271 // outer scope.
3272 break;
3273 }
3274
Douglas Gregor546be3c2009-12-30 17:04:44 +00003275 if (Ctx->isFunctionOrMethod())
3276 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003277
3278 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003279 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003280 }
3281 } else if (!S->getParent()) {
3282 // Look into the translation unit scope. We walk through the translation
3283 // unit's declaration context, because the Scope itself won't have all of
3284 // the declarations if we loaded a precompiled header.
3285 // FIXME: We would like the translation unit's Scope object to point to the
3286 // translation unit, so we don't need this special "if" branch. However,
3287 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003288 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003289 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00003290 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003291 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003292 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003293 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003294 }
3295
Douglas Gregor546be3c2009-12-30 17:04:44 +00003296 if (Entity) {
3297 // Lookup visible declarations in any namespaces found by using
3298 // directives.
3299 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
3300 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
3301 for (; UI != UEnd; ++UI)
3302 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003303 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003304 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003305 }
3306
3307 // Lookup names in the parent scope.
3308 ShadowContextRAII Shadow(Visited);
3309 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3310}
3311
3312void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00003313 VisibleDeclConsumer &Consumer,
3314 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003315 // Determine the set of using directives available during
3316 // unqualified name lookup.
3317 Scope *Initial = S;
3318 UnqualUsingDirectiveSet UDirs;
David Blaikie4e4d0842012-03-11 07:00:24 +00003319 if (getLangOpts().CPlusPlus) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003320 // Find the first namespace or translation-unit scope.
3321 while (S && !isNamespaceOrTranslationUnitScope(S))
3322 S = S->getParent();
3323
3324 UDirs.visitScopeChain(Initial, S);
3325 }
3326 UDirs.done();
3327
3328 // Look for visible declarations.
3329 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithd67679d2013-08-20 20:35:18 +00003330 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003331 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003332 if (!IncludeGlobalScope)
3333 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003334 ShadowContextRAII Shadow(Visited);
3335 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3336}
3337
3338void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00003339 VisibleDeclConsumer &Consumer,
3340 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003341 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithd67679d2013-08-20 20:35:18 +00003342 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003343 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00003344 if (!IncludeGlobalScope)
3345 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00003346 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003347 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor0cc84042010-01-14 15:47:35 +00003348 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003349}
3350
Chris Lattner4ae493c2011-02-18 02:08:43 +00003351/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara67843042011-03-05 18:21:20 +00003352/// If GnuLabelLoc is a valid source location, then this is a definition
3353/// of an __label__ label name, otherwise it is a normal label definition
3354/// or use.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003355LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara67843042011-03-05 18:21:20 +00003356 SourceLocation GnuLabelLoc) {
Chris Lattner337e5502011-02-18 01:27:55 +00003357 // Do a lookup to see if we have a label with this name already.
Chris Lattner4ae493c2011-02-18 02:08:43 +00003358 NamedDecl *Res = 0;
Abramo Bagnara67843042011-03-05 18:21:20 +00003359
3360 if (GnuLabelLoc.isValid()) {
3361 // Local label definitions always shadow existing labels.
3362 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3363 Scope *S = CurScope;
3364 PushOnScopeChains(Res, S, true);
3365 return cast<LabelDecl>(Res);
3366 }
3367
3368 // Not a GNU local label.
3369 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3370 // If we found a label, check to see if it is in the same context as us.
3371 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattner337e5502011-02-18 01:27:55 +00003372 if (Res && Res->getDeclContext() != CurContext)
3373 Res = 0;
Chris Lattner337e5502011-02-18 01:27:55 +00003374 if (Res == 0) {
3375 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara67843042011-03-05 18:21:20 +00003376 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3377 Scope *S = CurScope->getFnParent();
Chris Lattnerfebb5b82011-02-18 21:16:39 +00003378 assert(S && "Not in a function?");
3379 PushOnScopeChains(Res, S, true);
Chris Lattner337e5502011-02-18 01:27:55 +00003380 }
Chris Lattner337e5502011-02-18 01:27:55 +00003381 return cast<LabelDecl>(Res);
3382}
3383
3384//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003385// Typo correction
Chris Lattner337e5502011-02-18 01:27:55 +00003386//===----------------------------------------------------------------------===//
Douglas Gregor546be3c2009-12-30 17:04:44 +00003387
3388namespace {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003389
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003390typedef SmallVector<TypoCorrection, 1> TypoResultList;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003391typedef llvm::StringMap<TypoResultList, llvm::BumpPtrAllocator> TypoResultsMap;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00003392typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003393
3394static const unsigned MaxTypoDistanceResultSets = 5;
3395
Douglas Gregor546be3c2009-12-30 17:04:44 +00003396class TypoCorrectionConsumer : public VisibleDeclConsumer {
3397 /// \brief The name written that is a typo in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003398 StringRef Typo;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003399
3400 /// \brief The results found that have the smallest edit distance
3401 /// found (so far) with the typo name.
Douglas Gregore24b5752010-10-14 20:34:08 +00003402 ///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003403 /// The pointer value being set to the current DeclContext indicates
3404 /// whether there is a keyword with this name.
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003405 TypoEditDistanceMap CorrectionResults;
Douglas Gregor546be3c2009-12-30 17:04:44 +00003406
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003407 Sema &SemaRef;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003408
Douglas Gregor546be3c2009-12-30 17:04:44 +00003409public:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003410 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003411 : Typo(Typo->getName()),
Richard Smithd67679d2013-08-20 20:35:18 +00003412 SemaRef(SemaRef) {}
3413
3414 bool includeHiddenDecls() const { return true; }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003415
Erik Verbruggend1205962011-10-06 07:27:49 +00003416 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3417 bool InBaseClass);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003418 void FoundName(StringRef Name);
3419 void addKeywordResult(StringRef Keyword);
Kaelyn Uhrainfb61e462013-10-02 18:26:35 +00003420 void addName(StringRef Name, NamedDecl *ND, NestedNameSpecifier *NNS = NULL,
3421 bool isKeyword = false);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003422 void addCorrection(TypoCorrection Correction);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003423
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003424 typedef TypoResultsMap::iterator result_iterator;
3425 typedef TypoEditDistanceMap::iterator distance_iterator;
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003426 distance_iterator begin() { return CorrectionResults.begin(); }
3427 distance_iterator end() { return CorrectionResults.end(); }
3428 void erase(distance_iterator I) { CorrectionResults.erase(I); }
3429 unsigned size() const { return CorrectionResults.size(); }
3430 bool empty() const { return CorrectionResults.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003431
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003432 TypoResultList &operator[](StringRef Name) {
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003433 return CorrectionResults.begin()->second[Name];
Douglas Gregor7b824e82010-10-15 13:35:25 +00003434 }
3435
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003436 unsigned getBestEditDistance(bool Normalized) {
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003437 if (CorrectionResults.empty())
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003438 return (std::numeric_limits<unsigned>::max)();
3439
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003440 unsigned BestED = CorrectionResults.begin()->first;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003441 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003442 }
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003443
3444 TypoResultsMap &getBestResults() {
3445 return CorrectionResults.begin()->second;
3446 }
3447
Douglas Gregor546be3c2009-12-30 17:04:44 +00003448};
3449
3450}
3451
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003452void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggend1205962011-10-06 07:27:49 +00003453 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00003454 // Don't consider hidden names for typo correction.
3455 if (Hiding)
3456 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003457
Douglas Gregor546be3c2009-12-30 17:04:44 +00003458 // Only consider entities with identifiers for names, ignoring
3459 // special names (constructors, overloaded operators, selectors,
3460 // etc.).
3461 IdentifierInfo *Name = ND->getIdentifier();
3462 if (!Name)
3463 return;
3464
Richard Smithd67679d2013-08-20 20:35:18 +00003465 // Only consider visible declarations and declarations from modules with
3466 // names that exactly match.
3467 if (!LookupResult::isVisible(SemaRef, ND) && Name->getName() != Typo &&
3468 !findAcceptableDecl(SemaRef, ND))
3469 return;
3470
Douglas Gregor95f42922010-10-14 22:11:03 +00003471 FoundName(Name->getName());
3472}
3473
Chris Lattner5f9e2722011-07-23 10:55:15 +00003474void TypoCorrectionConsumer::FoundName(StringRef Name) {
Kaelyn Uhrainfb61e462013-10-02 18:26:35 +00003475 // Compute the edit distance between the typo and the name of this
3476 // entity, and add the identifier to the list of results.
3477 addName(Name, NULL);
3478}
3479
3480void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3481 // Compute the edit distance between the typo and this keyword,
3482 // and add the keyword to the list of results.
3483 addName(Keyword, NULL, NULL, true);
3484}
3485
3486void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
3487 NestedNameSpecifier *NNS, bool isKeyword) {
Douglas Gregor362a8f22010-10-19 19:39:10 +00003488 // Use a simple length-based heuristic to determine the minimum possible
3489 // edit distance. If the minimum isn't good enough, bail out early.
3490 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00003491 if (MinED && Typo.size() / MinED < 3)
Douglas Gregor362a8f22010-10-19 19:39:10 +00003492 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003493
Douglas Gregora1194772010-10-19 22:14:33 +00003494 // Compute an upper bound on the allowable edit distance, so that the
3495 // edit-distance algorithm can short-circuit.
Kaelyn Uhrainfb61e462013-10-02 18:26:35 +00003496 unsigned UpperBound = (Typo.size() + 2) / 3 + 1;
3497 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
3498 if (ED >= UpperBound) return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003499
Kaelyn Uhrainfb61e462013-10-02 18:26:35 +00003500 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00003501 if (isKeyword) TC.makeKeyword();
3502 addCorrection(TC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003503}
3504
3505void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003506 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003507 TypoResultList &CList =
3508 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth55620532011-06-28 22:48:40 +00003509
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00003510 if (!CList.empty() && !CList.back().isResolved())
3511 CList.pop_back();
3512 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3513 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3514 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3515 RI != RIEnd; ++RI) {
3516 // If the Correction refers to a decl already in the result list,
3517 // replace the existing result if the string representation of Correction
3518 // comes before the current result alphabetically, then stop as there is
3519 // nothing more to be done to add Correction to the candidate set.
3520 if (RI->getCorrectionDecl() == NewND) {
3521 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3522 *RI = Correction;
3523 return;
3524 }
3525 }
3526 }
3527 if (CList.empty() || Correction.isResolved())
3528 CList.push_back(Correction);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003529
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00003530 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
3531 erase(llvm::prior(CorrectionResults.end()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003532}
3533
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003534// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3535// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3536// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3537static void getNestedNameSpecifierIdentifiers(
3538 NestedNameSpecifier *NNS,
3539 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3540 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3541 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3542 else
3543 Identifiers.clear();
3544
3545 const IdentifierInfo *II = NULL;
3546
3547 switch (NNS->getKind()) {
3548 case NestedNameSpecifier::Identifier:
3549 II = NNS->getAsIdentifier();
3550 break;
3551
3552 case NestedNameSpecifier::Namespace:
3553 if (NNS->getAsNamespace()->isAnonymousNamespace())
3554 return;
3555 II = NNS->getAsNamespace()->getIdentifier();
3556 break;
3557
3558 case NestedNameSpecifier::NamespaceAlias:
3559 II = NNS->getAsNamespaceAlias()->getIdentifier();
3560 break;
3561
3562 case NestedNameSpecifier::TypeSpecWithTemplate:
3563 case NestedNameSpecifier::TypeSpec:
3564 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3565 break;
3566
3567 case NestedNameSpecifier::Global:
3568 return;
3569 }
3570
3571 if (II)
3572 Identifiers.push_back(II);
3573}
3574
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003575namespace {
3576
3577class SpecifierInfo {
3578 public:
3579 DeclContext* DeclCtx;
3580 NestedNameSpecifier* NameSpecifier;
3581 unsigned EditDistance;
3582
3583 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3584 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3585};
3586
Chris Lattner5f9e2722011-07-23 10:55:15 +00003587typedef SmallVector<DeclContext*, 4> DeclContextList;
3588typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003589
3590class NamespaceSpecifierSet {
3591 ASTContext &Context;
3592 DeclContextList CurContextChain;
Kaelyn Uhrain6e4f6f82013-10-19 00:04:52 +00003593 std::string CurNameSpecifier;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003594 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3595 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003596 bool isSorted;
3597
3598 SpecifierInfoList Specifiers;
3599 llvm::SmallSetVector<unsigned, 4> Distances;
3600 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3601
3602 /// \brief Helper for building the list of DeclContexts between the current
3603 /// context and the top of the translation unit
3604 static DeclContextList BuildContextChain(DeclContext *Start);
3605
3606 void SortNamespaces();
3607
3608 public:
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003609 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3610 CXXScopeSpec *CurScopeSpec)
Benjamin Kramerc5bb9d42011-07-05 09:46:31 +00003611 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
Kaelyn Uhrain8d90b4a2013-06-24 17:49:03 +00003612 isSorted(false) {
Kaelyn Uhrain6e4f6f82013-10-19 00:04:52 +00003613 if (NestedNameSpecifier *NNS =
3614 CurScopeSpec ? CurScopeSpec->getScopeRep() : 0) {
3615 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
3616 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3617
3618 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
3619 }
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003620 // Build the list of identifiers that would be used for an absolute
Benjamin Kramer48d798c2012-06-02 10:20:41 +00003621 // (from the global context) NestedNameSpecifier referring to the current
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003622 // context.
3623 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3624 CEnd = CurContextChain.rend();
3625 C != CEnd; ++C) {
3626 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3627 CurContextIdentifiers.push_back(ND->getIdentifier());
3628 }
Kaelyn Uhrain8d90b4a2013-06-24 17:49:03 +00003629
3630 // Add the global context as a NestedNameSpecifier
3631 Distances.insert(1);
3632 DistanceMap[1].push_back(
3633 SpecifierInfo(cast<DeclContext>(Context.getTranslationUnitDecl()),
3634 NestedNameSpecifier::GlobalSpecifier(Context), 1));
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00003635 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003636
Kaelyn Uhraina831f172013-10-19 00:04:49 +00003637 /// \brief Add the DeclContext (a namespace or record) to the set, computing
3638 /// the corresponding NestedNameSpecifier and its distance in the process.
3639 void AddNameSpecifier(DeclContext *Ctx);
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00003640
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003641 typedef SpecifierInfoList::iterator iterator;
3642 iterator begin() {
3643 if (!isSorted) SortNamespaces();
3644 return Specifiers.begin();
3645 }
3646 iterator end() { return Specifiers.end(); }
3647};
3648
3649}
3650
3651DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Nick Lewycky0db9d202013-04-08 21:55:21 +00003652 assert(Start && "Building a context chain from a null context");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003653 DeclContextList Chain;
3654 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3655 DC = DC->getLookupParent()) {
3656 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3657 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3658 !(ND && ND->isAnonymousNamespace()))
3659 Chain.push_back(DC->getPrimaryContext());
3660 }
3661 return Chain;
3662}
3663
3664void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003665 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003666 sortedDistances.append(Distances.begin(), Distances.end());
3667
3668 if (sortedDistances.size() > 1)
3669 std::sort(sortedDistances.begin(), sortedDistances.end());
3670
3671 Specifiers.clear();
Craig Topper09d19ef2013-07-04 03:08:24 +00003672 for (SmallVectorImpl<unsigned>::iterator DI = sortedDistances.begin(),
3673 DIEnd = sortedDistances.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003674 DI != DIEnd; ++DI) {
3675 SpecifierInfoList &SpecList = DistanceMap[*DI];
3676 Specifiers.append(SpecList.begin(), SpecList.end());
3677 }
3678
3679 isSorted = true;
3680}
3681
Kaelyn Uhrain6e4f6f82013-10-19 00:04:52 +00003682static unsigned BuildNestedNameSpecifier(ASTContext &Context,
3683 DeclContextList &DeclChain,
3684 NestedNameSpecifier *&NNS) {
3685 unsigned NumSpecifiers = 0;
3686 for (DeclContextList::reverse_iterator C = DeclChain.rbegin(),
3687 CEnd = DeclChain.rend();
3688 C != CEnd; ++C) {
3689 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) {
3690 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3691 ++NumSpecifiers;
3692 } else if (RecordDecl *RD = dyn_cast_or_null<RecordDecl>(*C)) {
3693 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
3694 RD->getTypeForDecl());
3695 ++NumSpecifiers;
3696 }
3697 }
3698 return NumSpecifiers;
3699}
3700
Kaelyn Uhraina831f172013-10-19 00:04:49 +00003701void NamespaceSpecifierSet::AddNameSpecifier(DeclContext *Ctx) {
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00003702 NestedNameSpecifier *NNS = NULL;
3703 unsigned NumSpecifiers = 0;
3704 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
3705 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
3706
3707 // Eliminate common elements from the two DeclContext chains.
3708 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3709 CEnd = CurContextChain.rend();
3710 C != CEnd && !NamespaceDeclChain.empty() &&
3711 NamespaceDeclChain.back() == *C; ++C) {
3712 NamespaceDeclChain.pop_back();
3713 }
3714
Kaelyn Uhrain6e4f6f82013-10-19 00:04:52 +00003715 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3716 NumSpecifiers = BuildNestedNameSpecifier(Context, NamespaceDeclChain, NNS);
3717
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00003718 // Add an explicit leading '::' specifier if needed.
3719 if (NamespaceDeclChain.empty()) {
Kaelyn Uhrain6e4f6f82013-10-19 00:04:52 +00003720 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00003721 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
Kaelyn Uhrain6e4f6f82013-10-19 00:04:52 +00003722 NumSpecifiers =
3723 BuildNestedNameSpecifier(Context, FullNamespaceDeclChain, NNS);
Kaelyn Uhrainfb61e462013-10-02 18:26:35 +00003724 } else if (NamedDecl *ND =
3725 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00003726 IdentifierInfo *Name = ND->getIdentifier();
Kaelyn Uhrain6e4f6f82013-10-19 00:04:52 +00003727 bool SameNameSpecifier = false;
3728 if (std::find(CurNameSpecifierIdentifiers.begin(),
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00003729 CurNameSpecifierIdentifiers.end(),
3730 Name) != CurNameSpecifierIdentifiers.end()) {
Kaelyn Uhrain6e4f6f82013-10-19 00:04:52 +00003731 std::string NewNameSpecifier;
3732 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
3733 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
3734 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3735 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3736 SpecifierOStream.flush();
3737 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00003738 }
Kaelyn Uhrain6e4f6f82013-10-19 00:04:52 +00003739 if (SameNameSpecifier ||
3740 std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3741 Name) != CurContextIdentifiers.end()) {
3742 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
3743 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3744 NumSpecifiers =
3745 BuildNestedNameSpecifier(Context, FullNamespaceDeclChain, NNS);
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00003746 }
3747 }
3748
3749 // If the built NestedNameSpecifier would be replacing an existing
3750 // NestedNameSpecifier, use the number of component identifiers that
3751 // would need to be changed as the edit distance instead of the number
3752 // of components in the built NestedNameSpecifier.
3753 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3754 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3755 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3756 NumSpecifiers = llvm::ComputeEditDistance(
3757 ArrayRef<const IdentifierInfo *>(CurNameSpecifierIdentifiers),
3758 ArrayRef<const IdentifierInfo *>(NewNameSpecifierIdentifiers));
3759 }
3760
3761 isSorted = false;
3762 Distances.insert(NumSpecifiers);
3763 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
3764}
3765
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003766/// \brief Perform name lookup for a possible result for typo correction.
3767static void LookupPotentialTypoResult(Sema &SemaRef,
3768 LookupResult &Res,
3769 IdentifierInfo *Name,
3770 Scope *S, CXXScopeSpec *SS,
3771 DeclContext *MemberContext,
3772 bool EnteringContext,
Richard Smithd67679d2013-08-20 20:35:18 +00003773 bool isObjCIvarLookup,
3774 bool FindHidden) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003775 Res.suppressDiagnostics();
3776 Res.clear();
3777 Res.setLookupName(Name);
Richard Smithd67679d2013-08-20 20:35:18 +00003778 Res.setAllowHidden(FindHidden);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003779 if (MemberContext) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003780 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003781 if (isObjCIvarLookup) {
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003782 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3783 Res.addDecl(Ivar);
3784 Res.resolveKind();
3785 return;
3786 }
3787 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003788
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003789 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3790 Res.addDecl(Prop);
3791 Res.resolveKind();
3792 return;
3793 }
3794 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003795
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003796 SemaRef.LookupQualifiedName(Res, MemberContext);
3797 return;
3798 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003799
3800 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003801 EnteringContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003802
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003803 // Fake ivar lookup; this should really be part of
3804 // LookupParsedName.
3805 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3806 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003807 (Res.empty() ||
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003808 (Res.isSingleResult() &&
3809 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003810 if (ObjCIvarDecl *IV
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003811 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3812 Res.addDecl(IV);
3813 Res.resolveKind();
3814 }
3815 }
3816 }
3817}
3818
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003819/// \brief Add keywords to the consumer as possible typo corrections.
3820static void AddKeywordsToConsumer(Sema &SemaRef,
3821 TypoCorrectionConsumer &Consumer,
Richard Smith0f4b5be2012-06-08 21:35:42 +00003822 Scope *S, CorrectionCandidateCallback &CCC,
3823 bool AfterNestedNameSpecifier) {
3824 if (AfterNestedNameSpecifier) {
3825 // For 'X::', we know exactly which keywords can appear next.
3826 Consumer.addKeywordResult("template");
3827 if (CCC.WantExpressionKeywords)
3828 Consumer.addKeywordResult("operator");
3829 return;
3830 }
3831
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003832 if (CCC.WantObjCSuper)
3833 Consumer.addKeywordResult("super");
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003834
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003835 if (CCC.WantTypeSpecifiers) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003836 // Add type-specifier keywords to the set of results.
Craig Topper3aa29df2013-07-15 08:24:27 +00003837 static const char *const CTypeSpecs[] = {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003838 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor07f4a062011-07-01 21:27:45 +00003839 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003840 "_Complex", "_Imaginary",
3841 // storage-specifiers as well
3842 "extern", "inline", "static", "typedef"
3843 };
3844
Craig Topperb9602322013-07-15 03:38:40 +00003845 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003846 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3847 Consumer.addKeywordResult(CTypeSpecs[I]);
3848
David Blaikie4e4d0842012-03-11 07:00:24 +00003849 if (SemaRef.getLangOpts().C99)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003850 Consumer.addKeywordResult("restrict");
David Blaikie4e4d0842012-03-11 07:00:24 +00003851 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003852 Consumer.addKeywordResult("bool");
David Blaikie4e4d0842012-03-11 07:00:24 +00003853 else if (SemaRef.getLangOpts().C99)
Douglas Gregor07f4a062011-07-01 21:27:45 +00003854 Consumer.addKeywordResult("_Bool");
3855
David Blaikie4e4d0842012-03-11 07:00:24 +00003856 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003857 Consumer.addKeywordResult("class");
3858 Consumer.addKeywordResult("typename");
3859 Consumer.addKeywordResult("wchar_t");
3860
Richard Smith80ad52f2013-01-02 11:42:31 +00003861 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003862 Consumer.addKeywordResult("char16_t");
3863 Consumer.addKeywordResult("char32_t");
3864 Consumer.addKeywordResult("constexpr");
3865 Consumer.addKeywordResult("decltype");
3866 Consumer.addKeywordResult("thread_local");
3867 }
3868 }
3869
David Blaikie4e4d0842012-03-11 07:00:24 +00003870 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003871 Consumer.addKeywordResult("typeof");
3872 }
3873
David Blaikie4e4d0842012-03-11 07:00:24 +00003874 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003875 Consumer.addKeywordResult("const_cast");
3876 Consumer.addKeywordResult("dynamic_cast");
3877 Consumer.addKeywordResult("reinterpret_cast");
3878 Consumer.addKeywordResult("static_cast");
3879 }
3880
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003881 if (CCC.WantExpressionKeywords) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003882 Consumer.addKeywordResult("sizeof");
David Blaikie4e4d0842012-03-11 07:00:24 +00003883 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003884 Consumer.addKeywordResult("false");
3885 Consumer.addKeywordResult("true");
3886 }
3887
David Blaikie4e4d0842012-03-11 07:00:24 +00003888 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topper3aa29df2013-07-15 08:24:27 +00003889 static const char *const CXXExprs[] = {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003890 "delete", "new", "operator", "throw", "typeid"
3891 };
Craig Topperb9602322013-07-15 03:38:40 +00003892 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003893 for (unsigned I = 0; I != NumCXXExprs; ++I)
3894 Consumer.addKeywordResult(CXXExprs[I]);
3895
3896 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3897 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3898 Consumer.addKeywordResult("this");
3899
Richard Smith80ad52f2013-01-02 11:42:31 +00003900 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003901 Consumer.addKeywordResult("alignof");
3902 Consumer.addKeywordResult("nullptr");
3903 }
3904 }
Jordan Rosef70a8862012-06-30 21:33:57 +00003905
3906 if (SemaRef.getLangOpts().C11) {
3907 // FIXME: We should not suggest _Alignof if the alignof macro
3908 // is present.
3909 Consumer.addKeywordResult("_Alignof");
3910 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003911 }
3912
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00003913 if (CCC.WantRemainingKeywords) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003914 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3915 // Statements.
Craig Topper3aa29df2013-07-15 08:24:27 +00003916 static const char *const CStmts[] = {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003917 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Topperb9602322013-07-15 03:38:40 +00003918 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003919 for (unsigned I = 0; I != NumCStmts; ++I)
3920 Consumer.addKeywordResult(CStmts[I]);
3921
David Blaikie4e4d0842012-03-11 07:00:24 +00003922 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003923 Consumer.addKeywordResult("catch");
3924 Consumer.addKeywordResult("try");
3925 }
3926
3927 if (S && S->getBreakParent())
3928 Consumer.addKeywordResult("break");
3929
3930 if (S && S->getContinueParent())
3931 Consumer.addKeywordResult("continue");
3932
3933 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3934 Consumer.addKeywordResult("case");
3935 Consumer.addKeywordResult("default");
3936 }
3937 } else {
David Blaikie4e4d0842012-03-11 07:00:24 +00003938 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003939 Consumer.addKeywordResult("namespace");
3940 Consumer.addKeywordResult("template");
3941 }
3942
3943 if (S && S->isClassScope()) {
3944 Consumer.addKeywordResult("explicit");
3945 Consumer.addKeywordResult("friend");
3946 Consumer.addKeywordResult("mutable");
3947 Consumer.addKeywordResult("private");
3948 Consumer.addKeywordResult("protected");
3949 Consumer.addKeywordResult("public");
3950 Consumer.addKeywordResult("virtual");
3951 }
3952 }
3953
David Blaikie4e4d0842012-03-11 07:00:24 +00003954 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003955 Consumer.addKeywordResult("using");
3956
Richard Smith80ad52f2013-01-02 11:42:31 +00003957 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003958 Consumer.addKeywordResult("static_assert");
3959 }
3960 }
3961}
3962
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00003963static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3964 TypoCorrection &Candidate) {
3965 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3966 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3967}
3968
Richard Smithd67679d2013-08-20 20:35:18 +00003969/// \brief Check whether the declarations found for a typo correction are
3970/// visible, and if none of them are, convert the correction to an 'import
3971/// a module' correction.
3972static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC,
3973 DeclarationName TypoName) {
3974 if (TC.begin() == TC.end())
3975 return;
3976
3977 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3978
3979 for (/**/; DI != DE; ++DI)
3980 if (!LookupResult::isVisible(SemaRef, *DI))
3981 break;
3982 // Nothing to do if all decls are visible.
3983 if (DI == DE)
3984 return;
3985
3986 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3987 bool AnyVisibleDecls = !NewDecls.empty();
3988
3989 for (/**/; DI != DE; ++DI) {
3990 NamedDecl *VisibleDecl = *DI;
3991 if (!LookupResult::isVisible(SemaRef, *DI))
3992 VisibleDecl = findAcceptableDecl(SemaRef, *DI);
3993
3994 if (VisibleDecl) {
3995 if (!AnyVisibleDecls) {
3996 // Found a visible decl, discard all hidden ones.
3997 AnyVisibleDecls = true;
3998 NewDecls.clear();
3999 }
4000 NewDecls.push_back(VisibleDecl);
4001 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
4002 NewDecls.push_back(*DI);
4003 }
4004
4005 if (NewDecls.empty())
4006 TC = TypoCorrection();
4007 else {
4008 TC.setCorrectionDecls(NewDecls);
4009 TC.setRequiresImport(!AnyVisibleDecls);
4010 }
4011}
4012
Douglas Gregor546be3c2009-12-30 17:04:44 +00004013/// \brief Try to "correct" a typo in the source code by finding
4014/// visible declarations whose names are similar to the name that was
4015/// present in the source code.
4016///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004017/// \param TypoName the \c DeclarationNameInfo structure that contains
4018/// the name that was present in the source code along with its location.
4019///
4020/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor546be3c2009-12-30 17:04:44 +00004021///
4022/// \param S the scope in which name lookup occurs.
4023///
4024/// \param SS the nested-name-specifier that precedes the name we're
4025/// looking for, if present.
4026///
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004027/// \param CCC A CorrectionCandidateCallback object that provides further
4028/// validation of typo correction candidates. It also provides flags for
4029/// determining the set of keywords permitted.
4030///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00004031/// \param MemberContext if non-NULL, the context in which to look for
4032/// a member access expression.
4033///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004034/// \param EnteringContext whether we're entering the context described by
Douglas Gregorbb092ba2009-12-31 05:20:13 +00004035/// the nested-name-specifier SS.
4036///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00004037/// \param OPT when non-NULL, the search for visible declarations will
4038/// also walk the protocols in the qualified interfaces of \p OPT.
4039///
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004040/// \returns a \c TypoCorrection containing the corrected name if the typo
4041/// along with information such as the \c NamedDecl where the corrected name
4042/// was declared, and any additional \c NestedNameSpecifier needed to access
4043/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
4044TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
4045 Sema::LookupNameKind LookupKind,
4046 Scope *S, CXXScopeSpec *SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00004047 CorrectionCandidateCallback &CCC,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004048 DeclContext *MemberContext,
4049 bool EnteringContext,
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004050 const ObjCObjectPointerType *OPT,
4051 bool RecordFailure) {
Kaelyn Uhrain70571f42013-08-12 19:54:38 +00004052 // Always let the ExternalSource have the first chance at correction, even
4053 // if we would otherwise have given up.
4054 if (ExternalSource) {
4055 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
4056 TypoName, LookupKind, S, SS, CCC, MemberContext, EnteringContext, OPT))
4057 return Correction;
4058 }
4059
Richard Smith9bd3cdc2013-09-12 23:28:08 +00004060 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4061 DisableTypoCorrection)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004062 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004063
Francois Pichet4d604d62011-12-03 15:55:29 +00004064 // In Microsoft mode, don't perform typo correction in a template member
4065 // function dependent context because it interferes with the "lookup into
4066 // dependent bases of class templates" feature.
David Blaikie4e4d0842012-03-11 07:00:24 +00004067 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichet4d604d62011-12-03 15:55:29 +00004068 isa<CXXMethodDecl>(CurContext))
4069 return TypoCorrection();
4070
Douglas Gregor546be3c2009-12-30 17:04:44 +00004071 // We only attempt to correct typos for identifiers.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004072 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor546be3c2009-12-30 17:04:44 +00004073 if (!Typo)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004074 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00004075
4076 // If the scope specifier itself was invalid, don't try to correct
4077 // typos.
4078 if (SS && SS->isInvalid())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004079 return TypoCorrection();
Douglas Gregor546be3c2009-12-30 17:04:44 +00004080
4081 // Never try to correct typos during template deduction or
4082 // instantiation.
4083 if (!ActiveTemplateInstantiations.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004084 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004085
Argyrios Kyrtzidis57f8da52013-03-14 22:56:43 +00004086 // Don't try to correct 'super'.
4087 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4088 return TypoCorrection();
4089
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004090 // Abort if typo correction already failed for this specific typo.
4091 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4092 if (locs != TypoCorrectionFailures.end() &&
Aaron Ballman6dfc04b2013-10-05 19:56:07 +00004093 locs->second.count(TypoName.getLoc()))
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004094 return TypoCorrection();
4095
Kaelyn Uhrainfb61e462013-10-02 18:26:35 +00004096 // Don't try to correct the identifier "vector" when in AltiVec mode.
4097 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4098 // remove this workaround.
4099 if (getLangOpts().AltiVec && Typo->isStr("vector"))
4100 return TypoCorrection();
4101
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004102 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004103
4104 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004105
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00004106 // If a callback object considers an empty typo correction candidate to be
4107 // viable, assume it does not do any actual validation of the candidates.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004108 TypoCorrection EmptyCorrection;
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00004109 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004110
Douglas Gregoraaf87162010-04-14 20:04:41 +00004111 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004112 bool IsUnqualifiedLookup = false;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004113 DeclContext *QualifiedDC = MemberContext;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00004114 if (MemberContext) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004115 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00004116
4117 // Look in qualified interfaces.
4118 if (OPT) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004119 for (ObjCObjectPointerType::qual_iterator
4120 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00004121 I != E; ++I)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004122 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00004123 }
4124 } else if (SS && SS->isSet()) {
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004125 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4126 if (!QualifiedDC)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004127 return TypoCorrection();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004128
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004129 // Provide a stop gap for files that are just seriously broken. Trying
4130 // to correct all typos can turn into a HUGE performance penalty, causing
4131 // some files to take minutes to get rejected by the parser.
4132 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004133 return TypoCorrection();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004134 ++TyposCorrected;
4135
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004136 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
Douglas Gregor546be3c2009-12-30 17:04:44 +00004137 } else {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004138 IsUnqualifiedLookup = true;
4139 UnqualifiedTyposCorrectedMap::iterator Cached
4140 = UnqualifiedTyposCorrected.find(Typo);
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004141 if (Cached != UnqualifiedTyposCorrected.end()) {
4142 // Add the cached value, unless it's a keyword or fails validation. In the
4143 // keyword case, we'll end up adding the keyword below.
4144 if (Cached->second) {
4145 if (!Cached->second.isKeyword() &&
Serge Pavlov81e34b12013-10-14 14:05:48 +00004146 isCandidateViable(CCC, Cached->second)) {
4147 // Do not use correction that is unaccessible in the given scope.
Serge Pavlov0ccadb22013-10-15 14:24:32 +00004148 NamedDecl *CorrectionDecl = Cached->second.getCorrectionDecl();
Serge Pavlov81e34b12013-10-14 14:05:48 +00004149 DeclarationNameInfo NameInfo(CorrectionDecl->getDeclName(),
4150 CorrectionDecl->getLocation());
4151 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4152 if (LookupName(R, S))
4153 Consumer.addCorrection(Cached->second);
4154 }
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004155 } else {
4156 // Only honor no-correction cache hits when a callback that will validate
4157 // correction candidates is not being used.
4158 if (!ValidatingCallback)
4159 return TypoCorrection();
4160 }
4161 }
4162 if (Cached == UnqualifiedTyposCorrected.end()) {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004163 // Provide a stop gap for files that are just seriously broken. Trying
4164 // to correct all typos can turn into a HUGE performance penalty, causing
4165 // some files to take minutes to get rejected by the parser.
4166 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004167 return TypoCorrection();
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004168 }
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004169 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004170
Douglas Gregor01798682012-03-26 16:54:18 +00004171 // Determine whether we are going to search in the various namespaces for
4172 // corrections.
4173 bool SearchNamespaces
Kaelyn Uhrain6d858d92012-04-03 18:20:11 +00004174 = getLangOpts().CPlusPlus &&
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +00004175 (IsUnqualifiedLookup || (SS && SS->isSet()));
Richard Smithd67679d2013-08-20 20:35:18 +00004176 // In a few cases we *only* want to search for corrections based on just
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00004177 // adding or changing the nested name specifier.
Kaelyn Uhrainfb61e462013-10-02 18:26:35 +00004178 unsigned TypoLen = Typo->getName().size();
4179 bool AllowOnlyNNSChanges = TypoLen < 3;
4180
Douglas Gregor01798682012-03-26 16:54:18 +00004181 if (IsUnqualifiedLookup || SearchNamespaces) {
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004182 // For unqualified lookup, look through all of the names that we have
4183 // seen in this translation unit.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00004184 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004185 for (IdentifierTable::iterator I = Context.Idents.begin(),
4186 IEnd = Context.Idents.end();
4187 I != IEnd; ++I)
4188 Consumer.FoundName(I->getKey());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004189
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004190 // Walk through identifiers in external identifier sources.
Kaelyn Uhrainbb3d9972012-02-07 01:32:58 +00004191 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004192 if (IdentifierInfoLookup *External
4193 = Context.Idents.getExternalIdentifierLookup()) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00004194 OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004195 do {
4196 StringRef Name = Iter->Next();
4197 if (Name.empty())
4198 break;
Douglas Gregor95f42922010-10-14 22:11:03 +00004199
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004200 Consumer.FoundName(Name);
4201 } while (true);
Douglas Gregor95f42922010-10-14 22:11:03 +00004202 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00004203 }
4204
Richard Smith0f4b5be2012-06-08 21:35:42 +00004205 AddKeywordsToConsumer(*this, Consumer, S, CCC, SS && SS->isNotEmpty());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004206
Douglas Gregoraaf87162010-04-14 20:04:41 +00004207 // If we haven't found anything, we're done.
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004208 if (Consumer.empty())
4209 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4210 IsUnqualifiedLookup);
Douglas Gregor546be3c2009-12-30 17:04:44 +00004211
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00004212 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4213 // is not more that about a third of the length of the typo's identifier.
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00004214 unsigned ED = Consumer.getBestEditDistance(true);
Kaelyn Uhrainfb61e462013-10-02 18:26:35 +00004215 if (ED > 0 && TypoLen / ED < 3)
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004216 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4217 IsUnqualifiedLookup);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004218
Douglas Gregor01798682012-03-26 16:54:18 +00004219 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4220 // to search those namespaces.
4221 if (SearchNamespaces) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004222 // Load any externally-known namespaces.
4223 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004224 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004225 LoadedExternalKnownNamespaces = true;
4226 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4227 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
4228 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
4229 }
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00004230
4231 for (llvm::MapVector<NamespaceDecl*, bool>::iterator
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004232 KNI = KnownNamespaces.begin(),
4233 KNIEnd = KnownNamespaces.end();
4234 KNI != KNIEnd; ++KNI)
Kaelyn Uhraina831f172013-10-19 00:04:49 +00004235 Namespaces.AddNameSpecifier(KNI->first);
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00004236
4237 for (ASTContext::type_iterator TI = Context.types_begin(),
4238 TIEnd = Context.types_end();
4239 TI != TIEnd; ++TI) {
4240 if (CXXRecordDecl *CD = (*TI)->getAsCXXRecordDecl()) {
Kaelyn Uhraina831f172013-10-19 00:04:49 +00004241 CD = CD->getCanonicalDecl();
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00004242 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
Kaelyn Uhraina831f172013-10-19 00:04:49 +00004243 !CD->isUnion() &&
4244 (CD->isBeingDefined() || CD->isCompleteDefinition()))
4245 Namespaces.AddNameSpecifier(CD);
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00004246 }
4247 }
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004248 }
Douglas Gregore24b5752010-10-14 20:34:08 +00004249
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004250 // Weed out any names that could not be found by name lookup or, if a
4251 // CorrectionCandidateCallback object was provided, failed validation.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004252 SmallVector<TypoCorrection, 16> QualifiedResults;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004253 LookupResult TmpRes(*this, TypoName, LookupKind);
4254 TmpRes.suppressDiagnostics();
4255 while (!Consumer.empty()) {
4256 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004257 for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(),
4258 IEnd = DI->second.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004259 I != IEnd; /* Increment in loop. */) {
Kaelyn Uhrain8d3607b2012-06-06 20:54:51 +00004260 // If we only want nested name specifier corrections, ignore potential
4261 // corrections that have a different base identifier from the typo.
4262 if (AllowOnlyNNSChanges &&
4263 I->second.front().getCorrectionAsIdentifierInfo() != Typo) {
4264 TypoCorrectionConsumer::result_iterator Prev = I;
4265 ++I;
4266 DI->second.erase(Prev);
4267 continue;
4268 }
4269
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004270 // If the item already has been looked up or is a keyword, keep it.
4271 // If a validator callback object was given, drop the correction
4272 // unless it passes validation.
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004273 bool Viable = false;
Benjamin Kramerb3996962012-07-27 10:21:08 +00004274 for (TypoResultList::iterator RI = I->second.begin();
4275 RI != I->second.end(); /* Increment in loop. */) {
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004276 TypoResultList::iterator Prev = RI;
4277 ++RI;
4278 if (Prev->isResolved()) {
4279 if (!isCandidateViable(CCC, *Prev))
Benjamin Kramerb3996962012-07-27 10:21:08 +00004280 RI = I->second.erase(Prev);
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004281 else
4282 Viable = true;
4283 }
4284 }
4285 if (Viable || I->second.empty()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004286 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004287 ++I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004288 if (!Viable)
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004289 DI->second.erase(Prev);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004290 continue;
Douglas Gregore24b5752010-10-14 20:34:08 +00004291 }
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004292 assert(I->second.size() == 1 && "Expected a single unresolved candidate");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004293
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004294 // Perform name lookup on this name.
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004295 TypoCorrection &Candidate = I->second.front();
4296 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00004297 DeclContext *TempMemberContext = MemberContext;
4298 CXXScopeSpec *TempSS = SS;
4299retry_lookup:
4300 LookupPotentialTypoResult(*this, TmpRes, Name, S, TempSS,
4301 TempMemberContext, EnteringContext,
Richard Smithd67679d2013-08-20 20:35:18 +00004302 CCC.IsObjCIvarLookup,
4303 Name == TypoName.getName() &&
4304 !Candidate.WillReplaceSpecifier());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004305
4306 switch (TmpRes.getResultKind()) {
4307 case LookupResult::NotFound:
4308 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00004309 case LookupResult::FoundUnresolvedValue:
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00004310 if (TempSS) {
4311 // Immediately retry the lookup without the given CXXScopeSpec
4312 TempSS = NULL;
4313 Candidate.WillReplaceSpecifier(true);
4314 goto retry_lookup;
4315 }
4316 if (TempMemberContext) {
4317 if (SS && !TempSS)
4318 TempSS = SS;
4319 TempMemberContext = NULL;
4320 goto retry_lookup;
4321 }
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004322 QualifiedResults.push_back(Candidate);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004323 // We didn't find this name in our scope, or didn't like what we found;
4324 // ignore it.
4325 {
4326 TypoCorrectionConsumer::result_iterator Next = I;
4327 ++Next;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004328 DI->second.erase(I);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004329 I = Next;
4330 }
4331 break;
4332
4333 case LookupResult::Ambiguous:
4334 // We don't deal with ambiguities.
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004335 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004336
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004337 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004338 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004339 // Store all of the Decls for overloaded symbols
4340 for (LookupResult::iterator TRD = TmpRes.begin(),
4341 TRDEnd = TmpRes.end();
4342 TRD != TRDEnd; ++TRD)
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004343 Candidate.addCorrectionDecl(*TRD);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004344 ++I;
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004345 if (!isCandidateViable(CCC, Candidate)) {
4346 QualifiedResults.push_back(Candidate);
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004347 DI->second.erase(Prev);
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004348 }
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004349 break;
4350 }
4351
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004352 case LookupResult::Found: {
4353 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004354 Candidate.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004355 ++I;
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004356 if (!isCandidateViable(CCC, Candidate)) {
4357 QualifiedResults.push_back(Candidate);
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004358 DI->second.erase(Prev);
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004359 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004360 break;
4361 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004362
4363 }
Douglas Gregore24b5752010-10-14 20:34:08 +00004364 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004365
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004366 if (DI->second.empty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004367 Consumer.erase(DI);
Kaelyn Uhrainfb61e462013-10-02 18:26:35 +00004368 else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !DI->first)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004369 // If there are results in the closest possible bucket, stop
4370 break;
4371
4372 // Only perform the qualified lookups for C++
Douglas Gregor01798682012-03-26 16:54:18 +00004373 if (SearchNamespaces) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004374 TmpRes.suppressDiagnostics();
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004375 for (SmallVector<TypoCorrection,
4376 16>::iterator QRI = QualifiedResults.begin(),
4377 QRIEnd = QualifiedResults.end();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004378 QRI != QRIEnd; ++QRI) {
4379 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
4380 NIEnd = Namespaces.end();
4381 NI != NIEnd; ++NI) {
4382 DeclContext *Ctx = NI->DeclCtx;
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00004383 const Type *NSType = NI->NameSpecifier->getAsType();
4384
4385 // If the current NestedNameSpecifier refers to a class and the
4386 // current correction candidate is the name of that class, then skip
4387 // it as it is unlikely a qualified version of the class' constructor
4388 // is an appropriate correction.
4389 if (CXXRecordDecl *NSDecl =
4390 NSType ? NSType->getAsCXXRecordDecl() : 0) {
4391 if (NSDecl->getIdentifier() == QRI->getCorrectionAsIdentifierInfo())
4392 continue;
4393 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004394
Kaelyn Uhrainfb61e462013-10-02 18:26:35 +00004395 TypoCorrection TC(*QRI);
4396 TC.ClearCorrectionDecls();
4397 TC.setCorrectionSpecifier(NI->NameSpecifier);
4398 TC.setQualifierDistance(NI->EditDistance);
4399 TC.setCallbackDistance(0); // Reset the callback distance
4400
4401 // If the current correction candidate and namespace combination are
4402 // too far away from the original typo based on the normalized edit
4403 // distance, then skip performing a qualified name lookup.
4404 unsigned TmpED = TC.getEditDistance(true);
4405 if (QRI->getCorrectionAsIdentifierInfo() != Typo &&
4406 TmpED && TypoLen / TmpED < 3)
4407 continue;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004408
4409 TmpRes.clear();
Kaelyn Uhrain63aae822012-02-14 18:56:48 +00004410 TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004411 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
4412
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004413 // Any corrections added below will be validated in subsequent
4414 // iterations of the main while() loop over the Consumer's contents.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004415 switch (TmpRes.getResultKind()) {
Kaelyn Uhraincaa16dd2013-07-02 23:47:35 +00004416 case LookupResult::Found:
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004417 case LookupResult::FoundOverloaded: {
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +00004418 if (SS && SS->isValid()) {
4419 std::string NewQualified = TC.getAsString(getLangOpts());
4420 std::string OldQualified;
4421 llvm::raw_string_ostream OldOStream(OldQualified);
4422 SS->getScopeRep()->print(OldOStream, getPrintingPolicy());
4423 OldOStream << TypoName;
4424 // If correction candidate would be an identical written qualified
4425 // identifer, then the existing CXXScopeSpec probably included a
4426 // typedef that didn't get accounted for properly.
4427 if (OldOStream.str() == NewQualified)
4428 break;
4429 }
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004430 for (LookupResult::iterator TRD = TmpRes.begin(),
4431 TRDEnd = TmpRes.end();
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00004432 TRD != TRDEnd; ++TRD) {
4433 if (CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4434 NSType ? NSType->getAsCXXRecordDecl() : 0,
Eli Friedman91d3f332013-10-01 02:44:48 +00004435 TRD.getPair()) == AR_accessible)
Kaelyn Uhrain3d9559b2013-09-26 19:10:29 +00004436 TC.addCorrectionDecl(*TRD);
4437 }
4438 if (TC.isResolved())
4439 Consumer.addCorrection(TC);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004440 break;
Kaelyn Uhrain2d4d7fd2012-02-15 22:14:18 +00004441 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004442 case LookupResult::NotFound:
4443 case LookupResult::NotFoundInCurrentInstantiation:
4444 case LookupResult::Ambiguous:
Kaelyn Uhrain82340e82011-09-07 20:25:59 +00004445 case LookupResult::FoundUnresolvedValue:
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004446 break;
4447 }
4448 }
4449 }
4450 }
4451
4452 QualifiedResults.clear();
4453 }
4454
4455 // No corrections remain...
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004456 if (Consumer.empty())
4457 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004458
Kaelyn Uhrain396e0a82012-05-31 23:32:58 +00004459 TypoResultsMap &BestResults = Consumer.getBestResults();
4460 ED = Consumer.getBestEditDistance(true);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004461
Kaelyn Uhrainfb61e462013-10-02 18:26:35 +00004462 if (!AllowOnlyNNSChanges && ED > 0 && TypoLen / ED < 3) {
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004463 // If this was an unqualified lookup and we believe the callback
4464 // object wouldn't have filtered out possible corrections, note
4465 // that no correction was found.
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004466 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4467 IsUnqualifiedLookup && !ValidatingCallback);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004468 }
4469
Douglas Gregore24b5752010-10-14 20:34:08 +00004470 // If only a single name remains, return that result.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004471 if (BestResults.size() == 1) {
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004472 const TypoResultList &CorrectionList = BestResults.begin()->second;
4473 const TypoCorrection &Result = CorrectionList.front();
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004474 if (CorrectionList.size() != 1)
4475 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004476
Douglas Gregor53e4b552010-10-26 17:18:00 +00004477 // Don't correct to a keyword that's the same as the typo; the keyword
4478 // wasn't actually in scope.
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004479 if (ED == 0 && Result.isKeyword())
4480 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004481
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004482 // Record the correction for unqualified lookup.
4483 if (IsUnqualifiedLookup)
4484 UnqualifiedTyposCorrected[Typo] = Result;
4485
David Blaikie6952c012012-10-12 20:00:44 +00004486 TypoCorrection TC = Result;
4487 TC.setCorrectionRange(SS, TypoName);
Richard Smithd67679d2013-08-20 20:35:18 +00004488 checkCorrectionVisibility(*this, TC, TypoName.getName());
David Blaikie6952c012012-10-12 20:00:44 +00004489 return TC;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004490 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00004491 else if (BestResults.size() > 1
4492 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4493 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4494 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4495 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00004496 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004497 && BestResults["super"].front().isKeyword()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004498 // Prefer 'super' when we're completing in a message-receiver
4499 // context.
4500
4501 // Don't correct to a keyword that's the same as the typo; the keyword
4502 // wasn't actually in scope.
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004503 if (ED == 0)
4504 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004505
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004506 // Record the correction for unqualified lookup.
4507 if (IsUnqualifiedLookup)
Kaelyn Uhrain784ae8e2012-06-01 18:11:16 +00004508 UnqualifiedTyposCorrected[Typo] = BestResults["super"].front();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004509
David Blaikie6952c012012-10-12 20:00:44 +00004510 TypoCorrection TC = BestResults["super"].front();
4511 TC.setCorrectionRange(SS, TypoName);
4512 return TC;
Douglas Gregor7b824e82010-10-15 13:35:25 +00004513 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004514
Kaelyn Uhrain438ee1f2012-01-23 20:18:59 +00004515 // If this was an unqualified lookup and we believe the callback object did
4516 // not filter out possible corrections, note that no correction was found.
4517 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00004518 (void)UnqualifiedTyposCorrected[Typo];
4519
Kaelyn Uhrain2b17b472013-09-27 19:40:08 +00004520 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004521}
4522
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004523void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4524 if (!CDecl) return;
4525
4526 if (isKeyword())
4527 CorrectionDecls.clear();
4528
Kaelyn Uhrain728948f2012-11-19 18:49:53 +00004529 CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00004530
4531 if (!CorrectionName)
4532 CorrectionName = CDecl->getDeclName();
4533}
4534
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004535std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4536 if (CorrectionNameSpec) {
4537 std::string tmpBuffer;
4538 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4539 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikie17828ca2013-05-14 21:04:00 +00004540 PrefixOStream << CorrectionName;
Benjamin Kramer34f9dc42012-04-14 08:26:28 +00004541 return PrefixOStream.str();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004542 }
4543
4544 return CorrectionName.getAsString();
Douglas Gregor546be3c2009-12-30 17:04:44 +00004545}
Kaelyn Uhrain20a7cf42013-04-03 16:59:49 +00004546
4547bool CorrectionCandidateCallback::ValidateCandidate(const TypoCorrection &candidate) {
4548 if (!candidate.isResolved())
4549 return true;
4550
4551 if (candidate.isKeyword())
4552 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4553 WantRemainingKeywords || WantObjCSuper;
4554
4555 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
4556 CDeclEnd = candidate.end();
4557 CDecl != CDeclEnd; ++CDecl) {
4558 if (!isa<TypeDecl>(*CDecl))
4559 return true;
4560 }
4561
4562 return WantTypeSpecifiers;
4563}
Kaelyn Uhrain761695f2013-07-08 23:13:39 +00004564
4565FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
4566 bool HasExplicitTemplateArgs)
4567 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
4568 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
4569 WantRemainingKeywords = false;
4570}
4571
4572bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4573 if (!candidate.getCorrectionDecl())
4574 return candidate.isKeyword();
4575
4576 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
4577 DIEnd = candidate.end();
4578 DI != DIEnd; ++DI) {
4579 FunctionDecl *FD = 0;
4580 NamedDecl *ND = (*DI)->getUnderlyingDecl();
4581 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4582 FD = FTD->getTemplatedDecl();
4583 if (!HasExplicitTemplateArgs && !FD) {
4584 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4585 // If the Decl is neither a function nor a template function,
4586 // determine if it is a pointer or reference to a function. If so,
4587 // check against the number of arguments expected for the pointee.
4588 QualType ValType = cast<ValueDecl>(ND)->getType();
4589 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4590 ValType = ValType->getPointeeType();
4591 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
4592 if (FPT->getNumArgs() == NumArgs)
4593 return true;
4594 }
4595 }
4596 if (FD && FD->getNumParams() >= NumArgs &&
4597 FD->getMinRequiredArguments() <= NumArgs)
4598 return true;
4599 }
4600 return false;
4601}
Richard Smith2d670972013-08-17 00:46:16 +00004602
4603void Sema::diagnoseTypo(const TypoCorrection &Correction,
4604 const PartialDiagnostic &TypoDiag,
4605 bool ErrorRecovery) {
4606 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
4607 ErrorRecovery);
4608}
4609
Richard Smithd67679d2013-08-20 20:35:18 +00004610/// Find which declaration we should import to provide the definition of
4611/// the given declaration.
4612static const NamedDecl *getDefinitionToImport(const NamedDecl *D) {
4613 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4614 return VD->getDefinition();
4615 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4616 return FD->isDefined(FD) ? FD : 0;
4617 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
4618 return TD->getDefinition();
4619 if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
4620 return ID->getDefinition();
4621 if (const ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
4622 return PD->getDefinition();
4623 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
4624 return getDefinitionToImport(TD->getTemplatedDecl());
4625 return 0;
4626}
4627
Richard Smith2d670972013-08-17 00:46:16 +00004628/// \brief Diagnose a successfully-corrected typo. Separated from the correction
4629/// itself to allow external validation of the result, etc.
4630///
4631/// \param Correction The result of performing typo correction.
4632/// \param TypoDiag The diagnostic to produce. This will have the corrected
4633/// string added to it (and usually also a fixit).
4634/// \param PrevNote A note to use when indicating the location of the entity to
4635/// which we are correcting. Will have the correction string added to it.
4636/// \param ErrorRecovery If \c true (the default), the caller is going to
4637/// recover from the typo as if the corrected string had been typed.
4638/// In this case, \c PDiag must be an error, and we will attach a fixit
4639/// to it.
4640void Sema::diagnoseTypo(const TypoCorrection &Correction,
4641 const PartialDiagnostic &TypoDiag,
4642 const PartialDiagnostic &PrevNote,
4643 bool ErrorRecovery) {
4644 std::string CorrectedStr = Correction.getAsString(getLangOpts());
4645 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
4646 FixItHint FixTypo = FixItHint::CreateReplacement(
4647 Correction.getCorrectionRange(), CorrectedStr);
4648
Richard Smithd67679d2013-08-20 20:35:18 +00004649 // Maybe we're just missing a module import.
4650 if (Correction.requiresImport()) {
4651 NamedDecl *Decl = Correction.getCorrectionDecl();
4652 assert(Decl && "import required but no declaration to import");
4653
4654 // Suggest importing a module providing the definition of this entity, if
4655 // possible.
4656 const NamedDecl *Def = getDefinitionToImport(Decl);
4657 if (!Def)
4658 Def = Decl;
4659 Module *Owner = Def->getOwningModule();
4660 assert(Owner && "definition of hidden declaration is not in a module");
4661
4662 Diag(Correction.getCorrectionRange().getBegin(),
4663 diag::err_module_private_declaration)
4664 << Def << Owner->getFullModuleName();
4665 Diag(Def->getLocation(), diag::note_previous_declaration);
4666
4667 // Recover by implicitly importing this module.
4668 if (!isSFINAEContext() && ErrorRecovery)
4669 createImplicitModuleImport(Correction.getCorrectionRange().getBegin(),
4670 Owner);
4671 return;
4672 }
4673
Richard Smith2d670972013-08-17 00:46:16 +00004674 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
4675 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
4676
4677 NamedDecl *ChosenDecl =
4678 Correction.isKeyword() ? 0 : Correction.getCorrectionDecl();
4679 if (PrevNote.getDiagID() && ChosenDecl)
4680 Diag(ChosenDecl->getLocation(), PrevNote)
4681 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
4682}