blob: 7b6536973ae4da1cf005c18c3c8aec057f5b055e [file] [log] [blame]
Douglas Gregor34074322009-01-14 22:20:51 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000014#include "clang/Sema/Lookup.h"
Douglas Gregor960b5bc2009-01-15 00:26:24 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000017#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
Nick Lewyckyc3921482012-04-03 21:44:08 +000019#include "clang/AST/DeclLookups.h"
Douglas Gregor34074322009-01-14 22:20:51 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000022#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000023#include "clang/AST/ExprCXX.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Douglas Gregor34074322009-01-14 22:20:51 +000025#include "clang/Basic/LangOptions.h"
Chandler Carruth3a022472012-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 Gregor34074322009-01-14 22:20:51 +000035#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000036#include "llvm/ADT/SetVector.h"
Douglas Gregore254f902009-02-04 00:32:51 +000037#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0afa7f62010-10-14 20:34:08 +000038#include "llvm/ADT/StringMap.h"
Chris Lattner83cfc7c2011-07-18 01:54:02 +000039#include "llvm/ADT/TinyPtrVector.h"
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +000040#include "llvm/ADT/edit_distance.h"
John McCall6538c932009-10-10 05:48:19 +000041#include "llvm/Support/ErrorHandling.h"
Nick Lewycky13668f22012-04-03 20:26:45 +000042#include <algorithm>
43#include <iterator>
Douglas Gregor0afa7f62010-10-14 20:34:08 +000044#include <limits>
Douglas Gregor2d435302009-12-30 17:04:44 +000045#include <list>
Douglas Gregorc2fa1692011-06-28 16:20:02 +000046#include <map>
Nick Lewycky13668f22012-04-03 20:26:45 +000047#include <set>
48#include <utility>
49#include <vector>
Douglas Gregor34074322009-01-14 22:20:51 +000050
51using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000052using namespace sema;
Douglas Gregor34074322009-01-14 22:20:51 +000053
John McCallf6c8a4e2009-11-10 07:01:13 +000054namespace {
55 class UnqualUsingEntry {
56 const DeclContext *Nominated;
57 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000058
John McCallf6c8a4e2009-11-10 07:01:13 +000059 public:
60 UnqualUsingEntry(const DeclContext *Nominated,
61 const DeclContext *CommonAncestor)
62 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
63 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000064
John McCallf6c8a4e2009-11-10 07:01:13 +000065 const DeclContext *getCommonAncestor() const {
66 return CommonAncestor;
67 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000068
John McCallf6c8a4e2009-11-10 07:01:13 +000069 const DeclContext *getNominatedNamespace() const {
70 return Nominated;
71 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000072
John McCallf6c8a4e2009-11-10 07:01:13 +000073 // Sort by the pointer value of the common ancestor.
74 struct Comparator {
75 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
76 return L.getCommonAncestor() < R.getCommonAncestor();
77 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000078
John McCallf6c8a4e2009-11-10 07:01:13 +000079 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
80 return E.getCommonAncestor() < DC;
81 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000082
John McCallf6c8a4e2009-11-10 07:01:13 +000083 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
84 return DC < E.getCommonAncestor();
85 }
86 };
87 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000088
John McCallf6c8a4e2009-11-10 07:01:13 +000089 /// A collection of using directives, as used by C++ unqualified
90 /// lookup.
91 class UnqualUsingDirectiveSet {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000092 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000093
John McCallf6c8a4e2009-11-10 07:01:13 +000094 ListTy list;
95 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000096
John McCallf6c8a4e2009-11-10 07:01:13 +000097 public:
98 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +000099
John McCallf6c8a4e2009-11-10 07:01:13 +0000100 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000101 // C++ [namespace.udir]p1:
John McCallf6c8a4e2009-11-10 07:01:13 +0000102 // During unqualified name lookup, the names appear as if they
103 // were declared in the nearest enclosing namespace which contains
104 // both the using-directive and the nominated namespace.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000105 DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
John McCallf6c8a4e2009-11-10 07:01:13 +0000106 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +0000107
John McCallf6c8a4e2009-11-10 07:01:13 +0000108 for (; S; S = S->getParent()) {
Nick Lewycky2bd636f2012-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 Kremenekc37877d2013-10-08 17:08:03 +0000112 DeclContext *Ctx = S->getEntity();
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000113 if (Ctx && Ctx->isFileContext()) {
114 visit(Ctx, Ctx);
115 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000116 Scope::udir_iterator I = S->using_directives_begin(),
117 End = S->using_directives_end();
John McCallf6c8a4e2009-11-10 07:01:13 +0000118 for (; I != End; ++I)
John McCall48871652010-08-21 09:40:31 +0000119 visit(*I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000120 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000121 }
122 }
John McCallf6c8a4e2009-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 Lattner0e62c1c2011-07-23 10:55:15 +0000154 SmallVector<DeclContext*,4> queue;
John McCallf6c8a4e2009-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 Wilhelm25284cc2013-08-23 16:11:15 +0000169 DC = queue.pop_back_val();
John McCallf6c8a4e2009-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 McCall9757d032009-11-10 09:20:04 +0000186 Common = Common->getPrimaryContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000187
John McCallf6c8a4e2009-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 McCallf6c8a4e2009-11-10 07:01:13 +0000195 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000196
John McCallf6c8a4e2009-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 McCall9757d032009-11-10 09:20:04 +0000202 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCallf6c8a4e2009-11-10 07:01:13 +0000203 UnqualUsingEntry::Comparator());
204 }
205 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000206}
207
Douglas Gregor889ceb72009-02-03 19:21:40 +0000208// Retrieve the set of identifier namespaces that correspond to a
209// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000210static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
211 bool CPlusPlus,
212 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000213 unsigned IDNS = 0;
214 switch (NameKind) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +0000215 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000216 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000217 case Sema::LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +0000218 case Sema::LookupLocalFriendName:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000219 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000220 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000221 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000222 if (Redeclaration)
223 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCallea305ed2009-12-18 10:40:03 +0000224 }
Richard Smith541b38b2013-09-20 01:15:31 +0000225 if (Redeclaration)
226 IDNS |= Decl::IDNS_LocalExtern;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000227 break;
228
John McCallb9467b62010-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 Gregor889ceb72009-02-03 19:21:40 +0000236 case Sema::LookupTagName:
John McCalle87beb22010-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 Gregor889ceb72009-02-03 19:21:40 +0000250 break;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000251 case Sema::LookupLabel:
252 IDNS = Decl::IDNS_Label;
253 break;
254
Douglas Gregor889ceb72009-02-03 19:21:40 +0000255 case Sema::LookupMemberName:
256 IDNS = Decl::IDNS_Member;
257 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000258 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000259 break;
260
261 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000262 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
263 break;
264
Douglas Gregor889ceb72009-02-03 19:21:40 +0000265 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000266 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000267 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000268
John McCall84d87672009-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 Gregor79947a22009-04-24 00:11:27 +0000274 case Sema::LookupObjCProtocolName:
275 IDNS = Decl::IDNS_ObjCProtocol;
276 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000277
Douglas Gregor39982192010-08-15 06:18:01 +0000278 case Sema::LookupAnyName:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000279 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor39982192010-08-15 06:18:01 +0000280 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
281 | Decl::IDNS_Type;
282 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000283 }
284 return IDNS;
285}
286
John McCallea305ed2009-12-18 10:40:03 +0000287void LookupResult::configure() {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000288 IDNS = getIDNS(LookupKind, SemaRef.getLangOpts().CPlusPlus,
John McCallea305ed2009-12-18 10:40:03 +0000289 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000290
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000291 if (!isForRedeclaration()) {
Douglas Gregor15197662013-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 Bagnarad6d2f182010-08-11 22:01:17 +0000295 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorbcf0a472010-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 Gregor15197662013-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 Gregorbcf0a472010-03-24 05:07:21 +0000315 }
John McCallea305ed2009-12-18 10:40:03 +0000316}
317
Alp Tokerc1086762013-12-07 13:51:35 +0000318bool LookupResult::sanity() const {
Daniel Dunbar9e19f132012-03-08 01:43:06 +0000319 // Note that this function is never called by NDEBUG builds. See
320 // LookupResult::sanity().
John McCall19c1bfd2010-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 Gregorc0d24902010-10-22 22:08:47 +0000328 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
329 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall19c1bfd2010-08-25 05:32:35 +0000330 assert((Paths != NULL) == (ResultKind == Ambiguous &&
331 (Ambiguity == AmbiguousBaseSubobjectTypes ||
332 Ambiguity == AmbiguousBaseSubobjects)));
Alp Tokerc1086762013-12-07 13:51:35 +0000333 return true;
John McCall19c1bfd2010-08-25 05:32:35 +0000334}
John McCall19c1bfd2010-08-25 05:32:35 +0000335
John McCall9f3059a2009-10-09 21:13:30 +0000336// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000337void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000338 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000339}
340
Richard Smith3876cc82013-10-30 01:02:04 +0000341/// Get a representative context for a declaration such that two declarations
342/// will have the same context if they were found within the same scope.
Benjamin Kramerfc58b042013-11-01 11:50:55 +0000343static DeclContext *getContextForScopeMatching(Decl *D) {
Richard Smith3876cc82013-10-30 01:02:04 +0000344 // For function-local declarations, use that function as the context. This
345 // doesn't account for scopes within the function; the caller must deal with
346 // those.
347 DeclContext *DC = D->getLexicalDeclContext();
348 if (DC->isFunctionOrMethod())
349 return DC;
350
351 // Otherwise, look at the semantic context of the declaration. The
352 // declaration must have been found there.
353 return D->getDeclContext()->getRedeclContext();
354}
355
John McCall283b9012009-11-22 00:44:51 +0000356/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000357void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000358 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000359
John McCall9f3059a2009-10-09 21:13:30 +0000360 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000361 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000362 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000363 return;
364 }
365
John McCall283b9012009-11-22 00:44:51 +0000366 // If there's a single decl, we need to examine it to decide what
367 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000368 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000369 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
370 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000371 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000372 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000373 ResultKind = FoundUnresolvedValue;
374 return;
375 }
John McCall9f3059a2009-10-09 21:13:30 +0000376
John McCall6538c932009-10-10 05:48:19 +0000377 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000378 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000379
John McCall9f3059a2009-10-09 21:13:30 +0000380 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor13e65872010-08-11 14:45:53 +0000381 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000382
John McCall9f3059a2009-10-09 21:13:30 +0000383 bool Ambiguous = false;
384 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000385 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000386
387 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000388
John McCall9f3059a2009-10-09 21:13:30 +0000389 unsigned I = 0;
390 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000391 NamedDecl *D = Decls[I]->getUnderlyingDecl();
392 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000393
Argyrios Kyrtzidis1fcd7fd2013-02-22 06:58:37 +0000394 // Ignore an invalid declaration unless it's the only one left.
395 if (D->isInvalidDecl() && I < N-1) {
396 Decls[I] = Decls[--N];
397 continue;
398 }
399
Douglas Gregor13e65872010-08-11 14:45:53 +0000400 // Redeclarations of types via typedef can occur both within a scope
401 // and, through using declarations and directives, across scopes. There is
402 // no ambiguity if they all refer to the same type, so unique based on the
403 // canonical type.
404 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
405 if (!TD->getDeclContext()->isRecord()) {
406 QualType T = SemaRef.Context.getTypeDeclType(TD);
407 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
408 // The type is not unique; pull something off the back and continue
409 // at this index.
410 Decls[I] = Decls[--N];
411 continue;
412 }
413 }
414 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000415
John McCallf0f1cf02009-11-17 07:50:12 +0000416 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000417 // If it's not unique, pull something off the back (and
418 // continue at this index).
419 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000420 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000421 }
422
Douglas Gregor13e65872010-08-11 14:45:53 +0000423 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000424
Douglas Gregor13e65872010-08-11 14:45:53 +0000425 if (isa<UnresolvedUsingValueDecl>(D)) {
426 HasUnresolved = true;
427 } else if (isa<TagDecl>(D)) {
428 if (HasTag)
429 Ambiguous = true;
430 UniqueTagIndex = I;
431 HasTag = true;
432 } else if (isa<FunctionTemplateDecl>(D)) {
433 HasFunction = true;
434 HasFunctionTemplate = true;
435 } else if (isa<FunctionDecl>(D)) {
436 HasFunction = true;
437 } else {
438 if (HasNonFunction)
439 Ambiguous = true;
440 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000441 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000442 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000443 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000444
John McCall9f3059a2009-10-09 21:13:30 +0000445 // C++ [basic.scope.hiding]p2:
446 // A class name or enumeration name can be hidden by the name of
447 // an object, function, or enumerator declared in the same
448 // scope. If a class or enumeration name and an object, function,
449 // or enumerator are declared in the same scope (in any order)
450 // with the same name, the class or enumeration name is hidden
451 // wherever the object, function, or enumerator name is visible.
452 // But it's still an error if there are distinct tag types found,
453 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000454 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000455 (HasFunction || HasNonFunction || HasUnresolved)) {
Richard Smith3876cc82013-10-30 01:02:04 +0000456 if (getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
457 getContextForScopeMatching(Decls[UniqueTagIndex ? 0 : N - 1])))
Douglas Gregore63d0872010-10-23 16:06:17 +0000458 Decls[UniqueTagIndex] = Decls[--N];
459 else
460 Ambiguous = true;
461 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000462
John McCall9f3059a2009-10-09 21:13:30 +0000463 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000464
John McCall80053822009-12-03 00:58:24 +0000465 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000466 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000467
John McCall9f3059a2009-10-09 21:13:30 +0000468 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000469 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000470 else if (HasUnresolved)
471 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000472 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000473 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000474 else
John McCall27b18f82009-11-17 02:14:36 +0000475 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000476}
477
John McCall5cebab12009-11-18 07:57:50 +0000478void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000479 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000480 for (I = P.begin(), E = P.end(); I != E; ++I)
David Blaikieff7d47a2012-12-19 00:45:41 +0000481 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
482 DE = I->Decls.end(); DI != DE; ++DI)
John McCall9f3059a2009-10-09 21:13:30 +0000483 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000484}
485
John McCall5cebab12009-11-18 07:57:50 +0000486void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000487 Paths = new CXXBasePaths;
488 Paths->swap(P);
489 addDeclsFromBasePaths(*Paths);
490 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000491 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000492}
493
John McCall5cebab12009-11-18 07:57:50 +0000494void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000495 Paths = new CXXBasePaths;
496 Paths->swap(P);
497 addDeclsFromBasePaths(*Paths);
498 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000499 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000500}
501
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000502void LookupResult::print(raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000503 Out << Decls.size() << " result(s)";
504 if (isAmbiguous()) Out << ", ambiguous";
505 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000506
John McCall9f3059a2009-10-09 21:13:30 +0000507 for (iterator I = begin(), E = end(); I != E; ++I) {
508 Out << "\n";
509 (*I)->print(Out, 2);
510 }
511}
512
Douglas Gregord3a59182010-02-12 05:48:04 +0000513/// \brief Lookup a builtin function, when name lookup would otherwise
514/// fail.
515static bool LookupBuiltin(Sema &S, LookupResult &R) {
516 Sema::LookupNameKind NameKind = R.getLookupKind();
517
518 // If we didn't find a use of this identifier, and if the identifier
519 // corresponds to a compiler builtin, create the decl object for the builtin
520 // now, injecting it into translation unit scope, and return it.
521 if (NameKind == Sema::LookupOrdinaryName ||
522 NameKind == Sema::LookupRedeclarationWithLinkage) {
523 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
524 if (II) {
Nico Webere1687c52013-06-20 21:44:55 +0000525 if (S.getLangOpts().CPlusPlus11 && S.getLangOpts().GNUMode &&
526 II == S.getFloat128Identifier()) {
527 // libstdc++4.7's type_traits expects type __float128 to exist, so
528 // insert a dummy type to make that header build in gnu++11 mode.
529 R.addDecl(S.getASTContext().getFloat128StubType());
530 return true;
531 }
532
Douglas Gregord3a59182010-02-12 05:48:04 +0000533 // If this is a builtin on this (or all) targets, create the decl.
534 if (unsigned BuiltinID = II->getBuiltinID()) {
535 // In C++, we don't have any predefined library functions like
536 // 'malloc'. Instead, we'll just error.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000537 if (S.getLangOpts().CPlusPlus &&
Douglas Gregord3a59182010-02-12 05:48:04 +0000538 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
539 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000540
541 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
542 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000543 R.isForRedeclaration(),
544 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000545 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000546 return true;
547 }
548
549 if (R.isForRedeclaration()) {
550 // If we're redeclaring this function anyway, forget that
551 // this was a builtin at all.
552 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
553 }
554
555 return false;
Douglas Gregord3a59182010-02-12 05:48:04 +0000556 }
557 }
558 }
559
560 return false;
561}
562
Douglas Gregor7454c562010-07-02 20:37:36 +0000563/// \brief Determine whether we can declare a special member function within
564/// the class at this point.
Richard Smith7d125a12012-11-27 21:20:31 +0000565static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +0000566 // We need to have a definition for the class.
567 if (!Class->getDefinition() || Class->isDependentContext())
568 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000569
Douglas Gregor7454c562010-07-02 20:37:36 +0000570 // We can't be in the middle of defining the class.
Richard Smith7d125a12012-11-27 21:20:31 +0000571 return !Class->isBeingDefined();
Douglas Gregor7454c562010-07-02 20:37:36 +0000572}
573
574void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smith7d125a12012-11-27 21:20:31 +0000575 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregora6d69502010-07-02 23:41:54 +0000576 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000577
578 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000579 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000580 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000581
Douglas Gregora6d69502010-07-02 23:41:54 +0000582 // If the copy constructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000583 if (Class->needsImplicitCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +0000584 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000585
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000586 // If the copy assignment operator has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000587 if (Class->needsImplicitCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000588 DeclareImplicitCopyAssignment(Class);
589
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000590 if (getLangOpts().CPlusPlus11) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000591 // If the move constructor has not yet been declared, do so now.
592 if (Class->needsImplicitMoveConstructor())
593 DeclareImplicitMoveConstructor(Class); // might not actually do it
594
595 // If the move assignment operator has not yet been declared, do so now.
596 if (Class->needsImplicitMoveAssignment())
597 DeclareImplicitMoveAssignment(Class); // might not actually do it
598 }
599
Douglas Gregor7454c562010-07-02 20:37:36 +0000600 // If the destructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000601 if (Class->needsImplicitDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000602 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000603}
604
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000605/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000606/// special member function.
607static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
608 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000609 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000610 case DeclarationName::CXXDestructorName:
611 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000612
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000613 case DeclarationName::CXXOperatorName:
614 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000615
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000616 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000617 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000618 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000619
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000620 return false;
621}
622
623/// \brief If there are any implicit member functions with the given name
624/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000625static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000626 DeclarationName Name,
627 const DeclContext *DC) {
628 if (!DC)
629 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000630
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000631 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000632 case DeclarationName::CXXConstructorName:
633 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith7d125a12012-11-27 21:20:31 +0000634 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000635 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000636 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000637 S.DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +0000638 if (Record->needsImplicitCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000639 S.DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000640 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000641 Record->needsImplicitMoveConstructor())
642 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000643 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000644 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000645
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000646 case DeclarationName::CXXDestructorName:
647 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith2be35f52012-12-01 02:35:44 +0000648 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smith7d125a12012-11-27 21:20:31 +0000649 CanDeclareSpecialMemberFunction(Record))
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000650 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000651 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000652
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000653 case DeclarationName::CXXOperatorName:
654 if (Name.getCXXOverloadedOperator() != OO_Equal)
655 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000656
Sebastian Redl22653ba2011-08-30 19:58:05 +0000657 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smith7d125a12012-11-27 21:20:31 +0000658 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000659 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smith2be35f52012-12-01 02:35:44 +0000660 if (Record->needsImplicitCopyAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000661 S.DeclareImplicitCopyAssignment(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000662 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000663 Record->needsImplicitMoveAssignment())
664 S.DeclareImplicitMoveAssignment(Class);
665 }
666 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000667 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000668
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000669 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000670 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000671 }
672}
Douglas Gregor7454c562010-07-02 20:37:36 +0000673
John McCall9f3059a2009-10-09 21:13:30 +0000674// Adds all qualifying matches for a name within a decl context to the
675// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000676static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000677 bool Found = false;
678
Douglas Gregor7454c562010-07-02 20:37:36 +0000679 // Lazily declare C++ special member functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000680 if (S.getLangOpts().CPlusPlus)
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000681 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000682
Douglas Gregor7454c562010-07-02 20:37:36 +0000683 // Perform lookup into this declaration context.
David Blaikieff7d47a2012-12-19 00:45:41 +0000684 DeclContext::lookup_const_result DR = DC->lookup(R.getLookupName());
685 for (DeclContext::lookup_const_iterator I = DR.begin(), E = DR.end(); I != E;
686 ++I) {
John McCall401982f2010-01-20 21:53:11 +0000687 NamedDecl *D = *I;
Douglas Gregor4a814562011-12-14 16:03:29 +0000688 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000689 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000690 Found = true;
691 }
692 }
John McCall9f3059a2009-10-09 21:13:30 +0000693
Douglas Gregord3a59182010-02-12 05:48:04 +0000694 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
695 return true;
696
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000697 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000698 != DeclarationName::CXXConversionFunctionName ||
699 R.getLookupName().getCXXNameType()->isDependentType() ||
700 !isa<CXXRecordDecl>(DC))
701 return Found;
702
703 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000704 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000705 // name lookup. Instead, any conversion function templates visible in the
706 // context of the use are considered. [...]
707 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000708 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000709 return Found;
710
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +0000711 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
712 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruth3a693b72010-01-31 11:44:02 +0000713 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
714 if (!ConvTemplate)
715 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000716
Chandler Carruth3a693b72010-01-31 11:44:02 +0000717 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000718 // add the conversion function template. When we deduce template
719 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000720 // type of the new declaration with the type of the function template.
721 if (R.isForRedeclaration()) {
722 R.addDecl(ConvTemplate);
723 Found = true;
724 continue;
725 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000726
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000727 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000728 // [...] For each such operator, if argument deduction succeeds
729 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000730 // name lookup.
731 //
732 // When referencing a conversion function for any purpose other than
733 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000734 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000735 // specialization into the result set. We do this to avoid forcing all
736 // callers to perform special deduction for conversion functions.
Craig Toppere6706e42012-09-19 02:26:47 +0000737 TemplateDeductionInfo Info(R.getNameLoc());
Chandler Carruth3a693b72010-01-31 11:44:02 +0000738 FunctionDecl *Specialization = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000739
740 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000741 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
742 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000743
Chandler Carruth3a693b72010-01-31 11:44:02 +0000744 // Compute the type of the function that we would expect the conversion
745 // function to have, if it were to match the name given.
746 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000747 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
Reid Kleckner78af0702013-08-27 23:08:25 +0000748 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
Sebastian Redl7c6c9e92011-03-06 10:52:04 +0000749 EPI.ExceptionSpecType = EST_None;
John McCalldb40c7f2010-12-14 08:05:40 +0000750 EPI.NumExceptions = 0;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000751 QualType ExpectedType
752 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000753 None, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000754
Chandler Carruth3a693b72010-01-31 11:44:02 +0000755 // Perform template argument deduction against the type that we would
756 // expect the function to have.
757 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
758 Specialization, Info)
759 == Sema::TDK_Success) {
760 R.addDecl(Specialization);
761 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000762 }
763 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000764
John McCall9f3059a2009-10-09 21:13:30 +0000765 return Found;
766}
767
John McCallf6c8a4e2009-11-10 07:01:13 +0000768// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000769static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000770CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000771 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000772
773 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
774
John McCallf6c8a4e2009-11-10 07:01:13 +0000775 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000776 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000777
John McCallf6c8a4e2009-11-10 07:01:13 +0000778 // Perform direct name lookup into the namespaces nominated by the
779 // using directives whose common ancestor is this namespace.
780 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
781 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000782
John McCallf6c8a4e2009-11-10 07:01:13 +0000783 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000784 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000785 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000786
787 R.resolveKind();
788
789 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000790}
791
792static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000793 if (DeclContext *Ctx = S->getEntity())
Douglas Gregor700792c2009-02-05 19:25:20 +0000794 return Ctx->isFileContext();
795 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000796}
Douglas Gregored8f2882009-01-30 01:04:22 +0000797
Douglas Gregor66230062010-03-15 14:33:29 +0000798// Find the next outer declaration context from this scope. This
799// routine actually returns the semantic outer context, which may
800// differ from the lexical context (encoded directly in the Scope
801// stack) when we are parsing a member of a class template. In this
802// case, the second element of the pair will be true, to indicate that
803// name lookup should continue searching in this semantic context when
804// it leaves the current template parameter scope.
805static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000806 DeclContext *DC = S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +0000807 DeclContext *Lexical = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000808 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000809 OuterS = OuterS->getParent()) {
810 if (OuterS->getEntity()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000811 Lexical = OuterS->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +0000812 break;
813 }
814 }
815
816 // C++ [temp.local]p8:
817 // In the definition of a member of a class template that appears
818 // outside of the namespace containing the class template
819 // definition, the name of a template-parameter hides the name of
820 // a member of this namespace.
821 //
822 // Example:
823 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000824 // namespace N {
825 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000826 //
827 // template<class T> class B {
828 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000829 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000830 // }
831 //
832 // template<class C> void N::B<C>::f(C) {
833 // C b; // C is the template parameter, not N::C
834 // }
835 //
836 // In this example, the lexical context we return is the
837 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000838 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000839 !S->getParent()->isTemplateParamScope())
840 return std::make_pair(Lexical, false);
841
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000842 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000843 // For the example, this is the scope for the template parameters of
844 // template<class C>.
845 Scope *OutermostTemplateScope = S->getParent();
846 while (OutermostTemplateScope->getParent() &&
847 OutermostTemplateScope->getParent()->isTemplateParamScope())
848 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000849
Douglas Gregor66230062010-03-15 14:33:29 +0000850 // Find the namespace context in which the original scope occurs. In
851 // the example, this is namespace N.
852 DeclContext *Semantic = DC;
853 while (!Semantic->isFileContext())
854 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000855
Douglas Gregor66230062010-03-15 14:33:29 +0000856 // Find the declaration context just outside of the template
857 // parameter scope. This is the context in which the template is
858 // being lexically declaration (a namespace context). In the
859 // example, this is the global scope.
860 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
861 Lexical->Encloses(Semantic))
862 return std::make_pair(Semantic, true);
863
864 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000865}
866
Richard Smith541b38b2013-09-20 01:15:31 +0000867namespace {
868/// An RAII object to specify that we want to find block scope extern
869/// declarations.
870struct FindLocalExternScope {
871 FindLocalExternScope(LookupResult &R)
872 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
873 Decl::IDNS_LocalExtern) {
874 R.setFindLocalExtern(R.getIdentifierNamespace() & Decl::IDNS_Ordinary);
875 }
876 void restore() {
877 R.setFindLocalExtern(OldFindLocalExtern);
878 }
879 ~FindLocalExternScope() {
880 restore();
881 }
882 LookupResult &R;
883 bool OldFindLocalExtern;
884};
885}
886
John McCall27b18f82009-11-17 02:14:36 +0000887bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000888 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000889
890 DeclarationName Name = R.getLookupName();
Richard Smith1c34fb72013-08-13 18:18:50 +0000891 Sema::LookupNameKind NameKind = R.getLookupKind();
John McCall27b18f82009-11-17 02:14:36 +0000892
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000893 // If this is the name of an implicitly-declared special member function,
894 // go through the scope stack to implicitly declare
895 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
896 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +0000897 if (DeclContext *DC = PreS->getEntity())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000898 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
899 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000900
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000901 // Implicitly declare member functions with the name we're looking for, if in
902 // fact we are in a scope where it matters.
903
Douglas Gregor889ceb72009-02-03 19:21:40 +0000904 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000905 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000906 I = IdResolver.begin(Name),
907 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000908
Douglas Gregor889ceb72009-02-03 19:21:40 +0000909 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000910 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000911 // ...During unqualified name lookup (3.4.1), the names appear as if
912 // they were declared in the nearest enclosing namespace which contains
913 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000914 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000915 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000916 //
917 // For example:
918 // namespace A { int i; }
919 // void foo() {
920 // int i;
921 // {
922 // using namespace A;
923 // ++i; // finds local 'i', A::i appears at global scope
924 // }
925 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000926 //
Douglas Gregorcc9406c2013-04-08 23:11:25 +0000927 UnqualUsingDirectiveSet UDirs;
928 bool VisitedUsingDirectives = false;
Richard Smith1c34fb72013-08-13 18:18:50 +0000929 bool LeftStartingScope = false;
Douglas Gregor66230062010-03-15 14:33:29 +0000930 DeclContext *OutsideOfTemplateParamDC = 0;
Richard Smith541b38b2013-09-20 01:15:31 +0000931
932 // When performing a scope lookup, we want to find local extern decls.
933 FindLocalExternScope FindLocals(R);
934
Douglas Gregor700792c2009-02-05 19:25:20 +0000935 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000936 DeclContext *Ctx = S->getEntity();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000937
Douglas Gregor889ceb72009-02-03 19:21:40 +0000938 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000939 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000940 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000941 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Richard Smith1c34fb72013-08-13 18:18:50 +0000942 if (NameKind == LookupRedeclarationWithLinkage) {
943 // Determine whether this (or a previous) declaration is
944 // out-of-scope.
945 if (!LeftStartingScope && !Initial->isDeclScope(*I))
946 LeftStartingScope = true;
947
948 // If we found something outside of our starting scope that
Richard Smith9a00bbf2013-10-16 21:12:00 +0000949 // does not have linkage, skip it. If it's a template parameter,
950 // we still find it, so we can diagnose the invalid redeclaration.
951 if (LeftStartingScope && !((*I)->hasLinkage()) &&
952 !(*I)->isTemplateParameter()) {
Richard Smith1c34fb72013-08-13 18:18:50 +0000953 R.setShadowed();
954 continue;
955 }
956 }
957
John McCall9f3059a2009-10-09 21:13:30 +0000958 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +0000959 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000960 }
961 }
John McCall9f3059a2009-10-09 21:13:30 +0000962 if (Found) {
963 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000964 if (S->isClassScope())
965 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
966 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000967 return true;
968 }
969
Richard Smith1c34fb72013-08-13 18:18:50 +0000970 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
Richard Smith114394f2013-08-09 04:35:01 +0000971 // C++11 [class.friend]p11:
972 // If a friend declaration appears in a local class and the name
973 // specified is an unqualified name, a prior declaration is
974 // looked up without considering scopes that are outside the
975 // innermost enclosing non-class scope.
976 return false;
977 }
978
Douglas Gregor66230062010-03-15 14:33:29 +0000979 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
980 S->getParent() && !S->getParent()->isTemplateParamScope()) {
981 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000982 // found nothing, so look into the contexts between the
Douglas Gregor66230062010-03-15 14:33:29 +0000983 // lexical and semantic declaration contexts returned by
984 // findOuterContext(). This implements the name lookup behavior
985 // of C++ [temp.local]p8.
986 Ctx = OutsideOfTemplateParamDC;
987 OutsideOfTemplateParamDC = 0;
988 }
989
990 if (Ctx) {
991 DeclContext *OuterCtx;
992 bool SearchAfterTemplateScope;
993 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
994 if (SearchAfterTemplateScope)
995 OutsideOfTemplateParamDC = OuterCtx;
996
Douglas Gregorea166062010-03-15 15:26:48 +0000997 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000998 // We do not directly look into transparent contexts, since
999 // those entities will be found in the nearest enclosing
1000 // non-transparent context.
1001 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +00001002 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +00001003
1004 // We do not look directly into function or method contexts,
1005 // since all of the local variables and parameters of the
1006 // function/method are present within the Scope.
1007 if (Ctx->isFunctionOrMethod()) {
1008 // If we have an Objective-C instance method, look for ivars
1009 // in the corresponding interface.
1010 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
1011 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1012 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1013 ObjCInterfaceDecl *ClassDeclared;
1014 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001015 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +00001016 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001017 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1018 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +00001019 R.resolveKind();
1020 return true;
1021 }
1022 }
1023 }
1024 }
1025
1026 continue;
1027 }
1028
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001029 // If this is a file context, we need to perform unqualified name
1030 // lookup considering using directives.
1031 if (Ctx->isFileContext()) {
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001032 // If we haven't handled using directives yet, do so now.
1033 if (!VisitedUsingDirectives) {
1034 // Add using directives from this context up to the top level.
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001035 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1036 if (UCtx->isTransparentContext())
1037 continue;
1038
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001039 UDirs.visit(UCtx, UCtx);
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001040 }
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001041
1042 // Find the innermost file scope, so we can add using directives
1043 // from local scopes.
1044 Scope *InnermostFileScope = S;
1045 while (InnermostFileScope &&
1046 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1047 InnermostFileScope = InnermostFileScope->getParent();
1048 UDirs.visitScopeChain(Initial, InnermostFileScope);
1049
1050 UDirs.done();
1051
1052 VisitedUsingDirectives = true;
1053 }
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001054
1055 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1056 R.resolveKind();
1057 return true;
1058 }
1059
1060 continue;
1061 }
1062
Douglas Gregor7f737c02009-09-10 16:57:35 +00001063 // Perform qualified name lookup into this context.
1064 // FIXME: In some cases, we know that every name that could be found by
1065 // this qualified name lookup will also be on the identifier chain. For
1066 // example, inside a class without any base classes, we never need to
1067 // perform qualified lookup because all of the members are on top of the
1068 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001069 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +00001070 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +00001071 }
Douglas Gregor700792c2009-02-05 19:25:20 +00001072 }
Douglas Gregored8f2882009-01-30 01:04:22 +00001073 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001074
John McCallf6c8a4e2009-11-10 07:01:13 +00001075 // Stop if we ran out of scopes.
1076 // FIXME: This really, really shouldn't be happening.
1077 if (!S) return false;
1078
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001079 // If we are looking for members, no need to look into global/namespace scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00001080 if (NameKind == LookupMemberName)
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001081 return false;
1082
Douglas Gregor700792c2009-02-05 19:25:20 +00001083 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +00001084 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +00001085 //
Mike Stump87c57ac2009-05-16 07:39:55 +00001086 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1087 // don't build it for each lookup!
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001088 if (!VisitedUsingDirectives) {
1089 UDirs.visitScopeChain(Initial, S);
1090 UDirs.done();
1091 }
Richard Smith541b38b2013-09-20 01:15:31 +00001092
1093 // If we're not performing redeclaration lookup, do not look for local
1094 // extern declarations outside of a function scope.
1095 if (!R.isForRedeclaration())
1096 FindLocals.restore();
1097
Douglas Gregor700792c2009-02-05 19:25:20 +00001098 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +00001099 // Unqualified name lookup in C++ requires looking into scopes
1100 // that aren't strictly lexical, and therefore we walk through the
1101 // context as well as walking through the scopes.
1102 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001103 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +00001104 bool Found = false;
John McCall48871652010-08-21 09:40:31 +00001105 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001106 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001107 // We found something. Look for anything else in our scope
1108 // with this same name and in an acceptable identifier
1109 // namespace, so that we can construct an overload set if we
1110 // need to.
John McCall9f3059a2009-10-09 21:13:30 +00001111 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +00001112 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001113 }
1114 }
1115
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001116 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +00001117 R.resolveKind();
1118 return true;
1119 }
1120
Ted Kremenekc37877d2013-10-08 17:08:03 +00001121 DeclContext *Ctx = S->getEntity();
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001122 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1123 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1124 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001125 // found nothing, so look into the contexts between the
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001126 // lexical and semantic declaration contexts returned by
1127 // findOuterContext(). This implements the name lookup behavior
1128 // of C++ [temp.local]p8.
1129 Ctx = OutsideOfTemplateParamDC;
1130 OutsideOfTemplateParamDC = 0;
1131 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001132
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001133 if (Ctx) {
1134 DeclContext *OuterCtx;
1135 bool SearchAfterTemplateScope;
1136 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1137 if (SearchAfterTemplateScope)
1138 OutsideOfTemplateParamDC = OuterCtx;
1139
1140 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1141 // We do not directly look into transparent contexts, since
1142 // those entities will be found in the nearest enclosing
1143 // non-transparent context.
1144 if (Ctx->isTransparentContext())
1145 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001146
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001147 // If we have a context, and it's not a context stashed in the
1148 // template parameter scope for an out-of-line definition, also
1149 // look into that context.
1150 if (!(Found && S && S->isTemplateParamScope())) {
1151 assert(Ctx->isFileContext() &&
1152 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001153
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001154 // Look into context considering using-directives.
1155 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1156 Found = true;
1157 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001158
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001159 if (Found) {
1160 R.resolveKind();
1161 return true;
1162 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001163
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001164 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1165 return false;
1166 }
1167 }
1168
Douglas Gregor3ce74932010-02-05 07:07:10 +00001169 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001170 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001171 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001172
John McCall9f3059a2009-10-09 21:13:30 +00001173 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001174}
1175
Richard Smith0e5d7b82013-07-25 23:08:39 +00001176/// \brief Find the declaration that a class temploid member specialization was
1177/// instantiated from, or the member itself if it is an explicit specialization.
1178static Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) {
1179 return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom();
1180}
1181
1182/// \brief Find the module in which the given declaration was defined.
1183static Module *getDefiningModule(Decl *Entity) {
1184 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1185 // If this function was instantiated from a template, the defining module is
1186 // the module containing the pattern.
1187 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1188 Entity = Pattern;
1189 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
1190 // If it's a class template specialization, find the template or partial
1191 // specialization from which it was instantiated.
1192 if (ClassTemplateSpecializationDecl *SpecRD =
1193 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
1194 llvm::PointerUnion<ClassTemplateDecl*,
1195 ClassTemplatePartialSpecializationDecl*> From =
1196 SpecRD->getInstantiatedFrom();
1197 if (ClassTemplateDecl *FromTemplate = From.dyn_cast<ClassTemplateDecl*>())
1198 Entity = FromTemplate->getTemplatedDecl();
1199 else if (From)
1200 Entity = From.get<ClassTemplatePartialSpecializationDecl*>();
1201 // Otherwise, it's an explicit specialization.
1202 } else if (MemberSpecializationInfo *MSInfo =
1203 RD->getMemberSpecializationInfo())
1204 Entity = getInstantiatedFrom(RD, MSInfo);
1205 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1206 if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo())
1207 Entity = getInstantiatedFrom(ED, MSInfo);
1208 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1209 // FIXME: Map from variable template specializations back to the template.
1210 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo())
1211 Entity = getInstantiatedFrom(VD, MSInfo);
1212 }
1213
1214 // Walk up to the containing context. That might also have been instantiated
1215 // from a template.
1216 DeclContext *Context = Entity->getDeclContext();
1217 if (Context->isFileContext())
1218 return Entity->getOwningModule();
1219 return getDefiningModule(cast<Decl>(Context));
1220}
1221
1222llvm::DenseSet<Module*> &Sema::getLookupModules() {
1223 unsigned N = ActiveTemplateInstantiations.size();
1224 for (unsigned I = ActiveTemplateInstantiationLookupModules.size();
1225 I != N; ++I) {
1226 Module *M = getDefiningModule(ActiveTemplateInstantiations[I].Entity);
1227 if (M && !LookupModulesCache.insert(M).second)
1228 M = 0;
1229 ActiveTemplateInstantiationLookupModules.push_back(M);
1230 }
1231 return LookupModulesCache;
1232}
1233
1234/// \brief Determine whether a declaration is visible to name lookup.
1235///
1236/// This routine determines whether the declaration D is visible in the current
1237/// lookup context, taking into account the current template instantiation
1238/// stack. During template instantiation, a declaration is visible if it is
1239/// visible from a module containing any entity on the template instantiation
1240/// path (by instantiating a template, you allow it to see the declarations that
1241/// your module can see, including those later on in your module).
1242bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
1243 assert(D->isHidden() && !SemaRef.ActiveTemplateInstantiations.empty() &&
1244 "should not call this: not in slow case");
1245 Module *DeclModule = D->getOwningModule();
1246 assert(DeclModule && "hidden decl not from a module");
1247
1248 // Find the extra places where we need to look.
1249 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
1250 if (LookupModules.empty())
1251 return false;
1252
1253 // If our lookup set contains the decl's module, it's visible.
1254 if (LookupModules.count(DeclModule))
1255 return true;
1256
1257 // If the declaration isn't exported, it's not visible in any other module.
1258 if (D->isModulePrivate())
1259 return false;
1260
1261 // Check whether DeclModule is transitively exported to an import of
1262 // the lookup set.
1263 for (llvm::DenseSet<Module *>::iterator I = LookupModules.begin(),
1264 E = LookupModules.end();
1265 I != E; ++I)
1266 if ((*I)->isModuleVisible(DeclModule))
1267 return true;
1268 return false;
1269}
1270
Douglas Gregor4a814562011-12-14 16:03:29 +00001271/// \brief Retrieve the visible declaration corresponding to D, if any.
1272///
1273/// This routine determines whether the declaration D is visible in the current
1274/// module, with the current imports. If not, it checks whether any
1275/// redeclaration of D is visible, and if so, returns that declaration.
Richard Smith0e5d7b82013-07-25 23:08:39 +00001276///
Douglas Gregor4a814562011-12-14 16:03:29 +00001277/// \returns D, or a visible previous declaration of D, whichever is more recent
1278/// and visible. If no declaration of D is visible, returns null.
Richard Smithe156254d2013-08-20 20:35:18 +00001279static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
1280 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
Richard Smith0e5d7b82013-07-25 23:08:39 +00001281
Douglas Gregor54079202012-01-06 22:05:37 +00001282 for (Decl::redecl_iterator RD = D->redecls_begin(), RDEnd = D->redecls_end();
1283 RD != RDEnd; ++RD) {
David Blaikie40ed2972012-06-06 20:45:41 +00001284 if (NamedDecl *ND = dyn_cast<NamedDecl>(*RD)) {
Richard Smithe156254d2013-08-20 20:35:18 +00001285 if (LookupResult::isVisible(SemaRef, ND))
Douglas Gregor54079202012-01-06 22:05:37 +00001286 return ND;
1287 }
Douglas Gregor4a814562011-12-14 16:03:29 +00001288 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001289
Douglas Gregor4a814562011-12-14 16:03:29 +00001290 return 0;
1291}
1292
Richard Smithe156254d2013-08-20 20:35:18 +00001293NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
1294 return findAcceptableDecl(SemaRef, D);
1295}
1296
Douglas Gregor34074322009-01-14 22:20:51 +00001297/// @brief Perform unqualified name lookup starting from a given
1298/// scope.
1299///
1300/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1301/// used to find names within the current scope. For example, 'x' in
1302/// @code
1303/// int x;
1304/// int f() {
1305/// return x; // unqualified name look finds 'x' in the global scope
1306/// }
1307/// @endcode
1308///
1309/// Different lookup criteria can find different names. For example, a
1310/// particular scope can have both a struct and a function of the same
1311/// name, and each can be found by certain lookup criteria. For more
1312/// information about lookup criteria, see the documentation for the
1313/// class LookupCriteria.
1314///
1315/// @param S The scope from which unqualified name lookup will
1316/// begin. If the lookup criteria permits, name lookup may also search
1317/// in the parent scopes.
1318///
James Dennett91738ff2012-06-22 10:32:46 +00001319/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1320/// look up and the lookup kind), and is updated with the results of lookup
1321/// including zero or more declarations and possibly additional information
1322/// used to diagnose ambiguities.
Douglas Gregor34074322009-01-14 22:20:51 +00001323///
James Dennett91738ff2012-06-22 10:32:46 +00001324/// @returns \c true if lookup succeeded and false otherwise.
John McCall27b18f82009-11-17 02:14:36 +00001325bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1326 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001327 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001328
John McCall27b18f82009-11-17 02:14:36 +00001329 LookupNameKind NameKind = R.getLookupKind();
1330
David Blaikiebbafb8a2012-03-11 07:00:24 +00001331 if (!getLangOpts().CPlusPlus) {
Douglas Gregor34074322009-01-14 22:20:51 +00001332 // Unqualified name lookup in C/Objective-C is purely lexical, so
1333 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001334 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001335 // Find the nearest non-transparent declaration scope.
1336 while (!(S->getFlags() & Scope::DeclScope) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001337 (S->getEntity() && S->getEntity()->isTransparentContext()))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001338 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001339 }
1340
Richard Smith541b38b2013-09-20 01:15:31 +00001341 // When performing a scope lookup, we want to find local extern decls.
1342 FindLocalExternScope FindLocals(R);
1343
Douglas Gregor34074322009-01-14 22:20:51 +00001344 // Scan up the scope chain looking for a decl that matches this
1345 // identifier that is in the appropriate namespace. This search
1346 // should not take long, as shadowing of names is uncommon, and
1347 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001348 bool LeftStartingScope = false;
1349
Douglas Gregored8f2882009-01-30 01:04:22 +00001350 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001351 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001352 I != IEnd; ++I)
Richard Smith0e5d7b82013-07-25 23:08:39 +00001353 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001354 if (NameKind == LookupRedeclarationWithLinkage) {
1355 // Determine whether this (or a previous) declaration is
1356 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001357 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001358 LeftStartingScope = true;
1359
1360 // If we found something outside of our starting scope that
1361 // does not have linkage, skip it.
Richard Smith1c34fb72013-08-13 18:18:50 +00001362 if (LeftStartingScope && !((*I)->hasLinkage())) {
1363 R.setShadowed();
Douglas Gregoreddf4332009-02-24 20:03:32 +00001364 continue;
Richard Smith1c34fb72013-08-13 18:18:50 +00001365 }
Douglas Gregoreddf4332009-02-24 20:03:32 +00001366 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001367 else if (NameKind == LookupObjCImplicitSelfParam &&
1368 !isa<ImplicitParamDecl>(*I))
1369 continue;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001370
Douglas Gregor4a814562011-12-14 16:03:29 +00001371 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001372
Douglas Gregorb59643b2012-01-03 23:26:26 +00001373 // Check whether there are any other declarations with the same name
1374 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001375 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001376 // Find the scope in which this declaration was declared (if it
1377 // actually exists in a Scope).
1378 while (S && !S->isDeclScope(D))
1379 S = S->getParent();
1380
1381 // If the scope containing the declaration is the translation unit,
1382 // then we'll need to perform our checks based on the matching
1383 // DeclContexts rather than matching scopes.
1384 if (S && isNamespaceOrTranslationUnitScope(S))
1385 S = 0;
1386
1387 // Compute the DeclContext, if we need it.
1388 DeclContext *DC = 0;
1389 if (!S)
1390 DC = (*I)->getDeclContext()->getRedeclContext();
1391
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001392 IdentifierResolver::iterator LastI = I;
1393 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001394 if (S) {
1395 // Match based on scope.
1396 if (!S->isDeclScope(*LastI))
1397 break;
1398 } else {
1399 // Match based on DeclContext.
1400 DeclContext *LastDC
1401 = (*LastI)->getDeclContext()->getRedeclContext();
1402 if (!LastDC->Equals(DC))
1403 break;
1404 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001405
1406 // If the declaration is in the right namespace and visible, add it.
1407 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1408 R.addDecl(LastD);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001409 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001410
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001411 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001412 }
Richard Smith541b38b2013-09-20 01:15:31 +00001413
John McCall9f3059a2009-10-09 21:13:30 +00001414 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001415 }
Douglas Gregor34074322009-01-14 22:20:51 +00001416 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001417 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001418 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001419 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001420 }
1421
1422 // If we didn't find a use of this identifier, and if the identifier
1423 // corresponds to a compiler builtin, create the decl object for the builtin
1424 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001425 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1426 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001427
Axel Naumann016538a2011-02-24 16:47:47 +00001428 // If we didn't find a use of this identifier, the ExternalSource
1429 // may be able to handle the situation.
1430 // Note: some lookup failures are expected!
1431 // See e.g. R.isForRedeclaration().
1432 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001433}
1434
John McCall6538c932009-10-10 05:48:19 +00001435/// @brief Perform qualified name lookup in the namespaces nominated by
1436/// using directives by the given context.
1437///
1438/// C++98 [namespace.qual]p2:
James Dennett51a8d8b2012-06-19 21:05:49 +00001439/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6538c932009-10-10 05:48:19 +00001440/// (where X is the global namespace), let S be the set of all
1441/// declarations of m in X and in the transitive closure of all
1442/// namespaces nominated by using-directives in X and its used
1443/// namespaces, except that using-directives are ignored in any
1444/// namespace, including X, directly containing one or more
1445/// declarations of m. No namespace is searched more than once in
1446/// the lookup of a name. If S is the empty set, the program is
1447/// ill-formed. Otherwise, if S has exactly one member, or if the
1448/// context of the reference is a using-declaration
1449/// (namespace.udecl), S is the required set of declarations of
1450/// m. Otherwise if the use of m is not one that allows a unique
1451/// declaration to be chosen from S, the program is ill-formed.
James Dennett51a8d8b2012-06-19 21:05:49 +00001452///
John McCall6538c932009-10-10 05:48:19 +00001453/// C++98 [namespace.qual]p5:
1454/// During the lookup of a qualified namespace member name, if the
1455/// lookup finds more than one declaration of the member, and if one
1456/// declaration introduces a class name or enumeration name and the
1457/// other declarations either introduce the same object, the same
1458/// enumerator or a set of functions, the non-type name hides the
1459/// class or enumeration name if and only if the declarations are
1460/// from the same namespace; otherwise (the declarations are from
1461/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001462static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001463 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001464 assert(StartDC->isFileContext() && "start context is not a file context");
1465
1466 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1467 DeclContext::udir_iterator E = StartDC->using_directives_end();
1468
1469 if (I == E) return false;
1470
1471 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001472 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001473 Visited.insert(StartDC);
1474
1475 // We have not yet looked into these namespaces, much less added
1476 // their "using-children" to the queue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001477 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001478
1479 // We have already looked into the initial namespace; seed the queue
1480 // with its using-children.
1481 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +00001482 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001483 if (Visited.insert(ND))
John McCall6538c932009-10-10 05:48:19 +00001484 Queue.push_back(ND);
1485 }
1486
1487 // The easiest way to implement the restriction in [namespace.qual]p5
1488 // is to check whether any of the individual results found a tag
1489 // and, if so, to declare an ambiguity if the final result is not
1490 // a tag.
1491 bool FoundTag = false;
1492 bool FoundNonTag = false;
1493
John McCall5cebab12009-11-18 07:57:50 +00001494 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001495
1496 bool Found = false;
1497 while (!Queue.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001498 NamespaceDecl *ND = Queue.pop_back_val();
John McCall6538c932009-10-10 05:48:19 +00001499
1500 // We go through some convolutions here to avoid copying results
1501 // between LookupResults.
1502 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001503 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001504 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001505
1506 if (FoundDirect) {
1507 // First do any local hiding.
1508 DirectR.resolveKind();
1509
1510 // If the local result is a tag, remember that.
1511 if (DirectR.isSingleTagDecl())
1512 FoundTag = true;
1513 else
1514 FoundNonTag = true;
1515
1516 // Append the local results to the total results if necessary.
1517 if (UseLocal) {
1518 R.addAllDecls(LocalR);
1519 LocalR.clear();
1520 }
1521 }
1522
1523 // If we find names in this namespace, ignore its using directives.
1524 if (FoundDirect) {
1525 Found = true;
1526 continue;
1527 }
1528
1529 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1530 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001531 if (Visited.insert(Nom))
John McCall6538c932009-10-10 05:48:19 +00001532 Queue.push_back(Nom);
1533 }
1534 }
1535
1536 if (Found) {
1537 if (FoundTag && FoundNonTag)
1538 R.setAmbiguousQualifiedTagHiding();
1539 else
1540 R.resolveKind();
1541 }
1542
1543 return Found;
1544}
1545
Douglas Gregor39982192010-08-15 06:18:01 +00001546/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001547static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor39982192010-08-15 06:18:01 +00001548 CXXBasePath &Path,
1549 void *Name) {
1550 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001551
Douglas Gregor39982192010-08-15 06:18:01 +00001552 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1553 Path.Decls = BaseRecord->lookup(N);
David Blaikieff7d47a2012-12-19 00:45:41 +00001554 return !Path.Decls.empty();
Douglas Gregor39982192010-08-15 06:18:01 +00001555}
1556
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001557/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001558/// static members, nested types, and enumerators.
1559template<typename InputIterator>
1560static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1561 Decl *D = (*First)->getUnderlyingDecl();
1562 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1563 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001564
Douglas Gregorc0d24902010-10-22 22:08:47 +00001565 if (isa<CXXMethodDecl>(D)) {
1566 // Determine whether all of the methods are static.
1567 bool AllMethodsAreStatic = true;
1568 for(; First != Last; ++First) {
1569 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001570
Douglas Gregorc0d24902010-10-22 22:08:47 +00001571 if (!isa<CXXMethodDecl>(D)) {
1572 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1573 break;
1574 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001575
Douglas Gregorc0d24902010-10-22 22:08:47 +00001576 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1577 AllMethodsAreStatic = false;
1578 break;
1579 }
1580 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001581
Douglas Gregorc0d24902010-10-22 22:08:47 +00001582 if (AllMethodsAreStatic)
1583 return true;
1584 }
1585
1586 return false;
1587}
1588
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001589/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001590///
1591/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1592/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001593/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001594///
1595/// Different lookup criteria can find different names. For example, a
1596/// particular scope can have both a struct and a function of the same
1597/// name, and each can be found by certain lookup criteria. For more
1598/// information about lookup criteria, see the documentation for the
1599/// class LookupCriteria.
1600///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001601/// \param R captures both the lookup criteria and any lookup results found.
1602///
1603/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001604/// search. If the lookup criteria permits, name lookup may also search
1605/// in the parent contexts or (for C++ classes) base classes.
1606///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001607/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001608/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001609///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001610/// \returns true if lookup succeeded, false if it failed.
1611bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1612 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001613 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001614
John McCall27b18f82009-11-17 02:14:36 +00001615 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001616 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001617
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001618 // Make sure that the declaration context is complete.
1619 assert((!isa<TagDecl>(LookupCtx) ||
1620 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00001621 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith7d137e32012-03-23 03:33:32 +00001622 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001623 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001624
Douglas Gregor34074322009-01-14 22:20:51 +00001625 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001626 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001627 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001628 if (isa<CXXRecordDecl>(LookupCtx))
1629 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001630 return true;
1631 }
Douglas Gregor34074322009-01-14 22:20:51 +00001632
John McCall6538c932009-10-10 05:48:19 +00001633 // Don't descend into implied contexts for redeclarations.
1634 // C++98 [namespace.qual]p6:
1635 // In a declaration for a namespace member in which the
1636 // declarator-id is a qualified-id, given that the qualified-id
1637 // for the namespace member has the form
1638 // nested-name-specifier unqualified-id
1639 // the unqualified-id shall name a member of the namespace
1640 // designated by the nested-name-specifier.
1641 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001642 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001643 return false;
1644
John McCall27b18f82009-11-17 02:14:36 +00001645 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001646 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001647 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001648
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001649 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001650 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001651 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001652 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001653 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001654
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001655 // If we're performing qualified name lookup into a dependent class,
1656 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001657 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001658 // template instantiation time (at which point all bases will be available)
1659 // or we have to fail.
1660 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1661 LookupRec->hasAnyDependentBases()) {
1662 R.setNotFoundInCurrentInstantiation();
1663 return false;
1664 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001665
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001666 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001667 CXXBasePaths Paths;
1668 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001669
1670 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001671 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001672 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001673 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001674 case LookupOrdinaryName:
1675 case LookupMemberName:
1676 case LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +00001677 case LookupLocalFriendName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001678 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1679 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001680
Douglas Gregor36d1b142009-10-06 17:59:45 +00001681 case LookupTagName:
1682 BaseCallback = &CXXRecordDecl::FindTagMember;
1683 break;
John McCall84d87672009-12-10 09:41:52 +00001684
Douglas Gregor39982192010-08-15 06:18:01 +00001685 case LookupAnyName:
1686 BaseCallback = &LookupAnyMember;
1687 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001688
John McCall84d87672009-12-10 09:41:52 +00001689 case LookupUsingDeclName:
1690 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001691
Douglas Gregor36d1b142009-10-06 17:59:45 +00001692 case LookupOperatorName:
1693 case LookupNamespaceName:
1694 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001695 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001696 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001697 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001698
Douglas Gregor36d1b142009-10-06 17:59:45 +00001699 case LookupNestedNameSpecifierName:
1700 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1701 break;
1702 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001703
John McCall27b18f82009-11-17 02:14:36 +00001704 if (!LookupRec->lookupInBases(BaseCallback,
1705 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001706 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001707
John McCall553c0792010-01-23 00:46:32 +00001708 R.setNamingClass(LookupRec);
1709
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001710 // C++ [class.member.lookup]p2:
1711 // [...] If the resulting set of declarations are not all from
1712 // sub-objects of the same type, or the set has a nonstatic member
1713 // and includes members from distinct sub-objects, there is an
1714 // ambiguity and the program is ill-formed. Otherwise that set is
1715 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001716 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001717 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001718 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001719
Douglas Gregor36d1b142009-10-06 17:59:45 +00001720 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001721 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001722 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001723
John McCall401982f2010-01-20 21:53:11 +00001724 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1725 // across all paths.
1726 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001727
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001728 // Determine whether we're looking at a distinct sub-object or not.
1729 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001730 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001731 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1732 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001733 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001734 }
1735
Douglas Gregorc0d24902010-10-22 22:08:47 +00001736 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001737 != Context.getCanonicalType(PathElement.Base->getType())) {
1738 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001739 // different types. If the declaration sets aren't the same, this
1740 // this lookup is ambiguous.
David Blaikieff7d47a2012-12-19 00:45:41 +00001741 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00001742 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikieff7d47a2012-12-19 00:45:41 +00001743 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
1744 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001745
David Blaikieff7d47a2012-12-19 00:45:41 +00001746 while (FirstD != FirstPath->Decls.end() &&
1747 CurrentD != Path->Decls.end()) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00001748 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1749 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1750 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001751
Douglas Gregorc0d24902010-10-22 22:08:47 +00001752 ++FirstD;
1753 ++CurrentD;
1754 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001755
David Blaikieff7d47a2012-12-19 00:45:41 +00001756 if (FirstD == FirstPath->Decls.end() &&
1757 CurrentD == Path->Decls.end())
Douglas Gregorc0d24902010-10-22 22:08:47 +00001758 continue;
1759 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001760
John McCall9f3059a2009-10-09 21:13:30 +00001761 R.setAmbiguousBaseSubobjectTypes(Paths);
1762 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001763 }
1764
Douglas Gregorc0d24902010-10-22 22:08:47 +00001765 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001766 // We have a different subobject of the same type.
1767
1768 // C++ [class.member.lookup]p5:
1769 // A static member, a nested type or an enumerator defined in
1770 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001771 // has more than one base class subobject of type T.
David Blaikieff7d47a2012-12-19 00:45:41 +00001772 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001773 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001774
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001775 // We have found a nonstatic member name in multiple, distinct
1776 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001777 R.setAmbiguousBaseSubobjects(Paths);
1778 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001779 }
1780 }
1781
1782 // Lookup in a base class succeeded; return these results.
1783
David Blaikieff7d47a2012-12-19 00:45:41 +00001784 DeclContext::lookup_result DR = Paths.front().Decls;
1785 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E; ++I) {
John McCall553c0792010-01-23 00:46:32 +00001786 NamedDecl *D = *I;
1787 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1788 D->getAccess());
1789 R.addDecl(D, AS);
1790 }
John McCall9f3059a2009-10-09 21:13:30 +00001791 R.resolveKind();
1792 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001793}
1794
1795/// @brief Performs name lookup for a name that was parsed in the
1796/// source code, and may contain a C++ scope specifier.
1797///
1798/// This routine is a convenience routine meant to be called from
1799/// contexts that receive a name and an optional C++ scope specifier
1800/// (e.g., "N::M::x"). It will then perform either qualified or
1801/// unqualified name lookup (with LookupQualifiedName or LookupName,
1802/// respectively) on the given name and return those results.
1803///
1804/// @param S The scope from which unqualified name lookup will
1805/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001806///
Douglas Gregore861bac2009-08-25 22:51:20 +00001807/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001808///
Douglas Gregore861bac2009-08-25 22:51:20 +00001809/// @param EnteringContext Indicates whether we are going to enter the
1810/// context of the scope-specifier SS (if present).
1811///
John McCall9f3059a2009-10-09 21:13:30 +00001812/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001813bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001814 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001815 if (SS && SS->isInvalid()) {
1816 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001817 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001818 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001819 }
Mike Stump11289f42009-09-09 15:08:12 +00001820
Douglas Gregore861bac2009-08-25 22:51:20 +00001821 if (SS && SS->isSet()) {
1822 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001823 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001824 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001825 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001826 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001827
John McCall27b18f82009-11-17 02:14:36 +00001828 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00001829 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001830 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001831
Douglas Gregore861bac2009-08-25 22:51:20 +00001832 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001833 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001834 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00001835 R.setNotFoundInCurrentInstantiation();
1836 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00001837 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001838 }
1839
Mike Stump11289f42009-09-09 15:08:12 +00001840 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001841 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001842}
1843
Douglas Gregor889ceb72009-02-03 19:21:40 +00001844
James Dennett41725122012-06-22 10:16:05 +00001845/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001846/// from name lookup.
1847///
James Dennett41725122012-06-22 10:16:05 +00001848/// \param Result The result of the ambiguous lookup to be diagnosed.
Serge Pavlov99292092013-08-29 07:23:24 +00001849void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001850 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1851
John McCall27b18f82009-11-17 02:14:36 +00001852 DeclarationName Name = Result.getLookupName();
1853 SourceLocation NameLoc = Result.getNameLoc();
1854 SourceRange LookupRange = Result.getContextRange();
1855
John McCall6538c932009-10-10 05:48:19 +00001856 switch (Result.getAmbiguityKind()) {
1857 case LookupResult::AmbiguousBaseSubobjects: {
1858 CXXBasePaths *Paths = Result.getBasePaths();
1859 QualType SubobjectType = Paths->front().back().Base->getType();
1860 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1861 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1862 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001863
David Blaikieff7d47a2012-12-19 00:45:41 +00001864 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6538c932009-10-10 05:48:19 +00001865 while (isa<CXXMethodDecl>(*Found) &&
1866 cast<CXXMethodDecl>(*Found)->isStatic())
1867 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001868
John McCall6538c932009-10-10 05:48:19 +00001869 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
Serge Pavlov99292092013-08-29 07:23:24 +00001870 break;
John McCall6538c932009-10-10 05:48:19 +00001871 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001872
John McCall6538c932009-10-10 05:48:19 +00001873 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001874 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1875 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001876
John McCall6538c932009-10-10 05:48:19 +00001877 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001878 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001879 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1880 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001881 Path != PathEnd; ++Path) {
David Blaikieff7d47a2012-12-19 00:45:41 +00001882 Decl *D = Path->Decls.front();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001883 if (DeclsPrinted.insert(D).second)
1884 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1885 }
Serge Pavlov99292092013-08-29 07:23:24 +00001886 break;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001887 }
1888
John McCall6538c932009-10-10 05:48:19 +00001889 case LookupResult::AmbiguousTagHiding: {
1890 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001891
John McCall6538c932009-10-10 05:48:19 +00001892 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1893
1894 LookupResult::iterator DI, DE = Result.end();
1895 for (DI = Result.begin(); DI != DE; ++DI)
1896 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1897 TagDecls.insert(TD);
1898 Diag(TD->getLocation(), diag::note_hidden_tag);
1899 }
1900
1901 for (DI = Result.begin(); DI != DE; ++DI)
1902 if (!isa<TagDecl>(*DI))
1903 Diag((*DI)->getLocation(), diag::note_hiding_object);
1904
1905 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001906 LookupResult::Filter F = Result.makeFilter();
1907 while (F.hasNext()) {
1908 if (TagDecls.count(F.next()))
1909 F.erase();
1910 }
1911 F.done();
Serge Pavlov99292092013-08-29 07:23:24 +00001912 break;
John McCall6538c932009-10-10 05:48:19 +00001913 }
1914
1915 case LookupResult::AmbiguousReference: {
1916 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001917
John McCall6538c932009-10-10 05:48:19 +00001918 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1919 for (; DI != DE; ++DI)
1920 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
Serge Pavlov99292092013-08-29 07:23:24 +00001921 break;
John McCall6538c932009-10-10 05:48:19 +00001922 }
Serge Pavlov99292092013-08-29 07:23:24 +00001923 }
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001924}
Douglas Gregore254f902009-02-04 00:32:51 +00001925
John McCallf24d7bb2010-05-28 18:45:08 +00001926namespace {
1927 struct AssociatedLookup {
John McCall7d8b0412012-08-24 20:38:34 +00001928 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallf24d7bb2010-05-28 18:45:08 +00001929 Sema::AssociatedNamespaceSet &Namespaces,
1930 Sema::AssociatedClassSet &Classes)
John McCall7d8b0412012-08-24 20:38:34 +00001931 : S(S), Namespaces(Namespaces), Classes(Classes),
1932 InstantiationLoc(InstantiationLoc) {
John McCallf24d7bb2010-05-28 18:45:08 +00001933 }
1934
1935 Sema &S;
1936 Sema::AssociatedNamespaceSet &Namespaces;
1937 Sema::AssociatedClassSet &Classes;
John McCall7d8b0412012-08-24 20:38:34 +00001938 SourceLocation InstantiationLoc;
John McCallf24d7bb2010-05-28 18:45:08 +00001939 };
1940}
1941
Mike Stump11289f42009-09-09 15:08:12 +00001942static void
John McCallf24d7bb2010-05-28 18:45:08 +00001943addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001944
Douglas Gregor8b895222010-04-30 07:08:38 +00001945static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1946 DeclContext *Ctx) {
1947 // Add the associated namespace for this class.
1948
1949 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1950 // be a locally scoped record.
1951
Sebastian Redlbd595762010-08-31 20:53:31 +00001952 // We skip out of inline namespaces. The innermost non-inline namespace
1953 // contains all names of all its nested inline namespaces anyway, so we can
1954 // replace the entire inline namespace tree with its root.
1955 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1956 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00001957 Ctx = Ctx->getParent();
1958
John McCallc7e8e792009-08-07 22:18:02 +00001959 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001960 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001961}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001962
Mike Stump11289f42009-09-09 15:08:12 +00001963// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001964// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001965static void
John McCallf24d7bb2010-05-28 18:45:08 +00001966addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1967 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001968 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001969 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001970 switch (Arg.getKind()) {
1971 case TemplateArgument::Null:
1972 break;
Mike Stump11289f42009-09-09 15:08:12 +00001973
Douglas Gregor197e5f72009-07-08 07:51:57 +00001974 case TemplateArgument::Type:
1975 // [...] the namespaces and classes associated with the types of the
1976 // template arguments provided for template type parameters (excluding
1977 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001978 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001979 break;
Mike Stump11289f42009-09-09 15:08:12 +00001980
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001981 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001982 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00001983 // [...] the namespaces in which any template template arguments are
1984 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001985 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001986 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00001987 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001988 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001989 DeclContext *Ctx = ClassTemplate->getDeclContext();
1990 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001991 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001992 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001993 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001994 }
1995 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001996 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001997
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001998 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001999 case TemplateArgument::Integral:
2000 case TemplateArgument::Expression:
Eli Friedmanb826a002012-09-26 02:36:12 +00002001 case TemplateArgument::NullPtr:
Mike Stump11289f42009-09-09 15:08:12 +00002002 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00002003 // associated namespaces. ]
2004 break;
Mike Stump11289f42009-09-09 15:08:12 +00002005
Douglas Gregor197e5f72009-07-08 07:51:57 +00002006 case TemplateArgument::Pack:
2007 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
2008 PEnd = Arg.pack_end();
2009 P != PEnd; ++P)
John McCallf24d7bb2010-05-28 18:45:08 +00002010 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002011 break;
2012 }
2013}
2014
Douglas Gregore254f902009-02-04 00:32:51 +00002015// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00002016// argument-dependent lookup with an argument of class type
2017// (C++ [basic.lookup.koenig]p2).
2018static void
John McCallf24d7bb2010-05-28 18:45:08 +00002019addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2020 CXXRecordDecl *Class) {
2021
2022 // Just silently ignore anything whose name is __va_list_tag.
2023 if (Class->getDeclName() == Result.S.VAListTagName)
2024 return;
2025
Douglas Gregore254f902009-02-04 00:32:51 +00002026 // C++ [basic.lookup.koenig]p2:
2027 // [...]
2028 // -- If T is a class type (including unions), its associated
2029 // classes are: the class itself; the class of which it is a
2030 // member, if any; and its direct and indirect base
2031 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00002032 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00002033
2034 // Add the class of which it is a member, if any.
2035 DeclContext *Ctx = Class->getDeclContext();
2036 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002037 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002038 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002039 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002040
Douglas Gregore254f902009-02-04 00:32:51 +00002041 // Add the class itself. If we've already seen this class, we don't
2042 // need to visit base classes.
John McCallf24d7bb2010-05-28 18:45:08 +00002043 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00002044 return;
2045
Mike Stump11289f42009-09-09 15:08:12 +00002046 // -- If T is a template-id, its associated namespaces and classes are
2047 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002048 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00002049 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00002050 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00002051 // namespaces in which any template template arguments are defined; and
2052 // the classes in which any member templates used as template template
2053 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00002054 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00002055 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00002056 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2057 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2058 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002059 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002060 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002061 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002062
Douglas Gregor197e5f72009-07-08 07:51:57 +00002063 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2064 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00002065 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002066 }
Mike Stump11289f42009-09-09 15:08:12 +00002067
John McCall67da35c2010-02-04 22:26:26 +00002068 // Only recurse into base classes for complete types.
2069 if (!Class->hasDefinition()) {
John McCall7d8b0412012-08-24 20:38:34 +00002070 QualType type = Result.S.Context.getTypeDeclType(Class);
2071 if (Result.S.RequireCompleteType(Result.InstantiationLoc, type,
2072 /*no diagnostic*/ 0))
2073 return;
John McCall67da35c2010-02-04 22:26:26 +00002074 }
2075
Douglas Gregore254f902009-02-04 00:32:51 +00002076 // Add direct and indirect base classes along with their associated
2077 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002078 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00002079 Bases.push_back(Class);
2080 while (!Bases.empty()) {
2081 // Pop this class off the stack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002082 Class = Bases.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002083
2084 // Visit the base classes.
2085 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
2086 BaseEnd = Class->bases_end();
2087 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002088 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00002089 // In dependent contexts, we do ADL twice, and the first time around,
2090 // the base type might be a dependent TemplateSpecializationType, or a
2091 // TemplateTypeParmType. If that happens, simply ignore it.
2092 // FIXME: If we want to support export, we probably need to add the
2093 // namespace of the template in a TemplateSpecializationType, or even
2094 // the classes and namespaces of known non-dependent arguments.
2095 if (!BaseType)
2096 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002097 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002098 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00002099 // Find the associated namespace for this base class.
2100 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00002101 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00002102
2103 // Make sure we visit the bases of this base class.
2104 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2105 Bases.push_back(BaseDecl);
2106 }
2107 }
2108 }
2109}
2110
2111// \brief Add the associated classes and namespaces for
2112// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00002113// (C++ [basic.lookup.koenig]p2).
2114static void
John McCallf24d7bb2010-05-28 18:45:08 +00002115addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00002116 // C++ [basic.lookup.koenig]p2:
2117 //
2118 // For each argument type T in the function call, there is a set
2119 // of zero or more associated namespaces and a set of zero or more
2120 // associated classes to be considered. The sets of namespaces and
2121 // classes is determined entirely by the types of the function
2122 // arguments (and the namespace of any template template
2123 // argument). Typedef names and using-declarations used to specify
2124 // the types do not contribute to this set. The sets of namespaces
2125 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00002126
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002127 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00002128 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2129
Douglas Gregore254f902009-02-04 00:32:51 +00002130 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00002131 switch (T->getTypeClass()) {
2132
2133#define TYPE(Class, Base)
2134#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2135#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2136#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2137#define ABSTRACT_TYPE(Class, Base)
2138#include "clang/AST/TypeNodes.def"
2139 // T is canonical. We can also ignore dependent types because
2140 // we don't need to do ADL at the definition point, but if we
2141 // wanted to implement template export (or if we find some other
2142 // use for associated classes and namespaces...) this would be
2143 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00002144 break;
Douglas Gregore254f902009-02-04 00:32:51 +00002145
John McCall0af3d3b2010-05-28 06:08:54 +00002146 // -- If T is a pointer to U or an array of U, its associated
2147 // namespaces and classes are those associated with U.
2148 case Type::Pointer:
2149 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2150 continue;
2151 case Type::ConstantArray:
2152 case Type::IncompleteArray:
2153 case Type::VariableArray:
2154 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2155 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002156
John McCall0af3d3b2010-05-28 06:08:54 +00002157 // -- If T is a fundamental type, its associated sets of
2158 // namespaces and classes are both empty.
2159 case Type::Builtin:
2160 break;
2161
2162 // -- If T is a class type (including unions), its associated
2163 // classes are: the class itself; the class of which it is a
2164 // member, if any; and its direct and indirect base
2165 // classes. Its associated namespaces are the namespaces in
2166 // which its associated classes are defined.
2167 case Type::Record: {
2168 CXXRecordDecl *Class
2169 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002170 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00002171 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00002172 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00002173
John McCall0af3d3b2010-05-28 06:08:54 +00002174 // -- If T is an enumeration type, its associated namespace is
2175 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002176 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00002177 // it has no associated class.
2178 case Type::Enum: {
2179 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002180
John McCall0af3d3b2010-05-28 06:08:54 +00002181 DeclContext *Ctx = Enum->getDeclContext();
2182 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002183 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002184
John McCall0af3d3b2010-05-28 06:08:54 +00002185 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002186 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00002187
John McCall0af3d3b2010-05-28 06:08:54 +00002188 break;
2189 }
2190
2191 // -- If T is a function type, its associated namespaces and
2192 // classes are those associated with the function parameter
2193 // types and those associated with the return type.
2194 case Type::FunctionProto: {
2195 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker9cacbab2014-01-20 20:26:09 +00002196 for (FunctionProtoType::param_type_iterator
2197 Arg = Proto->param_type_begin(),
2198 ArgEnd = Proto->param_type_end();
2199 Arg != ArgEnd; ++Arg)
John McCall0af3d3b2010-05-28 06:08:54 +00002200 Queue.push_back(Arg->getTypePtr());
2201 // fallthrough
2202 }
2203 case Type::FunctionNoProto: {
2204 const FunctionType *FnType = cast<FunctionType>(T);
2205 T = FnType->getResultType().getTypePtr();
2206 continue;
2207 }
2208
2209 // -- If T is a pointer to a member function of a class X, its
2210 // associated namespaces and classes are those associated
2211 // with the function parameter types and return type,
2212 // together with those associated with X.
2213 //
2214 // -- If T is a pointer to a data member of class X, its
2215 // associated namespaces and classes are those associated
2216 // with the member type together with those associated with
2217 // X.
2218 case Type::MemberPointer: {
2219 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2220
2221 // Queue up the class type into which this points.
2222 Queue.push_back(MemberPtr->getClass());
2223
2224 // And directly continue with the pointee type.
2225 T = MemberPtr->getPointeeType().getTypePtr();
2226 continue;
2227 }
2228
2229 // As an extension, treat this like a normal pointer.
2230 case Type::BlockPointer:
2231 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2232 continue;
2233
2234 // References aren't covered by the standard, but that's such an
2235 // obvious defect that we cover them anyway.
2236 case Type::LValueReference:
2237 case Type::RValueReference:
2238 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2239 continue;
2240
2241 // These are fundamental types.
2242 case Type::Vector:
2243 case Type::ExtVector:
2244 case Type::Complex:
2245 break;
2246
Richard Smith27d807c2013-04-30 13:56:41 +00002247 // Non-deduced auto types only get here for error cases.
2248 case Type::Auto:
2249 break;
2250
Douglas Gregor8e936662011-04-12 01:02:45 +00002251 // If T is an Objective-C object or interface type, or a pointer to an
2252 // object or interface type, the associated namespace is the global
2253 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002254 case Type::ObjCObject:
2255 case Type::ObjCInterface:
2256 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002257 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002258 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002259
2260 // Atomic types are just wrappers; use the associations of the
2261 // contained type.
2262 case Type::Atomic:
2263 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2264 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002265 }
2266
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002267 if (Queue.empty())
2268 break;
2269 T = Queue.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002270 }
Douglas Gregore254f902009-02-04 00:32:51 +00002271}
2272
2273/// \brief Find the associated classes and namespaces for
2274/// argument-dependent lookup for a call with the given set of
2275/// arguments.
2276///
2277/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002278/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002279/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00002280void Sema::FindAssociatedClassesAndNamespaces(
2281 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2282 AssociatedNamespaceSet &AssociatedNamespaces,
2283 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002284 AssociatedNamespaces.clear();
2285 AssociatedClasses.clear();
2286
John McCall7d8b0412012-08-24 20:38:34 +00002287 AssociatedLookup Result(*this, InstantiationLoc,
2288 AssociatedNamespaces, AssociatedClasses);
John McCallf24d7bb2010-05-28 18:45:08 +00002289
Douglas Gregore254f902009-02-04 00:32:51 +00002290 // C++ [basic.lookup.koenig]p2:
2291 // For each argument type T in the function call, there is a set
2292 // of zero or more associated namespaces and a set of zero or more
2293 // associated classes to be considered. The sets of namespaces and
2294 // classes is determined entirely by the types of the function
2295 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002296 // argument).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002297 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregore254f902009-02-04 00:32:51 +00002298 Expr *Arg = Args[ArgIdx];
2299
2300 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002301 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002302 continue;
2303 }
2304
2305 // [...] In addition, if the argument is the name or address of a
2306 // set of overloaded functions and/or function templates, its
2307 // associated classes and namespaces are the union of those
2308 // associated with each of the members of the set: the namespace
2309 // in which the function or function template is defined and the
2310 // classes and namespaces associated with its (non-dependent)
2311 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002312 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002313 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002314 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002315 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002316
John McCallf24d7bb2010-05-28 18:45:08 +00002317 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2318 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002319
John McCallf24d7bb2010-05-28 18:45:08 +00002320 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2321 I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002322 // Look through any using declarations to find the underlying function.
2323 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002324
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002325 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2326 if (!FDecl)
2327 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002328
2329 // Add the classes and namespaces associated with the parameter
2330 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002331 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002332 }
2333 }
2334}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002335
2336/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2337/// an acceptable non-member overloaded operator for a call whose
2338/// arguments have types T1 (and, if non-empty, T2). This routine
2339/// implements the check in C++ [over.match.oper]p3b2 concerning
2340/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00002341static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002342IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2343 QualType T1, QualType T2,
2344 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00002345 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2346 return true;
2347
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002348 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2349 return true;
2350
John McCall9dd450b2009-09-21 23:43:11 +00002351 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002352 if (Proto->getNumParams() < 1)
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002353 return false;
2354
2355 if (T1->isEnumeralType()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002356 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002357 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002358 return true;
2359 }
2360
Alp Toker9cacbab2014-01-20 20:26:09 +00002361 if (Proto->getNumParams() < 2)
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002362 return false;
2363
2364 if (!T2.isNull() && T2->isEnumeralType()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002365 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002366 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002367 return true;
2368 }
2369
2370 return false;
2371}
2372
John McCall5cebab12009-11-18 07:57:50 +00002373NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002374 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002375 LookupNameKind NameKind,
2376 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002377 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002378 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002379 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002380}
2381
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002382/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002383ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002384 SourceLocation IdLoc,
2385 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002386 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002387 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002388 return cast_or_null<ObjCProtocolDecl>(D);
2389}
2390
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002391void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002392 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002393 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002394 // C++ [over.match.oper]p3:
2395 // -- The set of non-member candidates is the result of the
2396 // unqualified lookup of operator@ in the context of the
2397 // expression according to the usual rules for name lookup in
2398 // unqualified function calls (3.4.2) except that all member
2399 // functions are ignored. However, if no operand has a class
2400 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00002401 // that have a first parameter of type T1 or "reference to
2402 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002403 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00002404 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002405 // when T2 is an enumeration type, are candidate functions.
2406 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002407 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2408 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002409
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002410 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2411
John McCall9f3059a2009-10-09 21:13:30 +00002412 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002413 return;
2414
2415 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2416 Op != OpEnd; ++Op) {
Douglas Gregor645d76f2010-04-25 20:25:43 +00002417 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2418 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002419 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor645d76f2010-04-25 20:25:43 +00002420 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00002421 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor645d76f2010-04-25 20:25:43 +00002422 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor15448f82009-06-27 21:05:07 +00002423 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00002424 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00002425 // later?
2426 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor645d76f2010-04-25 20:25:43 +00002427 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor15448f82009-06-27 21:05:07 +00002428 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002429 }
2430}
2431
Alexis Hunt1da39282011-06-24 02:11:39 +00002432Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002433 CXXSpecialMember SM,
2434 bool ConstArg,
2435 bool VolatileArg,
2436 bool RValueThis,
2437 bool ConstThis,
2438 bool VolatileThis) {
Richard Smith7d125a12012-11-27 21:20:31 +00002439 assert(CanDeclareSpecialMemberFunction(RD) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002440 "doing special member lookup into record that isn't fully complete");
Richard Smith7d125a12012-11-27 21:20:31 +00002441 RD = RD->getDefinition();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002442 if (RValueThis || ConstThis || VolatileThis)
2443 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2444 "constructors and destructors always have unqualified lvalue this");
2445 if (ConstArg || VolatileArg)
2446 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2447 "parameter-less special members can't have qualified arguments");
2448
2449 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002450 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002451 ID.AddInteger(SM);
2452 ID.AddInteger(ConstArg);
2453 ID.AddInteger(VolatileArg);
2454 ID.AddInteger(RValueThis);
2455 ID.AddInteger(ConstThis);
2456 ID.AddInteger(VolatileThis);
2457
2458 void *InsertPoint;
2459 SpecialMemberOverloadResult *Result =
2460 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2461
2462 // This was already cached
2463 if (Result)
2464 return Result;
2465
Alexis Huntba8e18d2011-06-07 00:11:58 +00002466 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2467 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002468 SpecialMemberCache.InsertNode(Result, InsertPoint);
2469
2470 if (SM == CXXDestructor) {
Richard Smith2be35f52012-12-01 02:35:44 +00002471 if (RD->needsImplicitDestructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002472 DeclareImplicitDestructor(RD);
2473 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002474 assert(DD && "record without a destructor");
2475 Result->setMethod(DD);
Richard Smith852265f2012-03-30 20:53:28 +00002476 Result->setKind(DD->isDeleted() ?
2477 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith83c478d2012-04-20 18:46:14 +00002478 SpecialMemberOverloadResult::Success);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002479 return Result;
2480 }
2481
Alexis Hunteef8ee02011-06-10 03:50:41 +00002482 // Prepare for overload resolution. Here we construct a synthetic argument
2483 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002484 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002485 DeclarationName Name;
2486 Expr *Arg = 0;
2487 unsigned NumArgs;
2488
Richard Smith83c478d2012-04-20 18:46:14 +00002489 QualType ArgType = CanTy;
2490 ExprValueKind VK = VK_LValue;
2491
Alexis Hunteef8ee02011-06-10 03:50:41 +00002492 if (SM == CXXDefaultConstructor) {
2493 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2494 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002495 if (RD->needsImplicitDefaultConstructor())
2496 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002497 } else {
2498 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2499 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smith2be35f52012-12-01 02:35:44 +00002500 if (RD->needsImplicitCopyConstructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002501 DeclareImplicitCopyConstructor(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002502 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002503 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002504 } else {
2505 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smith2be35f52012-12-01 02:35:44 +00002506 if (RD->needsImplicitCopyAssignment())
Alexis Hunt1da39282011-06-24 02:11:39 +00002507 DeclareImplicitCopyAssignment(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002508 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002509 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002510 }
2511
Alexis Hunteef8ee02011-06-10 03:50:41 +00002512 if (ConstArg)
2513 ArgType.addConst();
2514 if (VolatileArg)
2515 ArgType.addVolatile();
2516
2517 // This isn't /really/ specified by the standard, but it's implied
2518 // we should be working from an RValue in the case of move to ensure
2519 // that we prefer to bind to rvalue references, and an LValue in the
2520 // case of copy to ensure we don't bind to rvalue references.
2521 // Possibly an XValue is actually correct in the case of move, but
2522 // there is no semantic difference for class types in this restricted
2523 // case.
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002524 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002525 VK = VK_LValue;
2526 else
2527 VK = VK_RValue;
Richard Smith83c478d2012-04-20 18:46:14 +00002528 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00002529
Richard Smith83c478d2012-04-20 18:46:14 +00002530 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2531
2532 if (SM != CXXDefaultConstructor) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002533 NumArgs = 1;
Richard Smith83c478d2012-04-20 18:46:14 +00002534 Arg = &FakeArg;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002535 }
2536
2537 // Create the object argument
2538 QualType ThisTy = CanTy;
2539 if (ConstThis)
2540 ThisTy.addConst();
2541 if (VolatileThis)
2542 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002543 Expr::Classification Classification =
Richard Smith83c478d2012-04-20 18:46:14 +00002544 OpaqueValueExpr(SourceLocation(), ThisTy,
2545 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002546
2547 // Now we perform lookup on the name we computed earlier and do overload
2548 // resolution. Lookup is only performed directly into the class since there
2549 // will always be a (possibly implicit) declaration to shadow any others.
Nick Lewycky56412332014-01-11 02:37:12 +00002550 OverloadCandidateSet OCS(RD->getLocation());
David Blaikieff7d47a2012-12-19 00:45:41 +00002551 DeclContext::lookup_result R = RD->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00002552 assert(!R.empty() &&
Alexis Hunteef8ee02011-06-10 03:50:41 +00002553 "lookup for a constructor or assignment operator was empty");
Chandler Carruth7deaae72013-08-18 07:20:52 +00002554
2555 // Copy the candidates as our processing of them may load new declarations
2556 // from an external source and invalidate lookup_result.
2557 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2558
2559 for (SmallVectorImpl<NamedDecl *>::iterator I = Candidates.begin(),
Richard Smithd55889a2013-09-09 16:55:27 +00002560 E = Candidates.end();
Chandler Carruth7deaae72013-08-18 07:20:52 +00002561 I != E; ++I) {
2562 NamedDecl *Cand = *I;
Alexis Hunt080709f2011-06-23 00:26:20 +00002563
Alexis Hunt1da39282011-06-24 02:11:39 +00002564 if (Cand->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002565 continue;
2566
Alexis Hunt1da39282011-06-24 02:11:39 +00002567 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2568 // FIXME: [namespace.udecl]p15 says that we should only consider a
2569 // using declaration here if it does not match a declaration in the
2570 // derived class. We do not implement this correctly in other cases
2571 // either.
2572 Cand = U->getTargetDecl();
2573
2574 if (Cand->isInvalidDecl())
2575 continue;
2576 }
2577
2578 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002579 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Alexis Hunt1da39282011-06-24 02:11:39 +00002580 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002581 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2582 OCS, true);
Alexis Hunt080709f2011-06-23 00:26:20 +00002583 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002584 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2585 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt2949f022011-06-22 02:58:46 +00002586 } else if (FunctionTemplateDecl *Tmpl =
Alexis Hunt1da39282011-06-24 02:11:39 +00002587 dyn_cast<FunctionTemplateDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002588 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2589 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002590 RD, 0, ThisTy, Classification,
2591 llvm::makeArrayRef(&Arg, NumArgs),
Alexis Hunt080709f2011-06-23 00:26:20 +00002592 OCS, true);
2593 else
2594 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002595 0, llvm::makeArrayRef(&Arg, NumArgs),
2596 OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002597 } else {
2598 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002599 }
2600 }
2601
2602 OverloadCandidateSet::iterator Best;
2603 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2604 case OR_Success:
2605 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith83c478d2012-04-20 18:46:14 +00002606 Result->setKind(SpecialMemberOverloadResult::Success);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002607 break;
2608
2609 case OR_Deleted:
2610 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith852265f2012-03-30 20:53:28 +00002611 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002612 break;
2613
2614 case OR_Ambiguous:
Richard Smith852265f2012-03-30 20:53:28 +00002615 Result->setMethod(0);
2616 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2617 break;
2618
Alexis Hunteef8ee02011-06-10 03:50:41 +00002619 case OR_No_Viable_Function:
2620 Result->setMethod(0);
Richard Smith852265f2012-03-30 20:53:28 +00002621 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002622 break;
2623 }
2624
2625 return Result;
2626}
2627
2628/// \brief Look up the default constructor for the given class.
2629CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002630 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002631 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2632 false, false);
2633
2634 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002635}
2636
Alexis Hunt491ec602011-06-21 23:42:56 +00002637/// \brief Look up the copying constructor for the given class.
2638CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith83c478d2012-04-20 18:46:14 +00002639 unsigned Quals) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002640 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2641 "non-const, non-volatile qualifiers for copy ctor arg");
2642 SpecialMemberOverloadResult *Result =
2643 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2644 Quals & Qualifiers::Volatile, false, false, false);
2645
Alexis Hunt899bd442011-06-10 04:44:37 +00002646 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2647}
2648
Sebastian Redl22653ba2011-08-30 19:58:05 +00002649/// \brief Look up the moving constructor for the given class.
Richard Smith1c6461e2012-07-18 03:36:00 +00002650CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2651 unsigned Quals) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002652 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002653 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2654 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002655
2656 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2657}
2658
Douglas Gregor52b72822010-07-02 23:12:18 +00002659/// \brief Look up the constructors for the given class.
2660DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002661 // If the implicit constructors have not yet been declared, do so now.
Richard Smith7d125a12012-11-27 21:20:31 +00002662 if (CanDeclareSpecialMemberFunction(Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00002663 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002664 DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +00002665 if (Class->needsImplicitCopyConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002666 DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002667 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002668 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00002669 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002670
Douglas Gregor52b72822010-07-02 23:12:18 +00002671 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2672 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2673 return Class->lookup(Name);
2674}
2675
Alexis Hunt491ec602011-06-21 23:42:56 +00002676/// \brief Look up the copying assignment operator for the given class.
2677CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2678 unsigned Quals, bool RValueThis,
Richard Smith83c478d2012-04-20 18:46:14 +00002679 unsigned ThisQuals) {
Alexis Hunt491ec602011-06-21 23:42:56 +00002680 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2681 "non-const, non-volatile qualifiers for copy assignment arg");
2682 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2683 "non-const, non-volatile qualifiers for copy assignment this");
2684 SpecialMemberOverloadResult *Result =
2685 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2686 Quals & Qualifiers::Volatile, RValueThis,
2687 ThisQuals & Qualifiers::Const,
2688 ThisQuals & Qualifiers::Volatile);
2689
Alexis Hunt491ec602011-06-21 23:42:56 +00002690 return Result->getMethod();
2691}
2692
Sebastian Redl22653ba2011-08-30 19:58:05 +00002693/// \brief Look up the moving assignment operator for the given class.
2694CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith1c6461e2012-07-18 03:36:00 +00002695 unsigned Quals,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002696 bool RValueThis,
2697 unsigned ThisQuals) {
2698 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2699 "non-const, non-volatile qualifiers for copy assignment this");
2700 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002701 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2702 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002703 ThisQuals & Qualifiers::Const,
2704 ThisQuals & Qualifiers::Volatile);
2705
2706 return Result->getMethod();
2707}
2708
Douglas Gregore71edda2010-07-01 22:47:18 +00002709/// \brief Look for the destructor of the given class.
2710///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00002711/// During semantic analysis, this routine should be used in lieu of
2712/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00002713///
2714/// \returns The destructor for this class.
2715CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002716 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2717 false, false, false,
2718 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00002719}
2720
Richard Smithbcc22fc2012-03-09 08:00:36 +00002721/// LookupLiteralOperator - Determine which literal operator should be used for
2722/// a user-defined literal, per C++11 [lex.ext].
2723///
2724/// Normal overload resolution is not used to select which literal operator to
2725/// call for a user-defined literal. Look up the provided literal operator name,
2726/// and filter the results to the appropriate set for the given argument types.
2727Sema::LiteralOperatorLookupResult
2728Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2729 ArrayRef<QualType> ArgTys,
Richard Smithb8b41d32013-10-07 19:57:58 +00002730 bool AllowRaw, bool AllowTemplate,
2731 bool AllowStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002732 LookupName(R, S);
2733 assert(R.getResultKind() != LookupResult::Ambiguous &&
2734 "literal operator lookup can't be ambiguous");
2735
2736 // Filter the lookup results appropriately.
2737 LookupResult::Filter F = R.makeFilter();
2738
Richard Smithbcc22fc2012-03-09 08:00:36 +00002739 bool FoundRaw = false;
Richard Smithb8b41d32013-10-07 19:57:58 +00002740 bool FoundTemplate = false;
2741 bool FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002742 bool FoundExactMatch = false;
2743
2744 while (F.hasNext()) {
2745 Decl *D = F.next();
2746 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2747 D = USD->getTargetDecl();
2748
Douglas Gregorc1970572013-04-10 05:18:00 +00002749 // If the declaration we found is invalid, skip it.
2750 if (D->isInvalidDecl()) {
2751 F.erase();
2752 continue;
2753 }
2754
Richard Smithb8b41d32013-10-07 19:57:58 +00002755 bool IsRaw = false;
2756 bool IsTemplate = false;
2757 bool IsStringTemplate = false;
2758 bool IsExactMatch = false;
2759
Richard Smithbcc22fc2012-03-09 08:00:36 +00002760 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2761 if (FD->getNumParams() == 1 &&
2762 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2763 IsRaw = true;
Richard Smith550de452013-01-15 07:12:59 +00002764 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002765 IsExactMatch = true;
2766 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2767 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2768 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2769 IsExactMatch = false;
2770 break;
2771 }
2772 }
2773 }
2774 }
Richard Smithb8b41d32013-10-07 19:57:58 +00002775 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
2776 TemplateParameterList *Params = FD->getTemplateParameters();
2777 if (Params->size() == 1)
2778 IsTemplate = true;
2779 else
2780 IsStringTemplate = true;
2781 }
Richard Smithbcc22fc2012-03-09 08:00:36 +00002782
2783 if (IsExactMatch) {
2784 FoundExactMatch = true;
Richard Smithb8b41d32013-10-07 19:57:58 +00002785 AllowRaw = false;
2786 AllowTemplate = false;
2787 AllowStringTemplate = false;
2788 if (FoundRaw || FoundTemplate || FoundStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002789 // Go through again and remove the raw and template decls we've
2790 // already found.
2791 F.restart();
Richard Smithb8b41d32013-10-07 19:57:58 +00002792 FoundRaw = FoundTemplate = FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002793 }
Richard Smithb8b41d32013-10-07 19:57:58 +00002794 } else if (AllowRaw && IsRaw) {
2795 FoundRaw = true;
2796 } else if (AllowTemplate && IsTemplate) {
2797 FoundTemplate = true;
2798 } else if (AllowStringTemplate && IsStringTemplate) {
2799 FoundStringTemplate = true;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002800 } else {
2801 F.erase();
2802 }
2803 }
2804
2805 F.done();
2806
2807 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2808 // parameter type, that is used in preference to a raw literal operator
2809 // or literal operator template.
2810 if (FoundExactMatch)
2811 return LOLR_Cooked;
2812
2813 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2814 // operator template, but not both.
2815 if (FoundRaw && FoundTemplate) {
2816 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
2817 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2818 Decl *D = *I;
2819 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2820 D = USD->getTargetDecl();
2821 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2822 D = FunTmpl->getTemplatedDecl();
2823 NoteOverloadCandidate(cast<FunctionDecl>(D));
2824 }
2825 return LOLR_Error;
2826 }
2827
2828 if (FoundRaw)
2829 return LOLR_Raw;
2830
2831 if (FoundTemplate)
2832 return LOLR_Template;
2833
Richard Smithb8b41d32013-10-07 19:57:58 +00002834 if (FoundStringTemplate)
2835 return LOLR_StringTemplate;
2836
Richard Smithbcc22fc2012-03-09 08:00:36 +00002837 // Didn't find anything we could use.
2838 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2839 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
Richard Smithb8b41d32013-10-07 19:57:58 +00002840 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
2841 << (AllowTemplate || AllowStringTemplate);
Richard Smithbcc22fc2012-03-09 08:00:36 +00002842 return LOLR_Error;
2843}
2844
John McCall8fe68082010-01-26 07:16:45 +00002845void ADLResult::insert(NamedDecl *New) {
2846 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2847
2848 // If we haven't yet seen a decl for this key, or the last decl
2849 // was exactly this one, we're done.
2850 if (Old == 0 || Old == New) {
2851 Old = New;
2852 return;
2853 }
2854
2855 // Otherwise, decide which is a more recent redeclaration.
2856 FunctionDecl *OldFD, *NewFD;
2857 if (isa<FunctionTemplateDecl>(New)) {
2858 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2859 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2860 } else {
2861 OldFD = cast<FunctionDecl>(Old);
2862 NewFD = cast<FunctionDecl>(New);
2863 }
2864
2865 FunctionDecl *Cursor = NewFD;
2866 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002867 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00002868
2869 // If we got to the end without finding OldFD, OldFD is the newer
2870 // declaration; leave things as they are.
2871 if (!Cursor) return;
2872
2873 // If we do find OldFD, then NewFD is newer.
2874 if (Cursor == OldFD) break;
2875
2876 // Otherwise, keep looking.
2877 }
2878
2879 Old = New;
2880}
2881
Sebastian Redlc057f422009-10-23 19:23:15 +00002882void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Robert Wilhelm16e94b92013-08-09 18:02:13 +00002883 SourceLocation Loc, ArrayRef<Expr *> Args,
Richard Smithb6626742012-10-18 17:56:02 +00002884 ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002885 // Find all of the associated namespaces and classes based on the
2886 // arguments we have.
2887 AssociatedNamespaceSet AssociatedNamespaces;
2888 AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00002889 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCallc7e8e792009-08-07 22:18:02 +00002890 AssociatedNamespaces,
2891 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002892
Sebastian Redlc057f422009-10-23 19:23:15 +00002893 QualType T1, T2;
2894 if (Operator) {
2895 T1 = Args[0]->getType();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002896 if (Args.size() >= 2)
Sebastian Redlc057f422009-10-23 19:23:15 +00002897 T2 = Args[1]->getType();
2898 }
2899
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002900 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002901 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2902 // and let Y be the lookup set produced by argument dependent
2903 // lookup (defined as follows). If X contains [...] then Y is
2904 // empty. Otherwise Y is the set of declarations found in the
2905 // namespaces associated with the argument types as described
2906 // below. The set of declarations found by the lookup of the name
2907 // is the union of X and Y.
2908 //
2909 // Here, we compute Y and add its members to the overloaded
2910 // candidate set.
2911 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00002912 NSEnd = AssociatedNamespaces.end();
2913 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002914 // When considering an associated namespace, the lookup is the
2915 // same as the lookup performed when the associated namespace is
2916 // used as a qualifier (3.4.3.2) except that:
2917 //
2918 // -- Any using-directives in the associated namespace are
2919 // ignored.
2920 //
John McCallc7e8e792009-08-07 22:18:02 +00002921 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002922 // associated classes are visible within their respective
2923 // namespaces even if they are not visible during an ordinary
2924 // lookup (11.4).
David Blaikieff7d47a2012-12-19 00:45:41 +00002925 DeclContext::lookup_result R = (*NS)->lookup(Name);
2926 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
2927 ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00002928 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00002929 // If the only declaration here is an ordinary friend, consider
2930 // it only if it was declared in an associated classes.
Richard Smith541b38b2013-09-20 01:15:31 +00002931 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) {
2932 // If it's neither ordinarily visible nor a friend, we can't find it.
2933 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0)
2934 continue;
2935
Richard Smith64017682013-07-17 23:53:16 +00002936 bool DeclaredInAssociatedClass = false;
2937 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
2938 DeclContext *LexDC = DI->getLexicalDeclContext();
2939 if (isa<CXXRecordDecl>(LexDC) &&
2940 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) {
2941 DeclaredInAssociatedClass = true;
2942 break;
2943 }
2944 }
2945 if (!DeclaredInAssociatedClass)
John McCalld1e9d832009-08-11 06:59:38 +00002946 continue;
2947 }
Mike Stump11289f42009-09-09 15:08:12 +00002948
John McCall91f61fc2010-01-26 06:04:06 +00002949 if (isa<UsingShadowDecl>(D))
2950 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002951
John McCall91f61fc2010-01-26 06:04:06 +00002952 if (isa<FunctionDecl>(D)) {
2953 if (Operator &&
2954 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2955 T1, T2, Context))
2956 continue;
John McCall8fe68082010-01-26 07:16:45 +00002957 } else if (!isa<FunctionTemplateDecl>(D))
2958 continue;
2959
2960 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002961 }
2962 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002963}
Douglas Gregor2d435302009-12-30 17:04:44 +00002964
2965//----------------------------------------------------------------------------
2966// Search for all visible declarations.
2967//----------------------------------------------------------------------------
2968VisibleDeclConsumer::~VisibleDeclConsumer() { }
2969
Richard Smithe156254d2013-08-20 20:35:18 +00002970bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
2971
Douglas Gregor2d435302009-12-30 17:04:44 +00002972namespace {
2973
2974class ShadowContextRAII;
2975
2976class VisibleDeclsRecord {
2977public:
2978 /// \brief An entry in the shadow map, which is optimized to store a
2979 /// single declaration (the common case) but can also store a list
2980 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002981 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00002982
2983private:
2984 /// \brief A mapping from declaration names to the declarations that have
2985 /// this name within a particular scope.
2986 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2987
2988 /// \brief A list of shadow maps, which is used to model name hiding.
2989 std::list<ShadowMap> ShadowMaps;
2990
2991 /// \brief The declaration contexts we have already visited.
2992 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2993
2994 friend class ShadowContextRAII;
2995
2996public:
2997 /// \brief Determine whether we have already visited this context
2998 /// (and, if not, note that we are going to visit that context now).
2999 bool visitedContext(DeclContext *Ctx) {
3000 return !VisitedContexts.insert(Ctx);
3001 }
3002
Douglas Gregor39982192010-08-15 06:18:01 +00003003 bool alreadyVisitedContext(DeclContext *Ctx) {
3004 return VisitedContexts.count(Ctx);
3005 }
3006
Douglas Gregor2d435302009-12-30 17:04:44 +00003007 /// \brief Determine whether the given declaration is hidden in the
3008 /// current scope.
3009 ///
3010 /// \returns the declaration that hides the given declaration, or
3011 /// NULL if no such declaration exists.
3012 NamedDecl *checkHidden(NamedDecl *ND);
3013
3014 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00003015 void add(NamedDecl *ND) {
3016 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
3017 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003018};
3019
3020/// \brief RAII object that records when we've entered a shadow context.
3021class ShadowContextRAII {
3022 VisibleDeclsRecord &Visible;
3023
3024 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
3025
3026public:
3027 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
3028 Visible.ShadowMaps.push_back(ShadowMap());
3029 }
3030
3031 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00003032 Visible.ShadowMaps.pop_back();
3033 }
3034};
3035
3036} // end anonymous namespace
3037
Douglas Gregor2d435302009-12-30 17:04:44 +00003038NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00003039 // Look through using declarations.
3040 ND = ND->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003041
Douglas Gregor2d435302009-12-30 17:04:44 +00003042 unsigned IDNS = ND->getIdentifierNamespace();
3043 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
3044 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3045 SM != SMEnd; ++SM) {
3046 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
3047 if (Pos == SM->end())
3048 continue;
3049
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003050 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor2d435302009-12-30 17:04:44 +00003051 IEnd = Pos->second.end();
3052 I != IEnd; ++I) {
3053 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +00003054 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003055 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00003056 Decl::IDNS_ObjCProtocol)))
3057 continue;
3058
3059 // Protocols are in distinct namespaces from everything else.
3060 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
3061 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
3062 (*I)->getIdentifierNamespace() != IDNS)
3063 continue;
3064
Douglas Gregor09bbc652010-01-14 15:47:35 +00003065 // Functions and function templates in the same scope overload
3066 // rather than hide. FIXME: Look for hiding based on function
3067 // signatures!
Douglas Gregor200c99d2010-01-14 03:35:48 +00003068 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00003069 ND->isFunctionOrFunctionTemplate() &&
3070 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00003071 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003072
Douglas Gregor2d435302009-12-30 17:04:44 +00003073 // We've found a declaration that hides this one.
3074 return *I;
3075 }
3076 }
3077
3078 return 0;
3079}
3080
3081static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
3082 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003083 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00003084 VisibleDeclConsumer &Consumer,
3085 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00003086 if (!Ctx)
3087 return;
3088
Douglas Gregor2d435302009-12-30 17:04:44 +00003089 // Make sure we don't visit the same context twice.
3090 if (Visited.visitedContext(Ctx->getPrimaryContext()))
3091 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003092
Douglas Gregor7454c562010-07-02 20:37:36 +00003093 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3094 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3095
Douglas Gregor2d435302009-12-30 17:04:44 +00003096 // Enumerate all of the results in this context.
Nick Lewyckyc3921482012-04-03 21:44:08 +00003097 for (DeclContext::all_lookups_iterator L = Ctx->lookups_begin(),
3098 LEnd = Ctx->lookups_end();
3099 L != LEnd; ++L) {
David Blaikieff7d47a2012-12-19 00:45:41 +00003100 DeclContext::lookup_result R = *L;
3101 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
3102 ++I) {
3103 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00003104 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003105 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00003106 Visited.add(ND);
3107 }
Douglas Gregora3b23b02010-12-09 21:44:02 +00003108 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003109 }
3110 }
3111
3112 // Traverse using directives for qualified name lookup.
3113 if (QualifiedNameLookup) {
3114 ShadowContextRAII Shadow(Visited);
3115 DeclContext::udir_iterator I, E;
3116 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003117 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003118 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003119 }
3120 }
3121
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003122 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00003123 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00003124 if (!Record->hasDefinition())
3125 return;
3126
Douglas Gregor2d435302009-12-30 17:04:44 +00003127 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
3128 BEnd = Record->bases_end();
3129 B != BEnd; ++B) {
3130 QualType BaseType = B->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003131
Douglas Gregor2d435302009-12-30 17:04:44 +00003132 // Don't look into dependent bases, because name lookup can't look
3133 // there anyway.
3134 if (BaseType->isDependentType())
3135 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003136
Douglas Gregor2d435302009-12-30 17:04:44 +00003137 const RecordType *Record = BaseType->getAs<RecordType>();
3138 if (!Record)
3139 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003140
Douglas Gregor2d435302009-12-30 17:04:44 +00003141 // FIXME: It would be nice to be able to determine whether referencing
3142 // a particular member would be ambiguous. For example, given
3143 //
3144 // struct A { int member; };
3145 // struct B { int member; };
3146 // struct C : A, B { };
3147 //
3148 // void f(C *c) { c->### }
3149 //
3150 // accessing 'member' would result in an ambiguity. However, we
3151 // could be smart enough to qualify the member with the base
3152 // class, e.g.,
3153 //
3154 // c->B::member
3155 //
3156 // or
3157 //
3158 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003159
Douglas Gregor2d435302009-12-30 17:04:44 +00003160 // Find results in this base class (and its bases).
3161 ShadowContextRAII Shadow(Visited);
3162 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003163 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003164 }
3165 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003166
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003167 // Traverse the contexts of Objective-C classes.
3168 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3169 // Traverse categories.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003170 for (ObjCInterfaceDecl::visible_categories_iterator
3171 Cat = IFace->visible_categories_begin(),
3172 CatEnd = IFace->visible_categories_end();
3173 Cat != CatEnd; ++Cat) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003174 ShadowContextRAII Shadow(Visited);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003175 LookupVisibleDecls(*Cat, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003176 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003177 }
3178
3179 // Traverse protocols.
Ted Kremenek0ef508d2010-09-01 01:21:15 +00003180 for (ObjCInterfaceDecl::all_protocol_iterator
3181 I = IFace->all_referenced_protocol_begin(),
3182 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003183 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003184 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003185 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003186 }
3187
3188 // Traverse the superclass.
3189 if (IFace->getSuperClass()) {
3190 ShadowContextRAII Shadow(Visited);
3191 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003192 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003193 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003194
Douglas Gregor0b59e802010-04-19 18:02:19 +00003195 // If there is an implementation, traverse it. We do this to find
3196 // synthesized ivars.
3197 if (IFace->getImplementation()) {
3198 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003199 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky13668f22012-04-03 20:26:45 +00003200 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor0b59e802010-04-19 18:02:19 +00003201 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003202 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
3203 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
3204 E = Protocol->protocol_end(); I != E; ++I) {
3205 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003206 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003207 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003208 }
3209 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
3210 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
3211 E = Category->protocol_end(); I != E; ++I) {
3212 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003213 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003214 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003215 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003216
Douglas Gregor0b59e802010-04-19 18:02:19 +00003217 // If there is an implementation, traverse it.
3218 if (Category->getImplementation()) {
3219 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003220 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00003221 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003222 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003223 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003224}
3225
3226static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3227 UnqualUsingDirectiveSet &UDirs,
3228 VisibleDeclConsumer &Consumer,
3229 VisibleDeclsRecord &Visited) {
3230 if (!S)
3231 return;
3232
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003233 if (!S->getEntity() ||
3234 (!S->getParent() &&
Ted Kremenekc37877d2013-10-08 17:08:03 +00003235 !Visited.alreadyVisitedContext(S->getEntity())) ||
3236 (S->getEntity())->isFunctionOrMethod()) {
Richard Smith541b38b2013-09-20 01:15:31 +00003237 FindLocalExternScope FindLocals(Result);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003238 // Walk through the declarations in this Scope.
3239 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
3240 D != DEnd; ++D) {
John McCall48871652010-08-21 09:40:31 +00003241 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor4a814562011-12-14 16:03:29 +00003242 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003243 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003244 Visited.add(ND);
3245 }
3246 }
3247 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003248
Douglas Gregor66230062010-03-15 14:33:29 +00003249 // FIXME: C++ [temp.local]p8
Douglas Gregor2d435302009-12-30 17:04:44 +00003250 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00003251 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003252 // Look into this scope's declaration context, along with any of its
3253 // parent lookup contexts (e.g., enclosing classes), up to the point
3254 // where we hit the context stored in the next outer scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00003255 Entity = S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00003256 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003257
Douglas Gregorea166062010-03-15 15:26:48 +00003258 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00003259 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003260 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3261 if (Method->isInstanceMethod()) {
3262 // For instance methods, look for ivars in the method's interface.
3263 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3264 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003265 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003266 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Richard Smithe156254d2013-08-20 20:35:18 +00003267 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003268 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003269 }
3270
3271 // We've already performed all of the name lookup that we need
3272 // to for Objective-C methods; the next context will be the
3273 // outer scope.
3274 break;
3275 }
3276
Douglas Gregor2d435302009-12-30 17:04:44 +00003277 if (Ctx->isFunctionOrMethod())
3278 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003279
3280 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003281 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003282 }
3283 } else if (!S->getParent()) {
3284 // Look into the translation unit scope. We walk through the translation
3285 // unit's declaration context, because the Scope itself won't have all of
3286 // the declarations if we loaded a precompiled header.
3287 // FIXME: We would like the translation unit's Scope object to point to the
3288 // translation unit, so we don't need this special "if" branch. However,
3289 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003290 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00003291 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003292 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00003293 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003294 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003295 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003296 }
3297
Douglas Gregor2d435302009-12-30 17:04:44 +00003298 if (Entity) {
3299 // Lookup visible declarations in any namespaces found by using
3300 // directives.
3301 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
3302 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
3303 for (; UI != UEnd; ++UI)
3304 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003305 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003306 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003307 }
3308
3309 // Lookup names in the parent scope.
3310 ShadowContextRAII Shadow(Visited);
3311 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3312}
3313
3314void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003315 VisibleDeclConsumer &Consumer,
3316 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003317 // Determine the set of using directives available during
3318 // unqualified name lookup.
3319 Scope *Initial = S;
3320 UnqualUsingDirectiveSet UDirs;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003321 if (getLangOpts().CPlusPlus) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003322 // Find the first namespace or translation-unit scope.
3323 while (S && !isNamespaceOrTranslationUnitScope(S))
3324 S = S->getParent();
3325
3326 UDirs.visitScopeChain(Initial, S);
3327 }
3328 UDirs.done();
3329
3330 // Look for visible declarations.
3331 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003332 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003333 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003334 if (!IncludeGlobalScope)
3335 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003336 ShadowContextRAII Shadow(Visited);
3337 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3338}
3339
3340void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003341 VisibleDeclConsumer &Consumer,
3342 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003343 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003344 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003345 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003346 if (!IncludeGlobalScope)
3347 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003348 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003349 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003350 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003351}
3352
Chris Lattner43e7f312011-02-18 02:08:43 +00003353/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003354/// If GnuLabelLoc is a valid source location, then this is a definition
3355/// of an __label__ label name, otherwise it is a normal label definition
3356/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003357LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003358 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003359 // Do a lookup to see if we have a label with this name already.
Chris Lattner43e7f312011-02-18 02:08:43 +00003360 NamedDecl *Res = 0;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003361
3362 if (GnuLabelLoc.isValid()) {
3363 // Local label definitions always shadow existing labels.
3364 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3365 Scope *S = CurScope;
3366 PushOnScopeChains(Res, S, true);
3367 return cast<LabelDecl>(Res);
3368 }
3369
3370 // Not a GNU local label.
3371 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3372 // If we found a label, check to see if it is in the same context as us.
3373 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003374 if (Res && Res->getDeclContext() != CurContext)
3375 Res = 0;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003376 if (Res == 0) {
3377 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003378 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3379 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003380 assert(S && "Not in a function?");
3381 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003382 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003383 return cast<LabelDecl>(Res);
3384}
3385
3386//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003387// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003388//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003389
3390namespace {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003391
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003392typedef SmallVector<TypoCorrection, 1> TypoResultList;
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003393typedef llvm::StringMap<TypoResultList, llvm::BumpPtrAllocator> TypoResultsMap;
Benjamin Kramer73faad62012-04-14 08:26:28 +00003394typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003395
3396static const unsigned MaxTypoDistanceResultSets = 5;
3397
Douglas Gregor2d435302009-12-30 17:04:44 +00003398class TypoCorrectionConsumer : public VisibleDeclConsumer {
3399 /// \brief The name written that is a typo in the source.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003400 StringRef Typo;
Douglas Gregor2d435302009-12-30 17:04:44 +00003401
3402 /// \brief The results found that have the smallest edit distance
3403 /// found (so far) with the typo name.
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003404 ///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003405 /// The pointer value being set to the current DeclContext indicates
3406 /// whether there is a keyword with this name.
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003407 TypoEditDistanceMap CorrectionResults;
Douglas Gregor2d435302009-12-30 17:04:44 +00003408
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003409 Sema &SemaRef;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003410
Douglas Gregor2d435302009-12-30 17:04:44 +00003411public:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003412 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003413 : Typo(Typo->getName()),
Richard Smithe156254d2013-08-20 20:35:18 +00003414 SemaRef(SemaRef) {}
3415
3416 bool includeHiddenDecls() const { return true; }
Douglas Gregor2d435302009-12-30 17:04:44 +00003417
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003418 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3419 bool InBaseClass);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003420 void FoundName(StringRef Name);
3421 void addKeywordResult(StringRef Keyword);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003422 void addName(StringRef Name, NamedDecl *ND, NestedNameSpecifier *NNS = NULL,
3423 bool isKeyword = false);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003424 void addCorrection(TypoCorrection Correction);
Douglas Gregor2d435302009-12-30 17:04:44 +00003425
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003426 typedef TypoResultsMap::iterator result_iterator;
3427 typedef TypoEditDistanceMap::iterator distance_iterator;
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003428 distance_iterator begin() { return CorrectionResults.begin(); }
3429 distance_iterator end() { return CorrectionResults.end(); }
3430 void erase(distance_iterator I) { CorrectionResults.erase(I); }
3431 unsigned size() const { return CorrectionResults.size(); }
3432 bool empty() const { return CorrectionResults.empty(); }
Douglas Gregor2d435302009-12-30 17:04:44 +00003433
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003434 TypoResultList &operator[](StringRef Name) {
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003435 return CorrectionResults.begin()->second[Name];
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003436 }
3437
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003438 unsigned getBestEditDistance(bool Normalized) {
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003439 if (CorrectionResults.empty())
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003440 return (std::numeric_limits<unsigned>::max)();
3441
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003442 unsigned BestED = CorrectionResults.begin()->first;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003443 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003444 }
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003445
3446 TypoResultsMap &getBestResults() {
3447 return CorrectionResults.begin()->second;
3448 }
3449
Douglas Gregor2d435302009-12-30 17:04:44 +00003450};
3451
3452}
3453
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003454void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003455 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003456 // Don't consider hidden names for typo correction.
3457 if (Hiding)
3458 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003459
Douglas Gregor2d435302009-12-30 17:04:44 +00003460 // Only consider entities with identifiers for names, ignoring
3461 // special names (constructors, overloaded operators, selectors,
3462 // etc.).
3463 IdentifierInfo *Name = ND->getIdentifier();
3464 if (!Name)
3465 return;
3466
Richard Smithe156254d2013-08-20 20:35:18 +00003467 // Only consider visible declarations and declarations from modules with
3468 // names that exactly match.
3469 if (!LookupResult::isVisible(SemaRef, ND) && Name->getName() != Typo &&
3470 !findAcceptableDecl(SemaRef, ND))
3471 return;
3472
Douglas Gregor57756ea2010-10-14 22:11:03 +00003473 FoundName(Name->getName());
3474}
3475
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003476void TypoCorrectionConsumer::FoundName(StringRef Name) {
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003477 // Compute the edit distance between the typo and the name of this
3478 // entity, and add the identifier to the list of results.
3479 addName(Name, NULL);
3480}
3481
3482void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3483 // Compute the edit distance between the typo and this keyword,
3484 // and add the keyword to the list of results.
3485 addName(Keyword, NULL, NULL, true);
3486}
3487
3488void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
3489 NestedNameSpecifier *NNS, bool isKeyword) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003490 // Use a simple length-based heuristic to determine the minimum possible
3491 // edit distance. If the minimum isn't good enough, bail out early.
3492 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003493 if (MinED && Typo.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00003494 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003495
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003496 // Compute an upper bound on the allowable edit distance, so that the
3497 // edit-distance algorithm can short-circuit.
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003498 unsigned UpperBound = (Typo.size() + 2) / 3 + 1;
3499 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
3500 if (ED >= UpperBound) return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003501
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003502 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003503 if (isKeyword) TC.makeKeyword();
3504 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003505}
3506
3507void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003508 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003509 TypoResultList &CList =
3510 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003511
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003512 if (!CList.empty() && !CList.back().isResolved())
3513 CList.pop_back();
3514 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3515 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3516 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3517 RI != RIEnd; ++RI) {
3518 // If the Correction refers to a decl already in the result list,
3519 // replace the existing result if the string representation of Correction
3520 // comes before the current result alphabetically, then stop as there is
3521 // nothing more to be done to add Correction to the candidate set.
3522 if (RI->getCorrectionDecl() == NewND) {
3523 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3524 *RI = Correction;
3525 return;
3526 }
3527 }
3528 }
3529 if (CList.empty() || Correction.isResolved())
3530 CList.push_back(Correction);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003531
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003532 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
3533 erase(llvm::prior(CorrectionResults.end()));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003534}
3535
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003536// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3537// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3538// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3539static void getNestedNameSpecifierIdentifiers(
3540 NestedNameSpecifier *NNS,
3541 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3542 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3543 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3544 else
3545 Identifiers.clear();
3546
3547 const IdentifierInfo *II = NULL;
3548
3549 switch (NNS->getKind()) {
3550 case NestedNameSpecifier::Identifier:
3551 II = NNS->getAsIdentifier();
3552 break;
3553
3554 case NestedNameSpecifier::Namespace:
3555 if (NNS->getAsNamespace()->isAnonymousNamespace())
3556 return;
3557 II = NNS->getAsNamespace()->getIdentifier();
3558 break;
3559
3560 case NestedNameSpecifier::NamespaceAlias:
3561 II = NNS->getAsNamespaceAlias()->getIdentifier();
3562 break;
3563
3564 case NestedNameSpecifier::TypeSpecWithTemplate:
3565 case NestedNameSpecifier::TypeSpec:
3566 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3567 break;
3568
3569 case NestedNameSpecifier::Global:
3570 return;
3571 }
3572
3573 if (II)
3574 Identifiers.push_back(II);
3575}
3576
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003577namespace {
3578
3579class SpecifierInfo {
3580 public:
3581 DeclContext* DeclCtx;
3582 NestedNameSpecifier* NameSpecifier;
3583 unsigned EditDistance;
3584
3585 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3586 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3587};
3588
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003589typedef SmallVector<DeclContext*, 4> DeclContextList;
3590typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003591
3592class NamespaceSpecifierSet {
3593 ASTContext &Context;
3594 DeclContextList CurContextChain;
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003595 std::string CurNameSpecifier;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003596 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3597 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003598 bool isSorted;
3599
3600 SpecifierInfoList Specifiers;
3601 llvm::SmallSetVector<unsigned, 4> Distances;
3602 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3603
3604 /// \brief Helper for building the list of DeclContexts between the current
3605 /// context and the top of the translation unit
3606 static DeclContextList BuildContextChain(DeclContext *Start);
3607
3608 void SortNamespaces();
3609
3610 public:
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003611 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3612 CXXScopeSpec *CurScopeSpec)
Benjamin Kramerde1d6232011-07-05 09:46:31 +00003613 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
Kaelyn Uhrain52dd02d2013-06-24 17:49:03 +00003614 isSorted(false) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003615 if (NestedNameSpecifier *NNS =
3616 CurScopeSpec ? CurScopeSpec->getScopeRep() : 0) {
3617 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
3618 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3619
3620 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
3621 }
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003622 // Build the list of identifiers that would be used for an absolute
Benjamin Kramer474261a2012-06-02 10:20:41 +00003623 // (from the global context) NestedNameSpecifier referring to the current
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003624 // context.
3625 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3626 CEnd = CurContextChain.rend();
3627 C != CEnd; ++C) {
3628 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3629 CurContextIdentifiers.push_back(ND->getIdentifier());
3630 }
Kaelyn Uhrain52dd02d2013-06-24 17:49:03 +00003631
3632 // Add the global context as a NestedNameSpecifier
3633 Distances.insert(1);
3634 DistanceMap[1].push_back(
3635 SpecifierInfo(cast<DeclContext>(Context.getTranslationUnitDecl()),
3636 NestedNameSpecifier::GlobalSpecifier(Context), 1));
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003637 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003638
Kaelyn Uhrain5315a462013-10-19 00:04:49 +00003639 /// \brief Add the DeclContext (a namespace or record) to the set, computing
3640 /// the corresponding NestedNameSpecifier and its distance in the process.
3641 void AddNameSpecifier(DeclContext *Ctx);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003642
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003643 typedef SpecifierInfoList::iterator iterator;
3644 iterator begin() {
3645 if (!isSorted) SortNamespaces();
3646 return Specifiers.begin();
3647 }
3648 iterator end() { return Specifiers.end(); }
3649};
3650
3651}
3652
3653DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Nick Lewycky0d9b3192013-04-08 21:55:21 +00003654 assert(Start && "Building a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003655 DeclContextList Chain;
3656 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3657 DC = DC->getLookupParent()) {
3658 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3659 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3660 !(ND && ND->isAnonymousNamespace()))
3661 Chain.push_back(DC->getPrimaryContext());
3662 }
3663 return Chain;
3664}
3665
3666void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003667 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003668 sortedDistances.append(Distances.begin(), Distances.end());
3669
3670 if (sortedDistances.size() > 1)
3671 std::sort(sortedDistances.begin(), sortedDistances.end());
3672
3673 Specifiers.clear();
Craig Topper2341c0d2013-07-04 03:08:24 +00003674 for (SmallVectorImpl<unsigned>::iterator DI = sortedDistances.begin(),
3675 DIEnd = sortedDistances.end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003676 DI != DIEnd; ++DI) {
3677 SpecifierInfoList &SpecList = DistanceMap[*DI];
3678 Specifiers.append(SpecList.begin(), SpecList.end());
3679 }
3680
3681 isSorted = true;
3682}
3683
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003684static unsigned BuildNestedNameSpecifier(ASTContext &Context,
3685 DeclContextList &DeclChain,
3686 NestedNameSpecifier *&NNS) {
3687 unsigned NumSpecifiers = 0;
3688 for (DeclContextList::reverse_iterator C = DeclChain.rbegin(),
3689 CEnd = DeclChain.rend();
3690 C != CEnd; ++C) {
3691 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) {
3692 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3693 ++NumSpecifiers;
3694 } else if (RecordDecl *RD = dyn_cast_or_null<RecordDecl>(*C)) {
3695 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
3696 RD->getTypeForDecl());
3697 ++NumSpecifiers;
3698 }
3699 }
3700 return NumSpecifiers;
3701}
3702
Kaelyn Uhrain5315a462013-10-19 00:04:49 +00003703void NamespaceSpecifierSet::AddNameSpecifier(DeclContext *Ctx) {
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003704 NestedNameSpecifier *NNS = NULL;
3705 unsigned NumSpecifiers = 0;
3706 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
3707 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
3708
3709 // Eliminate common elements from the two DeclContext chains.
3710 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3711 CEnd = CurContextChain.rend();
3712 C != CEnd && !NamespaceDeclChain.empty() &&
3713 NamespaceDeclChain.back() == *C; ++C) {
3714 NamespaceDeclChain.pop_back();
3715 }
3716
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003717 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3718 NumSpecifiers = BuildNestedNameSpecifier(Context, NamespaceDeclChain, NNS);
3719
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003720 // Add an explicit leading '::' specifier if needed.
3721 if (NamespaceDeclChain.empty()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003722 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003723 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003724 NumSpecifiers =
3725 BuildNestedNameSpecifier(Context, FullNamespaceDeclChain, NNS);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003726 } else if (NamedDecl *ND =
3727 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003728 IdentifierInfo *Name = ND->getIdentifier();
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003729 bool SameNameSpecifier = false;
3730 if (std::find(CurNameSpecifierIdentifiers.begin(),
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003731 CurNameSpecifierIdentifiers.end(),
3732 Name) != CurNameSpecifierIdentifiers.end()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003733 std::string NewNameSpecifier;
3734 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
3735 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
3736 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3737 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3738 SpecifierOStream.flush();
3739 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003740 }
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003741 if (SameNameSpecifier ||
3742 std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3743 Name) != CurContextIdentifiers.end()) {
3744 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
3745 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3746 NumSpecifiers =
3747 BuildNestedNameSpecifier(Context, FullNamespaceDeclChain, NNS);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003748 }
3749 }
3750
3751 // If the built NestedNameSpecifier would be replacing an existing
3752 // NestedNameSpecifier, use the number of component identifiers that
3753 // would need to be changed as the edit distance instead of the number
3754 // of components in the built NestedNameSpecifier.
3755 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3756 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3757 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3758 NumSpecifiers = llvm::ComputeEditDistance(
3759 ArrayRef<const IdentifierInfo *>(CurNameSpecifierIdentifiers),
3760 ArrayRef<const IdentifierInfo *>(NewNameSpecifierIdentifiers));
3761 }
3762
3763 isSorted = false;
3764 Distances.insert(NumSpecifiers);
3765 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
3766}
3767
Douglas Gregord507d772010-10-20 03:06:34 +00003768/// \brief Perform name lookup for a possible result for typo correction.
3769static void LookupPotentialTypoResult(Sema &SemaRef,
3770 LookupResult &Res,
3771 IdentifierInfo *Name,
3772 Scope *S, CXXScopeSpec *SS,
3773 DeclContext *MemberContext,
3774 bool EnteringContext,
Richard Smithe156254d2013-08-20 20:35:18 +00003775 bool isObjCIvarLookup,
3776 bool FindHidden) {
Douglas Gregord507d772010-10-20 03:06:34 +00003777 Res.suppressDiagnostics();
3778 Res.clear();
3779 Res.setLookupName(Name);
Richard Smithe156254d2013-08-20 20:35:18 +00003780 Res.setAllowHidden(FindHidden);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003781 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00003782 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003783 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00003784 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3785 Res.addDecl(Ivar);
3786 Res.resolveKind();
3787 return;
3788 }
3789 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003790
Douglas Gregord507d772010-10-20 03:06:34 +00003791 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3792 Res.addDecl(Prop);
3793 Res.resolveKind();
3794 return;
3795 }
3796 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003797
Douglas Gregord507d772010-10-20 03:06:34 +00003798 SemaRef.LookupQualifiedName(Res, MemberContext);
3799 return;
3800 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003801
3802 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00003803 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003804
Douglas Gregord507d772010-10-20 03:06:34 +00003805 // Fake ivar lookup; this should really be part of
3806 // LookupParsedName.
3807 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3808 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003809 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00003810 (Res.isSingleResult() &&
3811 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003812 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00003813 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3814 Res.addDecl(IV);
3815 Res.resolveKind();
3816 }
3817 }
3818 }
3819}
3820
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003821/// \brief Add keywords to the consumer as possible typo corrections.
3822static void AddKeywordsToConsumer(Sema &SemaRef,
3823 TypoCorrectionConsumer &Consumer,
Richard Smithb3a1df02012-06-08 21:35:42 +00003824 Scope *S, CorrectionCandidateCallback &CCC,
3825 bool AfterNestedNameSpecifier) {
3826 if (AfterNestedNameSpecifier) {
3827 // For 'X::', we know exactly which keywords can appear next.
3828 Consumer.addKeywordResult("template");
3829 if (CCC.WantExpressionKeywords)
3830 Consumer.addKeywordResult("operator");
3831 return;
3832 }
3833
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003834 if (CCC.WantObjCSuper)
3835 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003836
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003837 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003838 // Add type-specifier keywords to the set of results.
Craig Topperd6d31ac2013-07-15 08:24:27 +00003839 static const char *const CTypeSpecs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003840 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00003841 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003842 "_Complex", "_Imaginary",
3843 // storage-specifiers as well
3844 "extern", "inline", "static", "typedef"
3845 };
3846
Craig Toppere5ce8312013-07-15 03:38:40 +00003847 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003848 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3849 Consumer.addKeywordResult(CTypeSpecs[I]);
3850
David Blaikiebbafb8a2012-03-11 07:00:24 +00003851 if (SemaRef.getLangOpts().C99)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003852 Consumer.addKeywordResult("restrict");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003853 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003854 Consumer.addKeywordResult("bool");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003855 else if (SemaRef.getLangOpts().C99)
Douglas Gregor3b22a882011-07-01 21:27:45 +00003856 Consumer.addKeywordResult("_Bool");
3857
David Blaikiebbafb8a2012-03-11 07:00:24 +00003858 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003859 Consumer.addKeywordResult("class");
3860 Consumer.addKeywordResult("typename");
3861 Consumer.addKeywordResult("wchar_t");
3862
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003863 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003864 Consumer.addKeywordResult("char16_t");
3865 Consumer.addKeywordResult("char32_t");
3866 Consumer.addKeywordResult("constexpr");
3867 Consumer.addKeywordResult("decltype");
3868 Consumer.addKeywordResult("thread_local");
3869 }
3870 }
3871
David Blaikiebbafb8a2012-03-11 07:00:24 +00003872 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003873 Consumer.addKeywordResult("typeof");
3874 }
3875
David Blaikiebbafb8a2012-03-11 07:00:24 +00003876 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003877 Consumer.addKeywordResult("const_cast");
3878 Consumer.addKeywordResult("dynamic_cast");
3879 Consumer.addKeywordResult("reinterpret_cast");
3880 Consumer.addKeywordResult("static_cast");
3881 }
3882
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003883 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003884 Consumer.addKeywordResult("sizeof");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003885 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003886 Consumer.addKeywordResult("false");
3887 Consumer.addKeywordResult("true");
3888 }
3889
David Blaikiebbafb8a2012-03-11 07:00:24 +00003890 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topperd6d31ac2013-07-15 08:24:27 +00003891 static const char *const CXXExprs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003892 "delete", "new", "operator", "throw", "typeid"
3893 };
Craig Toppere5ce8312013-07-15 03:38:40 +00003894 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003895 for (unsigned I = 0; I != NumCXXExprs; ++I)
3896 Consumer.addKeywordResult(CXXExprs[I]);
3897
3898 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3899 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3900 Consumer.addKeywordResult("this");
3901
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003902 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003903 Consumer.addKeywordResult("alignof");
3904 Consumer.addKeywordResult("nullptr");
3905 }
3906 }
Jordan Rose58d54722012-06-30 21:33:57 +00003907
3908 if (SemaRef.getLangOpts().C11) {
3909 // FIXME: We should not suggest _Alignof if the alignof macro
3910 // is present.
3911 Consumer.addKeywordResult("_Alignof");
3912 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003913 }
3914
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003915 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003916 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3917 // Statements.
Craig Topperd6d31ac2013-07-15 08:24:27 +00003918 static const char *const CStmts[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003919 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Toppere5ce8312013-07-15 03:38:40 +00003920 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003921 for (unsigned I = 0; I != NumCStmts; ++I)
3922 Consumer.addKeywordResult(CStmts[I]);
3923
David Blaikiebbafb8a2012-03-11 07:00:24 +00003924 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003925 Consumer.addKeywordResult("catch");
3926 Consumer.addKeywordResult("try");
3927 }
3928
3929 if (S && S->getBreakParent())
3930 Consumer.addKeywordResult("break");
3931
3932 if (S && S->getContinueParent())
3933 Consumer.addKeywordResult("continue");
3934
3935 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3936 Consumer.addKeywordResult("case");
3937 Consumer.addKeywordResult("default");
3938 }
3939 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003940 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003941 Consumer.addKeywordResult("namespace");
3942 Consumer.addKeywordResult("template");
3943 }
3944
3945 if (S && S->isClassScope()) {
3946 Consumer.addKeywordResult("explicit");
3947 Consumer.addKeywordResult("friend");
3948 Consumer.addKeywordResult("mutable");
3949 Consumer.addKeywordResult("private");
3950 Consumer.addKeywordResult("protected");
3951 Consumer.addKeywordResult("public");
3952 Consumer.addKeywordResult("virtual");
3953 }
3954 }
3955
David Blaikiebbafb8a2012-03-11 07:00:24 +00003956 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003957 Consumer.addKeywordResult("using");
3958
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003959 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003960 Consumer.addKeywordResult("static_assert");
3961 }
3962 }
3963}
3964
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003965static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3966 TypoCorrection &Candidate) {
3967 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3968 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3969}
3970
Richard Smithe156254d2013-08-20 20:35:18 +00003971/// \brief Check whether the declarations found for a typo correction are
3972/// visible, and if none of them are, convert the correction to an 'import
3973/// a module' correction.
3974static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC,
3975 DeclarationName TypoName) {
3976 if (TC.begin() == TC.end())
3977 return;
3978
3979 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3980
3981 for (/**/; DI != DE; ++DI)
3982 if (!LookupResult::isVisible(SemaRef, *DI))
3983 break;
3984 // Nothing to do if all decls are visible.
3985 if (DI == DE)
3986 return;
3987
3988 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3989 bool AnyVisibleDecls = !NewDecls.empty();
3990
3991 for (/**/; DI != DE; ++DI) {
3992 NamedDecl *VisibleDecl = *DI;
3993 if (!LookupResult::isVisible(SemaRef, *DI))
3994 VisibleDecl = findAcceptableDecl(SemaRef, *DI);
3995
3996 if (VisibleDecl) {
3997 if (!AnyVisibleDecls) {
3998 // Found a visible decl, discard all hidden ones.
3999 AnyVisibleDecls = true;
4000 NewDecls.clear();
4001 }
4002 NewDecls.push_back(VisibleDecl);
4003 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
4004 NewDecls.push_back(*DI);
4005 }
4006
4007 if (NewDecls.empty())
4008 TC = TypoCorrection();
4009 else {
4010 TC.setCorrectionDecls(NewDecls);
4011 TC.setRequiresImport(!AnyVisibleDecls);
4012 }
4013}
4014
Douglas Gregor2d435302009-12-30 17:04:44 +00004015/// \brief Try to "correct" a typo in the source code by finding
4016/// visible declarations whose names are similar to the name that was
4017/// present in the source code.
4018///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004019/// \param TypoName the \c DeclarationNameInfo structure that contains
4020/// the name that was present in the source code along with its location.
4021///
4022/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00004023///
4024/// \param S the scope in which name lookup occurs.
4025///
4026/// \param SS the nested-name-specifier that precedes the name we're
4027/// looking for, if present.
4028///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004029/// \param CCC A CorrectionCandidateCallback object that provides further
4030/// validation of typo correction candidates. It also provides flags for
4031/// determining the set of keywords permitted.
4032///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00004033/// \param MemberContext if non-NULL, the context in which to look for
4034/// a member access expression.
4035///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004036/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00004037/// the nested-name-specifier SS.
4038///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004039/// \param OPT when non-NULL, the search for visible declarations will
4040/// also walk the protocols in the qualified interfaces of \p OPT.
4041///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004042/// \returns a \c TypoCorrection containing the corrected name if the typo
4043/// along with information such as the \c NamedDecl where the corrected name
4044/// was declared, and any additional \c NestedNameSpecifier needed to access
4045/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
4046TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
4047 Sema::LookupNameKind LookupKind,
4048 Scope *S, CXXScopeSpec *SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00004049 CorrectionCandidateCallback &CCC,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004050 DeclContext *MemberContext,
4051 bool EnteringContext,
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004052 const ObjCObjectPointerType *OPT,
4053 bool RecordFailure) {
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004054 // Always let the ExternalSource have the first chance at correction, even
4055 // if we would otherwise have given up.
4056 if (ExternalSource) {
4057 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
4058 TypoName, LookupKind, S, SS, CCC, MemberContext, EnteringContext, OPT))
4059 return Correction;
4060 }
4061
Richard Smith1fff95c2013-09-12 23:28:08 +00004062 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4063 DisableTypoCorrection)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004064 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004065
Francois Pichet9c391132011-12-03 15:55:29 +00004066 // In Microsoft mode, don't perform typo correction in a template member
4067 // function dependent context because it interferes with the "lookup into
4068 // dependent bases of class templates" feature.
Alp Tokerbfa39342014-01-14 12:51:41 +00004069 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
Francois Pichet9c391132011-12-03 15:55:29 +00004070 isa<CXXMethodDecl>(CurContext))
4071 return TypoCorrection();
4072
Douglas Gregor2d435302009-12-30 17:04:44 +00004073 // We only attempt to correct typos for identifiers.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004074 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor2d435302009-12-30 17:04:44 +00004075 if (!Typo)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004076 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00004077
4078 // If the scope specifier itself was invalid, don't try to correct
4079 // typos.
4080 if (SS && SS->isInvalid())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004081 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00004082
4083 // Never try to correct typos during template deduction or
4084 // instantiation.
4085 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004086 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004087
Argyrios Kyrtzidis3e56dd42013-03-14 22:56:43 +00004088 // Don't try to correct 'super'.
4089 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4090 return TypoCorrection();
4091
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004092 // Abort if typo correction already failed for this specific typo.
4093 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4094 if (locs != TypoCorrectionFailures.end() &&
Aaron Ballman7fc6e1b2013-10-05 19:56:07 +00004095 locs->second.count(TypoName.getLoc()))
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004096 return TypoCorrection();
4097
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004098 // Don't try to correct the identifier "vector" when in AltiVec mode.
4099 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4100 // remove this workaround.
4101 if (getLangOpts().AltiVec && Typo->isStr("vector"))
4102 return TypoCorrection();
4103
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004104 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004105
4106 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004107
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00004108 // If a callback object considers an empty typo correction candidate to be
4109 // viable, assume it does not do any actual validation of the candidates.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004110 TypoCorrection EmptyCorrection;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00004111 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004112
Douglas Gregor280e1ee2010-04-14 20:04:41 +00004113 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor87074f12010-10-20 01:32:02 +00004114 bool IsUnqualifiedLookup = false;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004115 DeclContext *QualifiedDC = MemberContext;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004116 if (MemberContext) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004117 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004118
4119 // Look in qualified interfaces.
4120 if (OPT) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004121 for (ObjCObjectPointerType::qual_iterator
4122 I = OPT->qual_begin(), E = OPT->qual_end();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004123 I != E; ++I)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004124 LookupVisibleDecls(*I, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004125 }
4126 } else if (SS && SS->isSet()) {
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004127 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4128 if (!QualifiedDC)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004129 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004130
Douglas Gregor87074f12010-10-20 01:32:02 +00004131 // Provide a stop gap for files that are just seriously broken. Trying
4132 // to correct all typos can turn into a HUGE performance penalty, causing
4133 // some files to take minutes to get rejected by the parser.
4134 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004135 return TypoCorrection();
Douglas Gregor87074f12010-10-20 01:32:02 +00004136 ++TyposCorrected;
4137
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004138 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
Douglas Gregor2d435302009-12-30 17:04:44 +00004139 } else {
Douglas Gregor87074f12010-10-20 01:32:02 +00004140 IsUnqualifiedLookup = true;
4141 UnqualifiedTyposCorrectedMap::iterator Cached
4142 = UnqualifiedTyposCorrected.find(Typo);
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004143 if (Cached != UnqualifiedTyposCorrected.end()) {
4144 // Add the cached value, unless it's a keyword or fails validation. In the
4145 // keyword case, we'll end up adding the keyword below.
4146 if (Cached->second) {
4147 if (!Cached->second.isKeyword() &&
Serge Pavlovc0cd80f2013-10-14 14:05:48 +00004148 isCandidateViable(CCC, Cached->second)) {
4149 // Do not use correction that is unaccessible in the given scope.
Serge Pavlove8ae13f2013-10-15 14:24:32 +00004150 NamedDecl *CorrectionDecl = Cached->second.getCorrectionDecl();
Serge Pavlovc0cd80f2013-10-14 14:05:48 +00004151 DeclarationNameInfo NameInfo(CorrectionDecl->getDeclName(),
4152 CorrectionDecl->getLocation());
4153 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4154 if (LookupName(R, S))
4155 Consumer.addCorrection(Cached->second);
4156 }
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004157 } else {
4158 // Only honor no-correction cache hits when a callback that will validate
4159 // correction candidates is not being used.
4160 if (!ValidatingCallback)
4161 return TypoCorrection();
4162 }
4163 }
4164 if (Cached == UnqualifiedTyposCorrected.end()) {
Douglas Gregor87074f12010-10-20 01:32:02 +00004165 // Provide a stop gap for files that are just seriously broken. Trying
4166 // to correct all typos can turn into a HUGE performance penalty, causing
4167 // some files to take minutes to get rejected by the parser.
4168 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004169 return TypoCorrection();
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004170 }
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004171 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004172
Douglas Gregorb11f9452012-03-26 16:54:18 +00004173 // Determine whether we are going to search in the various namespaces for
4174 // corrections.
4175 bool SearchNamespaces
Kaelyn Uhrainf4657d52012-04-03 18:20:11 +00004176 = getLangOpts().CPlusPlus &&
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00004177 (IsUnqualifiedLookup || (SS && SS->isSet()));
Richard Smithe156254d2013-08-20 20:35:18 +00004178 // In a few cases we *only* want to search for corrections based on just
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004179 // adding or changing the nested name specifier.
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004180 unsigned TypoLen = Typo->getName().size();
4181 bool AllowOnlyNNSChanges = TypoLen < 3;
4182
Douglas Gregorb11f9452012-03-26 16:54:18 +00004183 if (IsUnqualifiedLookup || SearchNamespaces) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004184 // For unqualified lookup, look through all of the names that we have
4185 // seen in this translation unit.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00004186 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004187 for (IdentifierTable::iterator I = Context.Idents.begin(),
4188 IEnd = Context.Idents.end();
4189 I != IEnd; ++I)
4190 Consumer.FoundName(I->getKey());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004191
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004192 // Walk through identifiers in external identifier sources.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00004193 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004194 if (IdentifierInfoLookup *External
4195 = Context.Idents.getExternalIdentifierLookup()) {
Dylan Noblesmithe2778992012-02-05 02:12:40 +00004196 OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004197 do {
4198 StringRef Name = Iter->Next();
4199 if (Name.empty())
4200 break;
Douglas Gregor57756ea2010-10-14 22:11:03 +00004201
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004202 Consumer.FoundName(Name);
4203 } while (true);
Douglas Gregor57756ea2010-10-14 22:11:03 +00004204 }
Douglas Gregor2d435302009-12-30 17:04:44 +00004205 }
4206
Richard Smithb3a1df02012-06-08 21:35:42 +00004207 AddKeywordsToConsumer(*this, Consumer, S, CCC, SS && SS->isNotEmpty());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004208
Douglas Gregor280e1ee2010-04-14 20:04:41 +00004209 // If we haven't found anything, we're done.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004210 if (Consumer.empty())
4211 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4212 IsUnqualifiedLookup);
Douglas Gregor2d435302009-12-30 17:04:44 +00004213
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004214 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4215 // is not more that about a third of the length of the typo's identifier.
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00004216 unsigned ED = Consumer.getBestEditDistance(true);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004217 if (ED > 0 && TypoLen / ED < 3)
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004218 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4219 IsUnqualifiedLookup);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004220
Douglas Gregorb11f9452012-03-26 16:54:18 +00004221 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4222 // to search those namespaces.
4223 if (SearchNamespaces) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004224 // Load any externally-known namespaces.
4225 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004226 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004227 LoadedExternalKnownNamespaces = true;
4228 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4229 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
4230 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
4231 }
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004232
4233 for (llvm::MapVector<NamespaceDecl*, bool>::iterator
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004234 KNI = KnownNamespaces.begin(),
4235 KNIEnd = KnownNamespaces.end();
4236 KNI != KNIEnd; ++KNI)
Kaelyn Uhrain5315a462013-10-19 00:04:49 +00004237 Namespaces.AddNameSpecifier(KNI->first);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004238
4239 for (ASTContext::type_iterator TI = Context.types_begin(),
4240 TIEnd = Context.types_end();
4241 TI != TIEnd; ++TI) {
4242 if (CXXRecordDecl *CD = (*TI)->getAsCXXRecordDecl()) {
Kaelyn Uhrain5315a462013-10-19 00:04:49 +00004243 CD = CD->getCanonicalDecl();
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004244 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
Kaelyn Uhrain5315a462013-10-19 00:04:49 +00004245 !CD->isUnion() &&
4246 (CD->isBeingDefined() || CD->isCompleteDefinition()))
4247 Namespaces.AddNameSpecifier(CD);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004248 }
4249 }
Douglas Gregor87074f12010-10-20 01:32:02 +00004250 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004251
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004252 // Weed out any names that could not be found by name lookup or, if a
4253 // CorrectionCandidateCallback object was provided, failed validation.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004254 SmallVector<TypoCorrection, 16> QualifiedResults;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004255 LookupResult TmpRes(*this, TypoName, LookupKind);
4256 TmpRes.suppressDiagnostics();
4257 while (!Consumer.empty()) {
4258 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
Benjamin Kramer73faad62012-04-14 08:26:28 +00004259 for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(),
4260 IEnd = DI->second.end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004261 I != IEnd; /* Increment in loop. */) {
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004262 // If we only want nested name specifier corrections, ignore potential
4263 // corrections that have a different base identifier from the typo.
4264 if (AllowOnlyNNSChanges &&
4265 I->second.front().getCorrectionAsIdentifierInfo() != Typo) {
4266 TypoCorrectionConsumer::result_iterator Prev = I;
4267 ++I;
4268 DI->second.erase(Prev);
4269 continue;
4270 }
4271
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004272 // If the item already has been looked up or is a keyword, keep it.
4273 // If a validator callback object was given, drop the correction
4274 // unless it passes validation.
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004275 bool Viable = false;
Benjamin Kramera2dcac12012-07-27 10:21:08 +00004276 for (TypoResultList::iterator RI = I->second.begin();
4277 RI != I->second.end(); /* Increment in loop. */) {
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004278 TypoResultList::iterator Prev = RI;
4279 ++RI;
4280 if (Prev->isResolved()) {
4281 if (!isCandidateViable(CCC, *Prev))
Benjamin Kramera2dcac12012-07-27 10:21:08 +00004282 RI = I->second.erase(Prev);
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004283 else
4284 Viable = true;
4285 }
4286 }
4287 if (Viable || I->second.empty()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004288 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004289 ++I;
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004290 if (!Viable)
Benjamin Kramer73faad62012-04-14 08:26:28 +00004291 DI->second.erase(Prev);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004292 continue;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004293 }
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004294 assert(I->second.size() == 1 && "Expected a single unresolved candidate");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004295
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004296 // Perform name lookup on this name.
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004297 TypoCorrection &Candidate = I->second.front();
4298 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00004299 DeclContext *TempMemberContext = MemberContext;
4300 CXXScopeSpec *TempSS = SS;
4301retry_lookup:
4302 LookupPotentialTypoResult(*this, TmpRes, Name, S, TempSS,
4303 TempMemberContext, EnteringContext,
Richard Smithe156254d2013-08-20 20:35:18 +00004304 CCC.IsObjCIvarLookup,
4305 Name == TypoName.getName() &&
4306 !Candidate.WillReplaceSpecifier());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004307
4308 switch (TmpRes.getResultKind()) {
4309 case LookupResult::NotFound:
4310 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain5a43b462011-09-07 20:25:59 +00004311 case LookupResult::FoundUnresolvedValue:
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00004312 if (TempSS) {
4313 // Immediately retry the lookup without the given CXXScopeSpec
4314 TempSS = NULL;
4315 Candidate.WillReplaceSpecifier(true);
4316 goto retry_lookup;
4317 }
4318 if (TempMemberContext) {
4319 if (SS && !TempSS)
4320 TempSS = SS;
4321 TempMemberContext = NULL;
4322 goto retry_lookup;
4323 }
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004324 QualifiedResults.push_back(Candidate);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004325 // We didn't find this name in our scope, or didn't like what we found;
4326 // ignore it.
4327 {
4328 TypoCorrectionConsumer::result_iterator Next = I;
4329 ++Next;
Benjamin Kramer73faad62012-04-14 08:26:28 +00004330 DI->second.erase(I);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004331 I = Next;
4332 }
4333 break;
4334
4335 case LookupResult::Ambiguous:
4336 // We don't deal with ambiguities.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004337 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004338
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004339 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004340 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004341 // Store all of the Decls for overloaded symbols
4342 for (LookupResult::iterator TRD = TmpRes.begin(),
4343 TRDEnd = TmpRes.end();
4344 TRD != TRDEnd; ++TRD)
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004345 Candidate.addCorrectionDecl(*TRD);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004346 ++I;
Kaelyn Uhrainb18b0c02013-07-02 23:47:35 +00004347 if (!isCandidateViable(CCC, Candidate)) {
4348 QualifiedResults.push_back(Candidate);
Benjamin Kramer73faad62012-04-14 08:26:28 +00004349 DI->second.erase(Prev);
Kaelyn Uhrainb18b0c02013-07-02 23:47:35 +00004350 }
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004351 break;
4352 }
4353
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004354 case LookupResult::Found: {
4355 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004356 Candidate.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004357 ++I;
Kaelyn Uhrainb18b0c02013-07-02 23:47:35 +00004358 if (!isCandidateViable(CCC, Candidate)) {
4359 QualifiedResults.push_back(Candidate);
Benjamin Kramer73faad62012-04-14 08:26:28 +00004360 DI->second.erase(Prev);
Kaelyn Uhrainb18b0c02013-07-02 23:47:35 +00004361 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004362 break;
4363 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004364
4365 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004366 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004367
Benjamin Kramer73faad62012-04-14 08:26:28 +00004368 if (DI->second.empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004369 Consumer.erase(DI);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004370 else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !DI->first)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004371 // If there are results in the closest possible bucket, stop
4372 break;
4373
4374 // Only perform the qualified lookups for C++
Douglas Gregorb11f9452012-03-26 16:54:18 +00004375 if (SearchNamespaces) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004376 TmpRes.suppressDiagnostics();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004377 for (SmallVector<TypoCorrection,
4378 16>::iterator QRI = QualifiedResults.begin(),
4379 QRIEnd = QualifiedResults.end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004380 QRI != QRIEnd; ++QRI) {
4381 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
4382 NIEnd = Namespaces.end();
4383 NI != NIEnd; ++NI) {
4384 DeclContext *Ctx = NI->DeclCtx;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004385 const Type *NSType = NI->NameSpecifier->getAsType();
4386
4387 // If the current NestedNameSpecifier refers to a class and the
4388 // current correction candidate is the name of that class, then skip
4389 // it as it is unlikely a qualified version of the class' constructor
4390 // is an appropriate correction.
4391 if (CXXRecordDecl *NSDecl =
4392 NSType ? NSType->getAsCXXRecordDecl() : 0) {
4393 if (NSDecl->getIdentifier() == QRI->getCorrectionAsIdentifierInfo())
4394 continue;
4395 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004396
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004397 TypoCorrection TC(*QRI);
4398 TC.ClearCorrectionDecls();
4399 TC.setCorrectionSpecifier(NI->NameSpecifier);
4400 TC.setQualifierDistance(NI->EditDistance);
4401 TC.setCallbackDistance(0); // Reset the callback distance
4402
4403 // If the current correction candidate and namespace combination are
4404 // too far away from the original typo based on the normalized edit
4405 // distance, then skip performing a qualified name lookup.
4406 unsigned TmpED = TC.getEditDistance(true);
4407 if (QRI->getCorrectionAsIdentifierInfo() != Typo &&
4408 TmpED && TypoLen / TmpED < 3)
4409 continue;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004410
4411 TmpRes.clear();
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00004412 TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004413 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
4414
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004415 // Any corrections added below will be validated in subsequent
4416 // iterations of the main while() loop over the Consumer's contents.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004417 switch (TmpRes.getResultKind()) {
Kaelyn Uhrainb18b0c02013-07-02 23:47:35 +00004418 case LookupResult::Found:
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004419 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00004420 if (SS && SS->isValid()) {
4421 std::string NewQualified = TC.getAsString(getLangOpts());
4422 std::string OldQualified;
4423 llvm::raw_string_ostream OldOStream(OldQualified);
4424 SS->getScopeRep()->print(OldOStream, getPrintingPolicy());
4425 OldOStream << TypoName;
4426 // If correction candidate would be an identical written qualified
4427 // identifer, then the existing CXXScopeSpec probably included a
4428 // typedef that didn't get accounted for properly.
4429 if (OldOStream.str() == NewQualified)
4430 break;
4431 }
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004432 for (LookupResult::iterator TRD = TmpRes.begin(),
4433 TRDEnd = TmpRes.end();
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004434 TRD != TRDEnd; ++TRD) {
4435 if (CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4436 NSType ? NSType->getAsCXXRecordDecl() : 0,
Eli Friedman3be1a1c2013-10-01 02:44:48 +00004437 TRD.getPair()) == AR_accessible)
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004438 TC.addCorrectionDecl(*TRD);
4439 }
4440 if (TC.isResolved())
4441 Consumer.addCorrection(TC);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004442 break;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004443 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004444 case LookupResult::NotFound:
4445 case LookupResult::NotFoundInCurrentInstantiation:
4446 case LookupResult::Ambiguous:
Kaelyn Uhrain5a43b462011-09-07 20:25:59 +00004447 case LookupResult::FoundUnresolvedValue:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004448 break;
4449 }
4450 }
4451 }
4452 }
4453
4454 QualifiedResults.clear();
4455 }
4456
4457 // No corrections remain...
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004458 if (Consumer.empty())
4459 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004460
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00004461 TypoResultsMap &BestResults = Consumer.getBestResults();
4462 ED = Consumer.getBestEditDistance(true);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004463
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004464 if (!AllowOnlyNNSChanges && ED > 0 && TypoLen / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004465 // If this was an unqualified lookup and we believe the callback
4466 // object wouldn't have filtered out possible corrections, note
4467 // that no correction was found.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004468 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4469 IsUnqualifiedLookup && !ValidatingCallback);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004470 }
4471
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004472 // If only a single name remains, return that result.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004473 if (BestResults.size() == 1) {
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004474 const TypoResultList &CorrectionList = BestResults.begin()->second;
4475 const TypoCorrection &Result = CorrectionList.front();
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004476 if (CorrectionList.size() != 1)
4477 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004478
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00004479 // Don't correct to a keyword that's the same as the typo; the keyword
4480 // wasn't actually in scope.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004481 if (ED == 0 && Result.isKeyword())
4482 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004483
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004484 // Record the correction for unqualified lookup.
4485 if (IsUnqualifiedLookup)
4486 UnqualifiedTyposCorrected[Typo] = Result;
4487
David Blaikie04ea41c2012-10-12 20:00:44 +00004488 TypoCorrection TC = Result;
4489 TC.setCorrectionRange(SS, TypoName);
Richard Smithe156254d2013-08-20 20:35:18 +00004490 checkCorrectionVisibility(*this, TC, TypoName.getName());
David Blaikie04ea41c2012-10-12 20:00:44 +00004491 return TC;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004492 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004493 else if (BestResults.size() > 1
4494 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4495 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4496 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4497 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00004498 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004499 && BestResults["super"].front().isKeyword()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004500 // Prefer 'super' when we're completing in a message-receiver
4501 // context.
4502
4503 // Don't correct to a keyword that's the same as the typo; the keyword
4504 // wasn't actually in scope.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004505 if (ED == 0)
4506 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004507
Douglas Gregor87074f12010-10-20 01:32:02 +00004508 // Record the correction for unqualified lookup.
4509 if (IsUnqualifiedLookup)
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004510 UnqualifiedTyposCorrected[Typo] = BestResults["super"].front();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004511
David Blaikie04ea41c2012-10-12 20:00:44 +00004512 TypoCorrection TC = BestResults["super"].front();
4513 TC.setCorrectionRange(SS, TypoName);
4514 return TC;
Douglas Gregoraf9eb592010-10-15 13:35:25 +00004515 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004516
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004517 // If this was an unqualified lookup and we believe the callback object did
4518 // not filter out possible corrections, note that no correction was found.
4519 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregor87074f12010-10-20 01:32:02 +00004520 (void)UnqualifiedTyposCorrected[Typo];
4521
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004522 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004523}
4524
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004525void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4526 if (!CDecl) return;
4527
4528 if (isKeyword())
4529 CorrectionDecls.clear();
4530
Kaelyn Uhrainf60b55a2012-11-19 18:49:53 +00004531 CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004532
4533 if (!CorrectionName)
4534 CorrectionName = CDecl->getDeclName();
4535}
4536
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004537std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4538 if (CorrectionNameSpec) {
4539 std::string tmpBuffer;
4540 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4541 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikied4da8722013-05-14 21:04:00 +00004542 PrefixOStream << CorrectionName;
Benjamin Kramer73faad62012-04-14 08:26:28 +00004543 return PrefixOStream.str();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004544 }
4545
4546 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00004547}
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004548
4549bool CorrectionCandidateCallback::ValidateCandidate(const TypoCorrection &candidate) {
4550 if (!candidate.isResolved())
4551 return true;
4552
4553 if (candidate.isKeyword())
4554 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4555 WantRemainingKeywords || WantObjCSuper;
4556
4557 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
4558 CDeclEnd = candidate.end();
4559 CDecl != CDeclEnd; ++CDecl) {
4560 if (!isa<TypeDecl>(*CDecl))
4561 return true;
4562 }
4563
4564 return WantTypeSpecifiers;
4565}
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004566
4567FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
4568 bool HasExplicitTemplateArgs)
4569 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
4570 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
4571 WantRemainingKeywords = false;
4572}
4573
4574bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4575 if (!candidate.getCorrectionDecl())
4576 return candidate.isKeyword();
4577
4578 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
4579 DIEnd = candidate.end();
4580 DI != DIEnd; ++DI) {
4581 FunctionDecl *FD = 0;
4582 NamedDecl *ND = (*DI)->getUnderlyingDecl();
4583 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4584 FD = FTD->getTemplatedDecl();
4585 if (!HasExplicitTemplateArgs && !FD) {
4586 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4587 // If the Decl is neither a function nor a template function,
4588 // determine if it is a pointer or reference to a function. If so,
4589 // check against the number of arguments expected for the pointee.
4590 QualType ValType = cast<ValueDecl>(ND)->getType();
4591 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4592 ValType = ValType->getPointeeType();
4593 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
Alp Toker9cacbab2014-01-20 20:26:09 +00004594 if (FPT->getNumParams() == NumArgs)
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004595 return true;
4596 }
4597 }
4598 if (FD && FD->getNumParams() >= NumArgs &&
4599 FD->getMinRequiredArguments() <= NumArgs)
4600 return true;
4601 }
4602 return false;
4603}
Richard Smithf9b15102013-08-17 00:46:16 +00004604
4605void Sema::diagnoseTypo(const TypoCorrection &Correction,
4606 const PartialDiagnostic &TypoDiag,
4607 bool ErrorRecovery) {
4608 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
4609 ErrorRecovery);
4610}
4611
Richard Smithe156254d2013-08-20 20:35:18 +00004612/// Find which declaration we should import to provide the definition of
4613/// the given declaration.
4614static const NamedDecl *getDefinitionToImport(const NamedDecl *D) {
4615 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4616 return VD->getDefinition();
4617 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4618 return FD->isDefined(FD) ? FD : 0;
4619 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
4620 return TD->getDefinition();
4621 if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
4622 return ID->getDefinition();
4623 if (const ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
4624 return PD->getDefinition();
4625 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
4626 return getDefinitionToImport(TD->getTemplatedDecl());
4627 return 0;
4628}
4629
Richard Smithf9b15102013-08-17 00:46:16 +00004630/// \brief Diagnose a successfully-corrected typo. Separated from the correction
4631/// itself to allow external validation of the result, etc.
4632///
4633/// \param Correction The result of performing typo correction.
4634/// \param TypoDiag The diagnostic to produce. This will have the corrected
4635/// string added to it (and usually also a fixit).
4636/// \param PrevNote A note to use when indicating the location of the entity to
4637/// which we are correcting. Will have the correction string added to it.
4638/// \param ErrorRecovery If \c true (the default), the caller is going to
4639/// recover from the typo as if the corrected string had been typed.
4640/// In this case, \c PDiag must be an error, and we will attach a fixit
4641/// to it.
4642void Sema::diagnoseTypo(const TypoCorrection &Correction,
4643 const PartialDiagnostic &TypoDiag,
4644 const PartialDiagnostic &PrevNote,
4645 bool ErrorRecovery) {
4646 std::string CorrectedStr = Correction.getAsString(getLangOpts());
4647 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
4648 FixItHint FixTypo = FixItHint::CreateReplacement(
4649 Correction.getCorrectionRange(), CorrectedStr);
4650
Richard Smithe156254d2013-08-20 20:35:18 +00004651 // Maybe we're just missing a module import.
4652 if (Correction.requiresImport()) {
4653 NamedDecl *Decl = Correction.getCorrectionDecl();
4654 assert(Decl && "import required but no declaration to import");
4655
4656 // Suggest importing a module providing the definition of this entity, if
4657 // possible.
4658 const NamedDecl *Def = getDefinitionToImport(Decl);
4659 if (!Def)
4660 Def = Decl;
4661 Module *Owner = Def->getOwningModule();
4662 assert(Owner && "definition of hidden declaration is not in a module");
4663
4664 Diag(Correction.getCorrectionRange().getBegin(),
4665 diag::err_module_private_declaration)
4666 << Def << Owner->getFullModuleName();
4667 Diag(Def->getLocation(), diag::note_previous_declaration);
4668
4669 // Recover by implicitly importing this module.
4670 if (!isSFINAEContext() && ErrorRecovery)
4671 createImplicitModuleImport(Correction.getCorrectionRange().getBegin(),
4672 Owner);
4673 return;
4674 }
4675
Richard Smithf9b15102013-08-17 00:46:16 +00004676 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
4677 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
4678
4679 NamedDecl *ChosenDecl =
4680 Correction.isKeyword() ? 0 : Correction.getCorrectionDecl();
4681 if (PrevNote.getDiagID() && ChosenDecl)
4682 Diag(ChosenDecl->getLocation(), PrevNote)
4683 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
4684}