blob: c0d49a7dd94a9b165e7c172b49bb869d329d6330 [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"
John Thompson2255f2c2014-04-23 12:57:01 +000026#include "clang/Lex/HeaderSearch.h"
27#include "clang/Lex/ModuleLoader.h"
28#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/Sema/DeclSpec.h"
30#include "clang/Sema/ExternalSemaSource.h"
31#include "clang/Sema/Overload.h"
32#include "clang/Sema/Scope.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
35#include "clang/Sema/SemaInternal.h"
36#include "clang/Sema/TemplateDeduction.h"
37#include "clang/Sema/TypoCorrection.h"
John Thompson2255f2c2014-04-23 12:57:01 +000038#include "clang/Serialization/GlobalModuleIndex.h"
39#include "clang/Serialization/Module.h"
Douglas Gregor34074322009-01-14 22:20:51 +000040#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "llvm/ADT/SetVector.h"
Douglas Gregore254f902009-02-04 00:32:51 +000042#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0afa7f62010-10-14 20:34:08 +000043#include "llvm/ADT/StringMap.h"
Chris Lattner83cfc7c2011-07-18 01:54:02 +000044#include "llvm/ADT/TinyPtrVector.h"
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +000045#include "llvm/ADT/edit_distance.h"
John McCall6538c932009-10-10 05:48:19 +000046#include "llvm/Support/ErrorHandling.h"
Nick Lewycky13668f22012-04-03 20:26:45 +000047#include <algorithm>
48#include <iterator>
Douglas Gregor0afa7f62010-10-14 20:34:08 +000049#include <limits>
Douglas Gregor2d435302009-12-30 17:04:44 +000050#include <list>
Douglas Gregorc2fa1692011-06-28 16:20:02 +000051#include <map>
Nick Lewycky13668f22012-04-03 20:26:45 +000052#include <set>
53#include <utility>
54#include <vector>
Douglas Gregor34074322009-01-14 22:20:51 +000055
56using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000057using namespace sema;
Douglas Gregor34074322009-01-14 22:20:51 +000058
John McCallf6c8a4e2009-11-10 07:01:13 +000059namespace {
60 class UnqualUsingEntry {
61 const DeclContext *Nominated;
62 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000063
John McCallf6c8a4e2009-11-10 07:01:13 +000064 public:
65 UnqualUsingEntry(const DeclContext *Nominated,
66 const DeclContext *CommonAncestor)
67 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
68 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000069
John McCallf6c8a4e2009-11-10 07:01:13 +000070 const DeclContext *getCommonAncestor() const {
71 return CommonAncestor;
72 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000073
John McCallf6c8a4e2009-11-10 07:01:13 +000074 const DeclContext *getNominatedNamespace() const {
75 return Nominated;
76 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000077
John McCallf6c8a4e2009-11-10 07:01:13 +000078 // Sort by the pointer value of the common ancestor.
79 struct Comparator {
80 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
81 return L.getCommonAncestor() < R.getCommonAncestor();
82 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000083
John McCallf6c8a4e2009-11-10 07:01:13 +000084 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
85 return E.getCommonAncestor() < DC;
86 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000087
John McCallf6c8a4e2009-11-10 07:01:13 +000088 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
89 return DC < E.getCommonAncestor();
90 }
91 };
92 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000093
John McCallf6c8a4e2009-11-10 07:01:13 +000094 /// A collection of using directives, as used by C++ unqualified
95 /// lookup.
96 class UnqualUsingDirectiveSet {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000097 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000098
John McCallf6c8a4e2009-11-10 07:01:13 +000099 ListTy list;
100 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000101
John McCallf6c8a4e2009-11-10 07:01:13 +0000102 public:
103 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +0000104
John McCallf6c8a4e2009-11-10 07:01:13 +0000105 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000106 // C++ [namespace.udir]p1:
John McCallf6c8a4e2009-11-10 07:01:13 +0000107 // During unqualified name lookup, the names appear as if they
108 // were declared in the nearest enclosing namespace which contains
109 // both the using-directive and the nominated namespace.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000110 DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
John McCallf6c8a4e2009-11-10 07:01:13 +0000111 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +0000112
John McCallf6c8a4e2009-11-10 07:01:13 +0000113 for (; S; S = S->getParent()) {
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000114 // C++ [namespace.udir]p1:
115 // A using-directive shall not appear in class scope, but may
116 // appear in namespace scope or in block scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000117 DeclContext *Ctx = S->getEntity();
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000118 if (Ctx && Ctx->isFileContext()) {
119 visit(Ctx, Ctx);
120 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
Aaron Ballman5df6aa42014-03-17 17:03:37 +0000121 for (auto *I : S->using_directives())
122 visit(I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000123 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000124 }
125 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000126
127 // Visits a context and collect all of its using directives
128 // recursively. Treats all using directives as if they were
129 // declared in the context.
130 //
131 // A given context is only every visited once, so it is important
132 // that contexts be visited from the inside out in order to get
133 // the effective DCs right.
134 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
135 if (!visited.insert(DC))
136 return;
137
138 addUsingDirectives(DC, EffectiveDC);
139 }
140
141 // Visits a using directive and collects all of its using
142 // directives recursively. Treats all using directives as if they
143 // were declared in the effective DC.
144 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
145 DeclContext *NS = UD->getNominatedNamespace();
146 if (!visited.insert(NS))
147 return;
148
149 addUsingDirective(UD, EffectiveDC);
150 addUsingDirectives(NS, EffectiveDC);
151 }
152
153 // Adds all the using directives in a context (and those nominated
154 // by its using directives, transitively) as if they appeared in
155 // the given effective context.
156 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000157 SmallVector<DeclContext*,4> queue;
John McCallf6c8a4e2009-11-10 07:01:13 +0000158 while (true) {
Aaron Ballman804a7fb2014-03-17 17:14:12 +0000159 for (auto UD : DC->using_directives()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000160 DeclContext *NS = UD->getNominatedNamespace();
161 if (visited.insert(NS)) {
162 addUsingDirective(UD, EffectiveDC);
163 queue.push_back(NS);
164 }
165 }
166
167 if (queue.empty())
168 return;
169
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000170 DC = queue.pop_back_val();
John McCallf6c8a4e2009-11-10 07:01:13 +0000171 }
172 }
173
174 // Add a using directive as if it had been declared in the given
175 // context. This helps implement C++ [namespace.udir]p3:
176 // The using-directive is transitive: if a scope contains a
177 // using-directive that nominates a second namespace that itself
178 // contains using-directives, the effect is as if the
179 // using-directives from the second namespace also appeared in
180 // the first.
181 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
182 // Find the common ancestor between the effective context and
183 // the nominated namespace.
184 DeclContext *Common = UD->getNominatedNamespace();
185 while (!Common->Encloses(EffectiveDC))
186 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000187 Common = Common->getPrimaryContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000188
John McCallf6c8a4e2009-11-10 07:01:13 +0000189 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
190 }
191
192 void done() {
193 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
194 }
195
John McCallf6c8a4e2009-11-10 07:01:13 +0000196 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000197
John McCallf6c8a4e2009-11-10 07:01:13 +0000198 const_iterator begin() const { return list.begin(); }
199 const_iterator end() const { return list.end(); }
200
201 std::pair<const_iterator,const_iterator>
202 getNamespacesFor(DeclContext *DC) const {
John McCall9757d032009-11-10 09:20:04 +0000203 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCallf6c8a4e2009-11-10 07:01:13 +0000204 UnqualUsingEntry::Comparator());
205 }
206 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000207}
208
Douglas Gregor889ceb72009-02-03 19:21:40 +0000209// Retrieve the set of identifier namespaces that correspond to a
210// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000211static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
212 bool CPlusPlus,
213 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000214 unsigned IDNS = 0;
215 switch (NameKind) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +0000216 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000217 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000218 case Sema::LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +0000219 case Sema::LookupLocalFriendName:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000220 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000221 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000222 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000223 if (Redeclaration)
224 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCallea305ed2009-12-18 10:40:03 +0000225 }
Richard Smith541b38b2013-09-20 01:15:31 +0000226 if (Redeclaration)
227 IDNS |= Decl::IDNS_LocalExtern;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000228 break;
229
John McCallb9467b62010-04-24 01:30:58 +0000230 case Sema::LookupOperatorName:
231 // Operator lookup is its own crazy thing; it is not the same
232 // as (e.g.) looking up an operator name for redeclaration.
233 assert(!Redeclaration && "cannot do redeclaration operator lookup");
234 IDNS = Decl::IDNS_NonMemberOperator;
235 break;
236
Douglas Gregor889ceb72009-02-03 19:21:40 +0000237 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000238 if (CPlusPlus) {
239 IDNS = Decl::IDNS_Type;
240
241 // When looking for a redeclaration of a tag name, we add:
242 // 1) TagFriend to find undeclared friend decls
243 // 2) Namespace because they can't "overload" with tag decls.
244 // 3) Tag because it includes class templates, which can't
245 // "overload" with tag decls.
246 if (Redeclaration)
247 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
248 } else {
249 IDNS = Decl::IDNS_Tag;
250 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000251 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000252
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000253 case Sema::LookupLabel:
254 IDNS = Decl::IDNS_Label;
255 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000256
Douglas Gregor889ceb72009-02-03 19:21:40 +0000257 case Sema::LookupMemberName:
258 IDNS = Decl::IDNS_Member;
259 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000260 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000261 break;
262
263 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000264 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
265 break;
266
Douglas Gregor889ceb72009-02-03 19:21:40 +0000267 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000268 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000269 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000270
John McCall84d87672009-12-10 09:41:52 +0000271 case Sema::LookupUsingDeclName:
Richard Smith83e78f52014-04-11 01:03:38 +0000272 assert(Redeclaration && "should only be used for redecl lookup");
273 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |
274 Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend |
275 Decl::IDNS_LocalExtern;
John McCall84d87672009-12-10 09:41:52 +0000276 break;
277
Douglas Gregor79947a22009-04-24 00:11:27 +0000278 case Sema::LookupObjCProtocolName:
279 IDNS = Decl::IDNS_ObjCProtocol;
280 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000281
Douglas Gregor39982192010-08-15 06:18:01 +0000282 case Sema::LookupAnyName:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000283 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor39982192010-08-15 06:18:01 +0000284 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
285 | Decl::IDNS_Type;
286 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000287 }
288 return IDNS;
289}
290
John McCallea305ed2009-12-18 10:40:03 +0000291void LookupResult::configure() {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000292 IDNS = getIDNS(LookupKind, SemaRef.getLangOpts().CPlusPlus,
John McCallea305ed2009-12-18 10:40:03 +0000293 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000294
Richard Smithbdd14642014-02-04 01:14:30 +0000295 // If we're looking for one of the allocation or deallocation
296 // operators, make sure that the implicitly-declared new and delete
297 // operators can be found.
298 switch (NameInfo.getName().getCXXOverloadedOperator()) {
299 case OO_New:
300 case OO_Delete:
301 case OO_Array_New:
302 case OO_Array_Delete:
303 SemaRef.DeclareGlobalNewDelete();
304 break;
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000305
Richard Smithbdd14642014-02-04 01:14:30 +0000306 default:
307 break;
308 }
Douglas Gregor15197662013-04-03 23:06:26 +0000309
Richard Smithbdd14642014-02-04 01:14:30 +0000310 // Compiler builtins are always visible, regardless of where they end
311 // up being declared.
312 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
313 if (unsigned BuiltinID = Id->getBuiltinID()) {
314 if (!SemaRef.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
315 AllowHidden = true;
Douglas Gregor15197662013-04-03 23:06:26 +0000316 }
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000317 }
John McCallea305ed2009-12-18 10:40:03 +0000318}
319
Alp Tokerc1086762013-12-07 13:51:35 +0000320bool LookupResult::sanity() const {
Richard Smithf97ad222014-04-01 18:33:50 +0000321 // This function is never called by NDEBUG builds.
John McCall19c1bfd2010-08-25 05:32:35 +0000322 assert(ResultKind != NotFound || Decls.size() == 0);
323 assert(ResultKind != Found || Decls.size() == 1);
324 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
325 (Decls.size() == 1 &&
326 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
327 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
328 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000329 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
330 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall19c1bfd2010-08-25 05:32:35 +0000331 assert((Paths != NULL) == (ResultKind == Ambiguous &&
332 (Ambiguity == AmbiguousBaseSubobjectTypes ||
333 Ambiguity == AmbiguousBaseSubobjects)));
Alp Tokerc1086762013-12-07 13:51:35 +0000334 return true;
John McCall19c1bfd2010-08-25 05:32:35 +0000335}
John McCall19c1bfd2010-08-25 05:32:35 +0000336
John McCall9f3059a2009-10-09 21:13:30 +0000337// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000338void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000339 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000340}
341
Richard Smith3876cc82013-10-30 01:02:04 +0000342/// Get a representative context for a declaration such that two declarations
343/// will have the same context if they were found within the same scope.
Benjamin Kramerfc58b042013-11-01 11:50:55 +0000344static DeclContext *getContextForScopeMatching(Decl *D) {
Richard Smith3876cc82013-10-30 01:02:04 +0000345 // For function-local declarations, use that function as the context. This
346 // doesn't account for scopes within the function; the caller must deal with
347 // those.
348 DeclContext *DC = D->getLexicalDeclContext();
349 if (DC->isFunctionOrMethod())
350 return DC;
351
352 // Otherwise, look at the semantic context of the declaration. The
353 // declaration must have been found there.
354 return D->getDeclContext()->getRedeclContext();
355}
356
John McCall283b9012009-11-22 00:44:51 +0000357/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000358void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000359 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000360
John McCall9f3059a2009-10-09 21:13:30 +0000361 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000362 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000363 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000364 return;
365 }
366
John McCall283b9012009-11-22 00:44:51 +0000367 // If there's a single decl, we need to examine it to decide what
368 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000369 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000370 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
371 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000372 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000373 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000374 ResultKind = FoundUnresolvedValue;
375 return;
376 }
John McCall9f3059a2009-10-09 21:13:30 +0000377
John McCall6538c932009-10-10 05:48:19 +0000378 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000379 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000380
John McCall9f3059a2009-10-09 21:13:30 +0000381 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor13e65872010-08-11 14:45:53 +0000382 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000383
John McCall9f3059a2009-10-09 21:13:30 +0000384 bool Ambiguous = false;
385 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000386 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000387
388 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000389
John McCall9f3059a2009-10-09 21:13:30 +0000390 unsigned I = 0;
391 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000392 NamedDecl *D = Decls[I]->getUnderlyingDecl();
393 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000394
Argyrios Kyrtzidis1fcd7fd2013-02-22 06:58:37 +0000395 // Ignore an invalid declaration unless it's the only one left.
396 if (D->isInvalidDecl() && I < N-1) {
397 Decls[I] = Decls[--N];
398 continue;
399 }
400
Douglas Gregor13e65872010-08-11 14:45:53 +0000401 // Redeclarations of types via typedef can occur both within a scope
402 // and, through using declarations and directives, across scopes. There is
403 // no ambiguity if they all refer to the same type, so unique based on the
404 // canonical type.
405 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
406 if (!TD->getDeclContext()->isRecord()) {
407 QualType T = SemaRef.Context.getTypeDeclType(TD);
408 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
409 // The type is not unique; pull something off the back and continue
410 // at this index.
411 Decls[I] = Decls[--N];
412 continue;
413 }
414 }
415 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000416
John McCallf0f1cf02009-11-17 07:50:12 +0000417 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000418 // If it's not unique, pull something off the back (and
419 // continue at this index).
420 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000421 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000422 }
423
Douglas Gregor13e65872010-08-11 14:45:53 +0000424 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000425
Douglas Gregor13e65872010-08-11 14:45:53 +0000426 if (isa<UnresolvedUsingValueDecl>(D)) {
427 HasUnresolved = true;
428 } else if (isa<TagDecl>(D)) {
429 if (HasTag)
430 Ambiguous = true;
431 UniqueTagIndex = I;
432 HasTag = true;
433 } else if (isa<FunctionTemplateDecl>(D)) {
434 HasFunction = true;
435 HasFunctionTemplate = true;
436 } else if (isa<FunctionDecl>(D)) {
437 HasFunction = true;
438 } else {
439 if (HasNonFunction)
440 Ambiguous = true;
441 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000442 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000443 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000444 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000445
John McCall9f3059a2009-10-09 21:13:30 +0000446 // C++ [basic.scope.hiding]p2:
447 // A class name or enumeration name can be hidden by the name of
448 // an object, function, or enumerator declared in the same
449 // scope. If a class or enumeration name and an object, function,
450 // or enumerator are declared in the same scope (in any order)
451 // with the same name, the class or enumeration name is hidden
452 // wherever the object, function, or enumerator name is visible.
453 // But it's still an error if there are distinct tag types found,
454 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000455 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000456 (HasFunction || HasNonFunction || HasUnresolved)) {
Richard Smith3876cc82013-10-30 01:02:04 +0000457 if (getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
458 getContextForScopeMatching(Decls[UniqueTagIndex ? 0 : N - 1])))
Douglas Gregore63d0872010-10-23 16:06:17 +0000459 Decls[UniqueTagIndex] = Decls[--N];
460 else
461 Ambiguous = true;
462 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000463
John McCall9f3059a2009-10-09 21:13:30 +0000464 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000465
John McCall80053822009-12-03 00:58:24 +0000466 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000467 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000468
John McCall9f3059a2009-10-09 21:13:30 +0000469 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000470 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000471 else if (HasUnresolved)
472 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000473 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000474 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000475 else
John McCall27b18f82009-11-17 02:14:36 +0000476 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000477}
478
John McCall5cebab12009-11-18 07:57:50 +0000479void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000480 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000481 for (I = P.begin(), E = P.end(); I != E; ++I)
David Blaikieff7d47a2012-12-19 00:45:41 +0000482 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
483 DE = I->Decls.end(); DI != DE; ++DI)
John McCall9f3059a2009-10-09 21:13:30 +0000484 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000485}
486
John McCall5cebab12009-11-18 07:57:50 +0000487void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000488 Paths = new CXXBasePaths;
489 Paths->swap(P);
490 addDeclsFromBasePaths(*Paths);
491 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000492 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000493}
494
John McCall5cebab12009-11-18 07:57:50 +0000495void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000496 Paths = new CXXBasePaths;
497 Paths->swap(P);
498 addDeclsFromBasePaths(*Paths);
499 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000500 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000501}
502
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000503void LookupResult::print(raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000504 Out << Decls.size() << " result(s)";
505 if (isAmbiguous()) Out << ", ambiguous";
506 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000507
John McCall9f3059a2009-10-09 21:13:30 +0000508 for (iterator I = begin(), E = end(); I != E; ++I) {
509 Out << "\n";
510 (*I)->print(Out, 2);
511 }
512}
513
Douglas Gregord3a59182010-02-12 05:48:04 +0000514/// \brief Lookup a builtin function, when name lookup would otherwise
515/// fail.
516static bool LookupBuiltin(Sema &S, LookupResult &R) {
517 Sema::LookupNameKind NameKind = R.getLookupKind();
518
519 // If we didn't find a use of this identifier, and if the identifier
520 // corresponds to a compiler builtin, create the decl object for the builtin
521 // now, injecting it into translation unit scope, and return it.
522 if (NameKind == Sema::LookupOrdinaryName ||
523 NameKind == Sema::LookupRedeclarationWithLinkage) {
524 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
525 if (II) {
Nico Webere1687c52013-06-20 21:44:55 +0000526 if (S.getLangOpts().CPlusPlus11 && S.getLangOpts().GNUMode &&
527 II == S.getFloat128Identifier()) {
528 // libstdc++4.7's type_traits expects type __float128 to exist, so
529 // insert a dummy type to make that header build in gnu++11 mode.
530 R.addDecl(S.getASTContext().getFloat128StubType());
531 return true;
532 }
533
Douglas Gregord3a59182010-02-12 05:48:04 +0000534 // If this is a builtin on this (or all) targets, create the decl.
535 if (unsigned BuiltinID = II->getBuiltinID()) {
536 // In C++, we don't have any predefined library functions like
537 // 'malloc'. Instead, we'll just error.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000538 if (S.getLangOpts().CPlusPlus &&
Douglas Gregord3a59182010-02-12 05:48:04 +0000539 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
540 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000541
542 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
543 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000544 R.isForRedeclaration(),
545 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000546 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000547 return true;
548 }
Douglas Gregord3a59182010-02-12 05:48:04 +0000549 }
550 }
551 }
552
553 return false;
554}
555
Douglas Gregor7454c562010-07-02 20:37:36 +0000556/// \brief Determine whether we can declare a special member function within
557/// the class at this point.
Richard Smith7d125a12012-11-27 21:20:31 +0000558static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +0000559 // We need to have a definition for the class.
560 if (!Class->getDefinition() || Class->isDependentContext())
561 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000562
Douglas Gregor7454c562010-07-02 20:37:36 +0000563 // We can't be in the middle of defining the class.
Richard Smith7d125a12012-11-27 21:20:31 +0000564 return !Class->isBeingDefined();
Douglas Gregor7454c562010-07-02 20:37:36 +0000565}
566
567void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smith7d125a12012-11-27 21:20:31 +0000568 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregora6d69502010-07-02 23:41:54 +0000569 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000570
571 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000572 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000573 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000574
Douglas Gregora6d69502010-07-02 23:41:54 +0000575 // If the copy constructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000576 if (Class->needsImplicitCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +0000577 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000578
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000579 // If the copy assignment operator has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000580 if (Class->needsImplicitCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000581 DeclareImplicitCopyAssignment(Class);
582
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000583 if (getLangOpts().CPlusPlus11) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000584 // If the move constructor has not yet been declared, do so now.
585 if (Class->needsImplicitMoveConstructor())
586 DeclareImplicitMoveConstructor(Class); // might not actually do it
587
588 // If the move assignment operator has not yet been declared, do so now.
589 if (Class->needsImplicitMoveAssignment())
590 DeclareImplicitMoveAssignment(Class); // might not actually do it
591 }
592
Douglas Gregor7454c562010-07-02 20:37:36 +0000593 // If the destructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000594 if (Class->needsImplicitDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000595 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000596}
597
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000598/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000599/// special member function.
600static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
601 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000602 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000603 case DeclarationName::CXXDestructorName:
604 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000605
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000606 case DeclarationName::CXXOperatorName:
607 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000608
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000609 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000610 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000611 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000612
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000613 return false;
614}
615
616/// \brief If there are any implicit member functions with the given name
617/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000618static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000619 DeclarationName Name,
620 const DeclContext *DC) {
621 if (!DC)
622 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000623
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000624 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000625 case DeclarationName::CXXConstructorName:
626 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith7d125a12012-11-27 21:20:31 +0000627 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000628 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000629 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000630 S.DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +0000631 if (Record->needsImplicitCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000632 S.DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000633 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000634 Record->needsImplicitMoveConstructor())
635 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000636 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000637 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000638
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000639 case DeclarationName::CXXDestructorName:
640 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith2be35f52012-12-01 02:35:44 +0000641 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smith7d125a12012-11-27 21:20:31 +0000642 CanDeclareSpecialMemberFunction(Record))
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000643 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000644 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000645
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000646 case DeclarationName::CXXOperatorName:
647 if (Name.getCXXOverloadedOperator() != OO_Equal)
648 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000649
Sebastian Redl22653ba2011-08-30 19:58:05 +0000650 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smith7d125a12012-11-27 21:20:31 +0000651 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000652 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smith2be35f52012-12-01 02:35:44 +0000653 if (Record->needsImplicitCopyAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000654 S.DeclareImplicitCopyAssignment(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000655 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000656 Record->needsImplicitMoveAssignment())
657 S.DeclareImplicitMoveAssignment(Class);
658 }
659 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000660 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000661
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000662 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000663 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000664 }
665}
Douglas Gregor7454c562010-07-02 20:37:36 +0000666
John McCall9f3059a2009-10-09 21:13:30 +0000667// Adds all qualifying matches for a name within a decl context to the
668// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000669static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000670 bool Found = false;
671
Douglas Gregor7454c562010-07-02 20:37:36 +0000672 // Lazily declare C++ special member functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000673 if (S.getLangOpts().CPlusPlus)
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000674 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000675
Douglas Gregor7454c562010-07-02 20:37:36 +0000676 // Perform lookup into this declaration context.
David Blaikieff7d47a2012-12-19 00:45:41 +0000677 DeclContext::lookup_const_result DR = DC->lookup(R.getLookupName());
678 for (DeclContext::lookup_const_iterator I = DR.begin(), E = DR.end(); I != E;
679 ++I) {
John McCall401982f2010-01-20 21:53:11 +0000680 NamedDecl *D = *I;
Douglas Gregor4a814562011-12-14 16:03:29 +0000681 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000682 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000683 Found = true;
684 }
685 }
John McCall9f3059a2009-10-09 21:13:30 +0000686
Douglas Gregord3a59182010-02-12 05:48:04 +0000687 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
688 return true;
689
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000690 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000691 != DeclarationName::CXXConversionFunctionName ||
692 R.getLookupName().getCXXNameType()->isDependentType() ||
693 !isa<CXXRecordDecl>(DC))
694 return Found;
695
696 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000697 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000698 // name lookup. Instead, any conversion function templates visible in the
699 // context of the use are considered. [...]
700 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000701 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000702 return Found;
703
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +0000704 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
705 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruth3a693b72010-01-31 11:44:02 +0000706 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
707 if (!ConvTemplate)
708 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000709
Chandler Carruth3a693b72010-01-31 11:44:02 +0000710 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000711 // add the conversion function template. When we deduce template
712 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000713 // type of the new declaration with the type of the function template.
714 if (R.isForRedeclaration()) {
715 R.addDecl(ConvTemplate);
716 Found = true;
717 continue;
718 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000719
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000720 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000721 // [...] For each such operator, if argument deduction succeeds
722 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000723 // name lookup.
724 //
725 // When referencing a conversion function for any purpose other than
726 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000727 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000728 // specialization into the result set. We do this to avoid forcing all
729 // callers to perform special deduction for conversion functions.
Craig Toppere6706e42012-09-19 02:26:47 +0000730 TemplateDeductionInfo Info(R.getNameLoc());
Chandler Carruth3a693b72010-01-31 11:44:02 +0000731 FunctionDecl *Specialization = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000732
733 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000734 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
735 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000736
Chandler Carruth3a693b72010-01-31 11:44:02 +0000737 // Compute the type of the function that we would expect the conversion
738 // function to have, if it were to match the name given.
739 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000740 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
Reid Kleckner78af0702013-08-27 23:08:25 +0000741 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
Sebastian Redl7c6c9e92011-03-06 10:52:04 +0000742 EPI.ExceptionSpecType = EST_None;
John McCalldb40c7f2010-12-14 08:05:40 +0000743 EPI.NumExceptions = 0;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000744 QualType ExpectedType
745 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000746 None, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000747
Chandler Carruth3a693b72010-01-31 11:44:02 +0000748 // Perform template argument deduction against the type that we would
749 // expect the function to have.
750 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
751 Specialization, Info)
752 == Sema::TDK_Success) {
753 R.addDecl(Specialization);
754 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000755 }
756 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000757
John McCall9f3059a2009-10-09 21:13:30 +0000758 return Found;
759}
760
John McCallf6c8a4e2009-11-10 07:01:13 +0000761// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000762static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000763CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000764 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000765
766 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
767
John McCallf6c8a4e2009-11-10 07:01:13 +0000768 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000769 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000770
John McCallf6c8a4e2009-11-10 07:01:13 +0000771 // Perform direct name lookup into the namespaces nominated by the
772 // using directives whose common ancestor is this namespace.
773 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000774 std::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000775
John McCallf6c8a4e2009-11-10 07:01:13 +0000776 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000777 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000778 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000779
780 R.resolveKind();
781
782 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000783}
784
785static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000786 if (DeclContext *Ctx = S->getEntity())
Douglas Gregor700792c2009-02-05 19:25:20 +0000787 return Ctx->isFileContext();
788 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000789}
Douglas Gregored8f2882009-01-30 01:04:22 +0000790
Douglas Gregor66230062010-03-15 14:33:29 +0000791// Find the next outer declaration context from this scope. This
792// routine actually returns the semantic outer context, which may
793// differ from the lexical context (encoded directly in the Scope
794// stack) when we are parsing a member of a class template. In this
795// case, the second element of the pair will be true, to indicate that
796// name lookup should continue searching in this semantic context when
797// it leaves the current template parameter scope.
798static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000799 DeclContext *DC = S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +0000800 DeclContext *Lexical = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000801 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000802 OuterS = OuterS->getParent()) {
803 if (OuterS->getEntity()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000804 Lexical = OuterS->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +0000805 break;
806 }
807 }
808
809 // C++ [temp.local]p8:
810 // In the definition of a member of a class template that appears
811 // outside of the namespace containing the class template
812 // definition, the name of a template-parameter hides the name of
813 // a member of this namespace.
814 //
815 // Example:
816 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000817 // namespace N {
818 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000819 //
820 // template<class T> class B {
821 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000822 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000823 // }
824 //
825 // template<class C> void N::B<C>::f(C) {
826 // C b; // C is the template parameter, not N::C
827 // }
828 //
829 // In this example, the lexical context we return is the
830 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000831 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000832 !S->getParent()->isTemplateParamScope())
833 return std::make_pair(Lexical, false);
834
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000835 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000836 // For the example, this is the scope for the template parameters of
837 // template<class C>.
838 Scope *OutermostTemplateScope = S->getParent();
839 while (OutermostTemplateScope->getParent() &&
840 OutermostTemplateScope->getParent()->isTemplateParamScope())
841 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000842
Douglas Gregor66230062010-03-15 14:33:29 +0000843 // Find the namespace context in which the original scope occurs. In
844 // the example, this is namespace N.
845 DeclContext *Semantic = DC;
846 while (!Semantic->isFileContext())
847 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000848
Douglas Gregor66230062010-03-15 14:33:29 +0000849 // Find the declaration context just outside of the template
850 // parameter scope. This is the context in which the template is
851 // being lexically declaration (a namespace context). In the
852 // example, this is the global scope.
853 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
854 Lexical->Encloses(Semantic))
855 return std::make_pair(Semantic, true);
856
857 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000858}
859
Richard Smith541b38b2013-09-20 01:15:31 +0000860namespace {
861/// An RAII object to specify that we want to find block scope extern
862/// declarations.
863struct FindLocalExternScope {
864 FindLocalExternScope(LookupResult &R)
865 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
866 Decl::IDNS_LocalExtern) {
867 R.setFindLocalExtern(R.getIdentifierNamespace() & Decl::IDNS_Ordinary);
868 }
869 void restore() {
870 R.setFindLocalExtern(OldFindLocalExtern);
871 }
872 ~FindLocalExternScope() {
873 restore();
874 }
875 LookupResult &R;
876 bool OldFindLocalExtern;
877};
878}
879
John McCall27b18f82009-11-17 02:14:36 +0000880bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000881 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000882
883 DeclarationName Name = R.getLookupName();
Richard Smith1c34fb72013-08-13 18:18:50 +0000884 Sema::LookupNameKind NameKind = R.getLookupKind();
John McCall27b18f82009-11-17 02:14:36 +0000885
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000886 // If this is the name of an implicitly-declared special member function,
887 // go through the scope stack to implicitly declare
888 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
889 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +0000890 if (DeclContext *DC = PreS->getEntity())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000891 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
892 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000893
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000894 // Implicitly declare member functions with the name we're looking for, if in
895 // fact we are in a scope where it matters.
896
Douglas Gregor889ceb72009-02-03 19:21:40 +0000897 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000898 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000899 I = IdResolver.begin(Name),
900 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000901
Douglas Gregor889ceb72009-02-03 19:21:40 +0000902 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000903 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000904 // ...During unqualified name lookup (3.4.1), the names appear as if
905 // they were declared in the nearest enclosing namespace which contains
906 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000907 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000908 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000909 //
910 // For example:
911 // namespace A { int i; }
912 // void foo() {
913 // int i;
914 // {
915 // using namespace A;
916 // ++i; // finds local 'i', A::i appears at global scope
917 // }
918 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000919 //
Douglas Gregorcc9406c2013-04-08 23:11:25 +0000920 UnqualUsingDirectiveSet UDirs;
921 bool VisitedUsingDirectives = false;
Richard Smith1c34fb72013-08-13 18:18:50 +0000922 bool LeftStartingScope = false;
Douglas Gregor66230062010-03-15 14:33:29 +0000923 DeclContext *OutsideOfTemplateParamDC = 0;
Richard Smith541b38b2013-09-20 01:15:31 +0000924
925 // When performing a scope lookup, we want to find local extern decls.
926 FindLocalExternScope FindLocals(R);
927
Douglas Gregor700792c2009-02-05 19:25:20 +0000928 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000929 DeclContext *Ctx = S->getEntity();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000930
Douglas Gregor889ceb72009-02-03 19:21:40 +0000931 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000932 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000933 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000934 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Richard Smith1c34fb72013-08-13 18:18:50 +0000935 if (NameKind == LookupRedeclarationWithLinkage) {
936 // Determine whether this (or a previous) declaration is
937 // out-of-scope.
938 if (!LeftStartingScope && !Initial->isDeclScope(*I))
939 LeftStartingScope = true;
940
941 // If we found something outside of our starting scope that
Richard Smith9a00bbf2013-10-16 21:12:00 +0000942 // does not have linkage, skip it. If it's a template parameter,
943 // we still find it, so we can diagnose the invalid redeclaration.
944 if (LeftStartingScope && !((*I)->hasLinkage()) &&
945 !(*I)->isTemplateParameter()) {
Richard Smith1c34fb72013-08-13 18:18:50 +0000946 R.setShadowed();
947 continue;
948 }
949 }
950
John McCall9f3059a2009-10-09 21:13:30 +0000951 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +0000952 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000953 }
954 }
John McCall9f3059a2009-10-09 21:13:30 +0000955 if (Found) {
956 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000957 if (S->isClassScope())
958 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
959 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000960 return true;
961 }
962
Richard Smith1c34fb72013-08-13 18:18:50 +0000963 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
Richard Smith114394f2013-08-09 04:35:01 +0000964 // C++11 [class.friend]p11:
965 // If a friend declaration appears in a local class and the name
966 // specified is an unqualified name, a prior declaration is
967 // looked up without considering scopes that are outside the
968 // innermost enclosing non-class scope.
969 return false;
970 }
971
Douglas Gregor66230062010-03-15 14:33:29 +0000972 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
973 S->getParent() && !S->getParent()->isTemplateParamScope()) {
974 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000975 // found nothing, so look into the contexts between the
Douglas Gregor66230062010-03-15 14:33:29 +0000976 // lexical and semantic declaration contexts returned by
977 // findOuterContext(). This implements the name lookup behavior
978 // of C++ [temp.local]p8.
979 Ctx = OutsideOfTemplateParamDC;
980 OutsideOfTemplateParamDC = 0;
981 }
982
983 if (Ctx) {
984 DeclContext *OuterCtx;
985 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000986 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregor66230062010-03-15 14:33:29 +0000987 if (SearchAfterTemplateScope)
988 OutsideOfTemplateParamDC = OuterCtx;
989
Douglas Gregorea166062010-03-15 15:26:48 +0000990 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000991 // We do not directly look into transparent contexts, since
992 // those entities will be found in the nearest enclosing
993 // non-transparent context.
994 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000995 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000996
997 // We do not look directly into function or method contexts,
998 // since all of the local variables and parameters of the
999 // function/method are present within the Scope.
1000 if (Ctx->isFunctionOrMethod()) {
1001 // If we have an Objective-C instance method, look for ivars
1002 // in the corresponding interface.
1003 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
1004 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1005 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1006 ObjCInterfaceDecl *ClassDeclared;
1007 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001008 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +00001009 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001010 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1011 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +00001012 R.resolveKind();
1013 return true;
1014 }
1015 }
1016 }
1017 }
1018
1019 continue;
1020 }
1021
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001022 // If this is a file context, we need to perform unqualified name
1023 // lookup considering using directives.
1024 if (Ctx->isFileContext()) {
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001025 // If we haven't handled using directives yet, do so now.
1026 if (!VisitedUsingDirectives) {
1027 // Add using directives from this context up to the top level.
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001028 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1029 if (UCtx->isTransparentContext())
1030 continue;
1031
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001032 UDirs.visit(UCtx, UCtx);
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001033 }
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001034
1035 // Find the innermost file scope, so we can add using directives
1036 // from local scopes.
1037 Scope *InnermostFileScope = S;
1038 while (InnermostFileScope &&
1039 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1040 InnermostFileScope = InnermostFileScope->getParent();
1041 UDirs.visitScopeChain(Initial, InnermostFileScope);
1042
1043 UDirs.done();
1044
1045 VisitedUsingDirectives = true;
1046 }
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001047
1048 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1049 R.resolveKind();
1050 return true;
1051 }
1052
1053 continue;
1054 }
1055
Douglas Gregor7f737c02009-09-10 16:57:35 +00001056 // Perform qualified name lookup into this context.
1057 // FIXME: In some cases, we know that every name that could be found by
1058 // this qualified name lookup will also be on the identifier chain. For
1059 // example, inside a class without any base classes, we never need to
1060 // perform qualified lookup because all of the members are on top of the
1061 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001062 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +00001063 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +00001064 }
Douglas Gregor700792c2009-02-05 19:25:20 +00001065 }
Douglas Gregored8f2882009-01-30 01:04:22 +00001066 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001067
John McCallf6c8a4e2009-11-10 07:01:13 +00001068 // Stop if we ran out of scopes.
1069 // FIXME: This really, really shouldn't be happening.
1070 if (!S) return false;
1071
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001072 // If we are looking for members, no need to look into global/namespace scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00001073 if (NameKind == LookupMemberName)
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001074 return false;
1075
Douglas Gregor700792c2009-02-05 19:25:20 +00001076 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +00001077 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +00001078 //
Mike Stump87c57ac2009-05-16 07:39:55 +00001079 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1080 // don't build it for each lookup!
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001081 if (!VisitedUsingDirectives) {
1082 UDirs.visitScopeChain(Initial, S);
1083 UDirs.done();
1084 }
Richard Smith541b38b2013-09-20 01:15:31 +00001085
1086 // If we're not performing redeclaration lookup, do not look for local
1087 // extern declarations outside of a function scope.
1088 if (!R.isForRedeclaration())
1089 FindLocals.restore();
1090
Douglas Gregor700792c2009-02-05 19:25:20 +00001091 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +00001092 // Unqualified name lookup in C++ requires looking into scopes
1093 // that aren't strictly lexical, and therefore we walk through the
1094 // context as well as walking through the scopes.
1095 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001096 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +00001097 bool Found = false;
John McCall48871652010-08-21 09:40:31 +00001098 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001099 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001100 // We found something. Look for anything else in our scope
1101 // with this same name and in an acceptable identifier
1102 // namespace, so that we can construct an overload set if we
1103 // need to.
John McCall9f3059a2009-10-09 21:13:30 +00001104 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +00001105 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001106 }
1107 }
1108
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001109 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +00001110 R.resolveKind();
1111 return true;
1112 }
1113
Ted Kremenekc37877d2013-10-08 17:08:03 +00001114 DeclContext *Ctx = S->getEntity();
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001115 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1116 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1117 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001118 // found nothing, so look into the contexts between the
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001119 // lexical and semantic declaration contexts returned by
1120 // findOuterContext(). This implements the name lookup behavior
1121 // of C++ [temp.local]p8.
1122 Ctx = OutsideOfTemplateParamDC;
1123 OutsideOfTemplateParamDC = 0;
1124 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001125
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001126 if (Ctx) {
1127 DeclContext *OuterCtx;
1128 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001129 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001130 if (SearchAfterTemplateScope)
1131 OutsideOfTemplateParamDC = OuterCtx;
1132
1133 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1134 // We do not directly look into transparent contexts, since
1135 // those entities will be found in the nearest enclosing
1136 // non-transparent context.
1137 if (Ctx->isTransparentContext())
1138 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001139
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001140 // If we have a context, and it's not a context stashed in the
1141 // template parameter scope for an out-of-line definition, also
1142 // look into that context.
1143 if (!(Found && S && S->isTemplateParamScope())) {
1144 assert(Ctx->isFileContext() &&
1145 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001146
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001147 // Look into context considering using-directives.
1148 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1149 Found = true;
1150 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001151
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001152 if (Found) {
1153 R.resolveKind();
1154 return true;
1155 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001156
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001157 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1158 return false;
1159 }
1160 }
1161
Douglas Gregor3ce74932010-02-05 07:07:10 +00001162 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001163 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001164 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001165
John McCall9f3059a2009-10-09 21:13:30 +00001166 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001167}
1168
Richard Smith0e5d7b82013-07-25 23:08:39 +00001169/// \brief Find the declaration that a class temploid member specialization was
1170/// instantiated from, or the member itself if it is an explicit specialization.
1171static Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) {
1172 return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom();
1173}
1174
1175/// \brief Find the module in which the given declaration was defined.
1176static Module *getDefiningModule(Decl *Entity) {
1177 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1178 // If this function was instantiated from a template, the defining module is
1179 // the module containing the pattern.
1180 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1181 Entity = Pattern;
1182 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
1183 // If it's a class template specialization, find the template or partial
1184 // specialization from which it was instantiated.
1185 if (ClassTemplateSpecializationDecl *SpecRD =
1186 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
1187 llvm::PointerUnion<ClassTemplateDecl*,
1188 ClassTemplatePartialSpecializationDecl*> From =
1189 SpecRD->getInstantiatedFrom();
1190 if (ClassTemplateDecl *FromTemplate = From.dyn_cast<ClassTemplateDecl*>())
1191 Entity = FromTemplate->getTemplatedDecl();
1192 else if (From)
1193 Entity = From.get<ClassTemplatePartialSpecializationDecl*>();
1194 // Otherwise, it's an explicit specialization.
1195 } else if (MemberSpecializationInfo *MSInfo =
1196 RD->getMemberSpecializationInfo())
1197 Entity = getInstantiatedFrom(RD, MSInfo);
1198 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1199 if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo())
1200 Entity = getInstantiatedFrom(ED, MSInfo);
1201 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1202 // FIXME: Map from variable template specializations back to the template.
1203 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo())
1204 Entity = getInstantiatedFrom(VD, MSInfo);
1205 }
1206
1207 // Walk up to the containing context. That might also have been instantiated
1208 // from a template.
1209 DeclContext *Context = Entity->getDeclContext();
1210 if (Context->isFileContext())
1211 return Entity->getOwningModule();
1212 return getDefiningModule(cast<Decl>(Context));
1213}
1214
1215llvm::DenseSet<Module*> &Sema::getLookupModules() {
1216 unsigned N = ActiveTemplateInstantiations.size();
1217 for (unsigned I = ActiveTemplateInstantiationLookupModules.size();
1218 I != N; ++I) {
1219 Module *M = getDefiningModule(ActiveTemplateInstantiations[I].Entity);
1220 if (M && !LookupModulesCache.insert(M).second)
1221 M = 0;
1222 ActiveTemplateInstantiationLookupModules.push_back(M);
1223 }
1224 return LookupModulesCache;
1225}
1226
1227/// \brief Determine whether a declaration is visible to name lookup.
1228///
1229/// This routine determines whether the declaration D is visible in the current
1230/// lookup context, taking into account the current template instantiation
1231/// stack. During template instantiation, a declaration is visible if it is
1232/// visible from a module containing any entity on the template instantiation
1233/// path (by instantiating a template, you allow it to see the declarations that
1234/// your module can see, including those later on in your module).
1235bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
1236 assert(D->isHidden() && !SemaRef.ActiveTemplateInstantiations.empty() &&
1237 "should not call this: not in slow case");
1238 Module *DeclModule = D->getOwningModule();
1239 assert(DeclModule && "hidden decl not from a module");
1240
1241 // Find the extra places where we need to look.
1242 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
1243 if (LookupModules.empty())
1244 return false;
1245
1246 // If our lookup set contains the decl's module, it's visible.
1247 if (LookupModules.count(DeclModule))
1248 return true;
1249
1250 // If the declaration isn't exported, it's not visible in any other module.
1251 if (D->isModulePrivate())
1252 return false;
1253
1254 // Check whether DeclModule is transitively exported to an import of
1255 // the lookup set.
1256 for (llvm::DenseSet<Module *>::iterator I = LookupModules.begin(),
1257 E = LookupModules.end();
1258 I != E; ++I)
1259 if ((*I)->isModuleVisible(DeclModule))
1260 return true;
1261 return false;
1262}
1263
Douglas Gregor4a814562011-12-14 16:03:29 +00001264/// \brief Retrieve the visible declaration corresponding to D, if any.
1265///
1266/// This routine determines whether the declaration D is visible in the current
1267/// module, with the current imports. If not, it checks whether any
1268/// redeclaration of D is visible, and if so, returns that declaration.
Richard Smith0e5d7b82013-07-25 23:08:39 +00001269///
Douglas Gregor4a814562011-12-14 16:03:29 +00001270/// \returns D, or a visible previous declaration of D, whichever is more recent
1271/// and visible. If no declaration of D is visible, returns null.
Richard Smithe156254d2013-08-20 20:35:18 +00001272static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
1273 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
Richard Smith0e5d7b82013-07-25 23:08:39 +00001274
Aaron Ballman86c93902014-03-06 23:45:36 +00001275 for (auto RD : D->redecls()) {
1276 if (auto ND = dyn_cast<NamedDecl>(RD)) {
Richard Smithe156254d2013-08-20 20:35:18 +00001277 if (LookupResult::isVisible(SemaRef, ND))
Douglas Gregor54079202012-01-06 22:05:37 +00001278 return ND;
1279 }
Douglas Gregor4a814562011-12-14 16:03:29 +00001280 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001281
Douglas Gregor4a814562011-12-14 16:03:29 +00001282 return 0;
1283}
1284
Richard Smithe156254d2013-08-20 20:35:18 +00001285NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
1286 return findAcceptableDecl(SemaRef, D);
1287}
1288
Douglas Gregor34074322009-01-14 22:20:51 +00001289/// @brief Perform unqualified name lookup starting from a given
1290/// scope.
1291///
1292/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1293/// used to find names within the current scope. For example, 'x' in
1294/// @code
1295/// int x;
1296/// int f() {
1297/// return x; // unqualified name look finds 'x' in the global scope
1298/// }
1299/// @endcode
1300///
1301/// Different lookup criteria can find different names. For example, a
1302/// particular scope can have both a struct and a function of the same
1303/// name, and each can be found by certain lookup criteria. For more
1304/// information about lookup criteria, see the documentation for the
1305/// class LookupCriteria.
1306///
1307/// @param S The scope from which unqualified name lookup will
1308/// begin. If the lookup criteria permits, name lookup may also search
1309/// in the parent scopes.
1310///
James Dennett91738ff2012-06-22 10:32:46 +00001311/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1312/// look up and the lookup kind), and is updated with the results of lookup
1313/// including zero or more declarations and possibly additional information
1314/// used to diagnose ambiguities.
Douglas Gregor34074322009-01-14 22:20:51 +00001315///
James Dennett91738ff2012-06-22 10:32:46 +00001316/// @returns \c true if lookup succeeded and false otherwise.
John McCall27b18f82009-11-17 02:14:36 +00001317bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1318 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001319 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001320
John McCall27b18f82009-11-17 02:14:36 +00001321 LookupNameKind NameKind = R.getLookupKind();
1322
David Blaikiebbafb8a2012-03-11 07:00:24 +00001323 if (!getLangOpts().CPlusPlus) {
Douglas Gregor34074322009-01-14 22:20:51 +00001324 // Unqualified name lookup in C/Objective-C is purely lexical, so
1325 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001326 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001327 // Find the nearest non-transparent declaration scope.
1328 while (!(S->getFlags() & Scope::DeclScope) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001329 (S->getEntity() && S->getEntity()->isTransparentContext()))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001330 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001331 }
1332
Richard Smith541b38b2013-09-20 01:15:31 +00001333 // When performing a scope lookup, we want to find local extern decls.
1334 FindLocalExternScope FindLocals(R);
1335
Douglas Gregor34074322009-01-14 22:20:51 +00001336 // Scan up the scope chain looking for a decl that matches this
1337 // identifier that is in the appropriate namespace. This search
1338 // should not take long, as shadowing of names is uncommon, and
1339 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001340 bool LeftStartingScope = false;
1341
Douglas Gregored8f2882009-01-30 01:04:22 +00001342 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001343 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001344 I != IEnd; ++I)
Richard Smith0e5d7b82013-07-25 23:08:39 +00001345 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001346 if (NameKind == LookupRedeclarationWithLinkage) {
1347 // Determine whether this (or a previous) declaration is
1348 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001349 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001350 LeftStartingScope = true;
1351
1352 // If we found something outside of our starting scope that
1353 // does not have linkage, skip it.
Richard Smith1c34fb72013-08-13 18:18:50 +00001354 if (LeftStartingScope && !((*I)->hasLinkage())) {
1355 R.setShadowed();
Douglas Gregoreddf4332009-02-24 20:03:32 +00001356 continue;
Richard Smith1c34fb72013-08-13 18:18:50 +00001357 }
Douglas Gregoreddf4332009-02-24 20:03:32 +00001358 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001359 else if (NameKind == LookupObjCImplicitSelfParam &&
1360 !isa<ImplicitParamDecl>(*I))
1361 continue;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001362
Douglas Gregor4a814562011-12-14 16:03:29 +00001363 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001364
Douglas Gregorb59643b2012-01-03 23:26:26 +00001365 // Check whether there are any other declarations with the same name
1366 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001367 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001368 // Find the scope in which this declaration was declared (if it
1369 // actually exists in a Scope).
1370 while (S && !S->isDeclScope(D))
1371 S = S->getParent();
1372
1373 // If the scope containing the declaration is the translation unit,
1374 // then we'll need to perform our checks based on the matching
1375 // DeclContexts rather than matching scopes.
1376 if (S && isNamespaceOrTranslationUnitScope(S))
1377 S = 0;
1378
1379 // Compute the DeclContext, if we need it.
1380 DeclContext *DC = 0;
1381 if (!S)
1382 DC = (*I)->getDeclContext()->getRedeclContext();
1383
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001384 IdentifierResolver::iterator LastI = I;
1385 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001386 if (S) {
1387 // Match based on scope.
1388 if (!S->isDeclScope(*LastI))
1389 break;
1390 } else {
1391 // Match based on DeclContext.
1392 DeclContext *LastDC
1393 = (*LastI)->getDeclContext()->getRedeclContext();
1394 if (!LastDC->Equals(DC))
1395 break;
1396 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001397
1398 // If the declaration is in the right namespace and visible, add it.
1399 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1400 R.addDecl(LastD);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001401 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001402
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001403 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001404 }
Richard Smith541b38b2013-09-20 01:15:31 +00001405
John McCall9f3059a2009-10-09 21:13:30 +00001406 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001407 }
Douglas Gregor34074322009-01-14 22:20:51 +00001408 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001409 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001410 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001411 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001412 }
1413
1414 // If we didn't find a use of this identifier, and if the identifier
1415 // corresponds to a compiler builtin, create the decl object for the builtin
1416 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001417 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1418 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001419
Axel Naumann016538a2011-02-24 16:47:47 +00001420 // If we didn't find a use of this identifier, the ExternalSource
1421 // may be able to handle the situation.
1422 // Note: some lookup failures are expected!
1423 // See e.g. R.isForRedeclaration().
1424 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001425}
1426
John McCall6538c932009-10-10 05:48:19 +00001427/// @brief Perform qualified name lookup in the namespaces nominated by
1428/// using directives by the given context.
1429///
1430/// C++98 [namespace.qual]p2:
James Dennett51a8d8b2012-06-19 21:05:49 +00001431/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6538c932009-10-10 05:48:19 +00001432/// (where X is the global namespace), let S be the set of all
1433/// declarations of m in X and in the transitive closure of all
1434/// namespaces nominated by using-directives in X and its used
1435/// namespaces, except that using-directives are ignored in any
1436/// namespace, including X, directly containing one or more
1437/// declarations of m. No namespace is searched more than once in
1438/// the lookup of a name. If S is the empty set, the program is
1439/// ill-formed. Otherwise, if S has exactly one member, or if the
1440/// context of the reference is a using-declaration
1441/// (namespace.udecl), S is the required set of declarations of
1442/// m. Otherwise if the use of m is not one that allows a unique
1443/// declaration to be chosen from S, the program is ill-formed.
James Dennett51a8d8b2012-06-19 21:05:49 +00001444///
John McCall6538c932009-10-10 05:48:19 +00001445/// C++98 [namespace.qual]p5:
1446/// During the lookup of a qualified namespace member name, if the
1447/// lookup finds more than one declaration of the member, and if one
1448/// declaration introduces a class name or enumeration name and the
1449/// other declarations either introduce the same object, the same
1450/// enumerator or a set of functions, the non-type name hides the
1451/// class or enumeration name if and only if the declarations are
1452/// from the same namespace; otherwise (the declarations are from
1453/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001454static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001455 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001456 assert(StartDC->isFileContext() && "start context is not a file context");
1457
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001458 DeclContext::udir_range UsingDirectives = StartDC->using_directives();
1459 if (UsingDirectives.begin() == UsingDirectives.end()) return false;
John McCall6538c932009-10-10 05:48:19 +00001460
1461 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001462 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001463 Visited.insert(StartDC);
1464
1465 // We have not yet looked into these namespaces, much less added
1466 // their "using-children" to the queue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001467 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001468
1469 // We have already looked into the initial namespace; seed the queue
1470 // with its using-children.
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001471 for (auto *I : UsingDirectives) {
1472 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001473 if (Visited.insert(ND))
John McCall6538c932009-10-10 05:48:19 +00001474 Queue.push_back(ND);
1475 }
1476
1477 // The easiest way to implement the restriction in [namespace.qual]p5
1478 // is to check whether any of the individual results found a tag
1479 // and, if so, to declare an ambiguity if the final result is not
1480 // a tag.
1481 bool FoundTag = false;
1482 bool FoundNonTag = false;
1483
John McCall5cebab12009-11-18 07:57:50 +00001484 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001485
1486 bool Found = false;
1487 while (!Queue.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001488 NamespaceDecl *ND = Queue.pop_back_val();
John McCall6538c932009-10-10 05:48:19 +00001489
1490 // We go through some convolutions here to avoid copying results
1491 // between LookupResults.
1492 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001493 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001494 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001495
1496 if (FoundDirect) {
1497 // First do any local hiding.
1498 DirectR.resolveKind();
1499
1500 // If the local result is a tag, remember that.
1501 if (DirectR.isSingleTagDecl())
1502 FoundTag = true;
1503 else
1504 FoundNonTag = true;
1505
1506 // Append the local results to the total results if necessary.
1507 if (UseLocal) {
1508 R.addAllDecls(LocalR);
1509 LocalR.clear();
1510 }
1511 }
1512
1513 // If we find names in this namespace, ignore its using directives.
1514 if (FoundDirect) {
1515 Found = true;
1516 continue;
1517 }
1518
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001519 for (auto I : ND->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00001520 NamespaceDecl *Nom = I->getNominatedNamespace();
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001521 if (Visited.insert(Nom))
John McCall6538c932009-10-10 05:48:19 +00001522 Queue.push_back(Nom);
1523 }
1524 }
1525
1526 if (Found) {
1527 if (FoundTag && FoundNonTag)
1528 R.setAmbiguousQualifiedTagHiding();
1529 else
1530 R.resolveKind();
1531 }
1532
1533 return Found;
1534}
1535
Douglas Gregor39982192010-08-15 06:18:01 +00001536/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001537static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor39982192010-08-15 06:18:01 +00001538 CXXBasePath &Path,
1539 void *Name) {
1540 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001541
Douglas Gregor39982192010-08-15 06:18:01 +00001542 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1543 Path.Decls = BaseRecord->lookup(N);
David Blaikieff7d47a2012-12-19 00:45:41 +00001544 return !Path.Decls.empty();
Douglas Gregor39982192010-08-15 06:18:01 +00001545}
1546
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001547/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001548/// static members, nested types, and enumerators.
1549template<typename InputIterator>
1550static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1551 Decl *D = (*First)->getUnderlyingDecl();
1552 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1553 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001554
Douglas Gregorc0d24902010-10-22 22:08:47 +00001555 if (isa<CXXMethodDecl>(D)) {
1556 // Determine whether all of the methods are static.
1557 bool AllMethodsAreStatic = true;
1558 for(; First != Last; ++First) {
1559 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001560
Douglas Gregorc0d24902010-10-22 22:08:47 +00001561 if (!isa<CXXMethodDecl>(D)) {
1562 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1563 break;
1564 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001565
Douglas Gregorc0d24902010-10-22 22:08:47 +00001566 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1567 AllMethodsAreStatic = false;
1568 break;
1569 }
1570 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001571
Douglas Gregorc0d24902010-10-22 22:08:47 +00001572 if (AllMethodsAreStatic)
1573 return true;
1574 }
1575
1576 return false;
1577}
1578
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001579/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001580///
1581/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1582/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001583/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001584///
1585/// Different lookup criteria can find different names. For example, a
1586/// particular scope can have both a struct and a function of the same
1587/// name, and each can be found by certain lookup criteria. For more
1588/// information about lookup criteria, see the documentation for the
1589/// class LookupCriteria.
1590///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001591/// \param R captures both the lookup criteria and any lookup results found.
1592///
1593/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001594/// search. If the lookup criteria permits, name lookup may also search
1595/// in the parent contexts or (for C++ classes) base classes.
1596///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001597/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001598/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001599///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001600/// \returns true if lookup succeeded, false if it failed.
1601bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1602 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001603 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001604
John McCall27b18f82009-11-17 02:14:36 +00001605 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001606 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001607
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001608 // Make sure that the declaration context is complete.
1609 assert((!isa<TagDecl>(LookupCtx) ||
1610 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00001611 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith7d137e32012-03-23 03:33:32 +00001612 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001613 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001614
Douglas Gregor34074322009-01-14 22:20:51 +00001615 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001616 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001617 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001618 if (isa<CXXRecordDecl>(LookupCtx))
1619 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001620 return true;
1621 }
Douglas Gregor34074322009-01-14 22:20:51 +00001622
John McCall6538c932009-10-10 05:48:19 +00001623 // Don't descend into implied contexts for redeclarations.
1624 // C++98 [namespace.qual]p6:
1625 // In a declaration for a namespace member in which the
1626 // declarator-id is a qualified-id, given that the qualified-id
1627 // for the namespace member has the form
1628 // nested-name-specifier unqualified-id
1629 // the unqualified-id shall name a member of the namespace
1630 // designated by the nested-name-specifier.
1631 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001632 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001633 return false;
1634
John McCall27b18f82009-11-17 02:14:36 +00001635 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001636 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001637 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001638
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001639 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001640 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001641 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001642 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001643 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001644
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001645 // If we're performing qualified name lookup into a dependent class,
1646 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001647 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001648 // template instantiation time (at which point all bases will be available)
1649 // or we have to fail.
1650 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1651 LookupRec->hasAnyDependentBases()) {
1652 R.setNotFoundInCurrentInstantiation();
1653 return false;
1654 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001655
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001656 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001657 CXXBasePaths Paths;
1658 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001659
1660 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001661 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001662 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001663 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001664 case LookupOrdinaryName:
1665 case LookupMemberName:
1666 case LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +00001667 case LookupLocalFriendName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001668 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1669 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001670
Douglas Gregor36d1b142009-10-06 17:59:45 +00001671 case LookupTagName:
1672 BaseCallback = &CXXRecordDecl::FindTagMember;
1673 break;
John McCall84d87672009-12-10 09:41:52 +00001674
Douglas Gregor39982192010-08-15 06:18:01 +00001675 case LookupAnyName:
1676 BaseCallback = &LookupAnyMember;
1677 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001678
John McCall84d87672009-12-10 09:41:52 +00001679 case LookupUsingDeclName:
1680 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001681
Douglas Gregor36d1b142009-10-06 17:59:45 +00001682 case LookupOperatorName:
1683 case LookupNamespaceName:
1684 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001685 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001686 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001687 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001688
Douglas Gregor36d1b142009-10-06 17:59:45 +00001689 case LookupNestedNameSpecifierName:
1690 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1691 break;
1692 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001693
John McCall27b18f82009-11-17 02:14:36 +00001694 if (!LookupRec->lookupInBases(BaseCallback,
1695 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001696 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001697
John McCall553c0792010-01-23 00:46:32 +00001698 R.setNamingClass(LookupRec);
1699
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001700 // C++ [class.member.lookup]p2:
1701 // [...] If the resulting set of declarations are not all from
1702 // sub-objects of the same type, or the set has a nonstatic member
1703 // and includes members from distinct sub-objects, there is an
1704 // ambiguity and the program is ill-formed. Otherwise that set is
1705 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001706 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001707 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001708 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001709
Douglas Gregor36d1b142009-10-06 17:59:45 +00001710 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001711 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001712 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001713
John McCall401982f2010-01-20 21:53:11 +00001714 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1715 // across all paths.
1716 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001717
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001718 // Determine whether we're looking at a distinct sub-object or not.
1719 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001720 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001721 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1722 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001723 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001724 }
1725
Douglas Gregorc0d24902010-10-22 22:08:47 +00001726 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001727 != Context.getCanonicalType(PathElement.Base->getType())) {
1728 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001729 // different types. If the declaration sets aren't the same, this
1730 // this lookup is ambiguous.
David Blaikieff7d47a2012-12-19 00:45:41 +00001731 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00001732 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikieff7d47a2012-12-19 00:45:41 +00001733 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
1734 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001735
David Blaikieff7d47a2012-12-19 00:45:41 +00001736 while (FirstD != FirstPath->Decls.end() &&
1737 CurrentD != Path->Decls.end()) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00001738 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1739 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1740 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001741
Douglas Gregorc0d24902010-10-22 22:08:47 +00001742 ++FirstD;
1743 ++CurrentD;
1744 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001745
David Blaikieff7d47a2012-12-19 00:45:41 +00001746 if (FirstD == FirstPath->Decls.end() &&
1747 CurrentD == Path->Decls.end())
Douglas Gregorc0d24902010-10-22 22:08:47 +00001748 continue;
1749 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001750
John McCall9f3059a2009-10-09 21:13:30 +00001751 R.setAmbiguousBaseSubobjectTypes(Paths);
1752 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001753 }
1754
Douglas Gregorc0d24902010-10-22 22:08:47 +00001755 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001756 // We have a different subobject of the same type.
1757
1758 // C++ [class.member.lookup]p5:
1759 // A static member, a nested type or an enumerator defined in
1760 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001761 // has more than one base class subobject of type T.
David Blaikieff7d47a2012-12-19 00:45:41 +00001762 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001763 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001764
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001765 // We have found a nonstatic member name in multiple, distinct
1766 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001767 R.setAmbiguousBaseSubobjects(Paths);
1768 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001769 }
1770 }
1771
1772 // Lookup in a base class succeeded; return these results.
1773
David Blaikieff7d47a2012-12-19 00:45:41 +00001774 DeclContext::lookup_result DR = Paths.front().Decls;
1775 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E; ++I) {
John McCall553c0792010-01-23 00:46:32 +00001776 NamedDecl *D = *I;
1777 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1778 D->getAccess());
1779 R.addDecl(D, AS);
1780 }
John McCall9f3059a2009-10-09 21:13:30 +00001781 R.resolveKind();
1782 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001783}
1784
1785/// @brief Performs name lookup for a name that was parsed in the
1786/// source code, and may contain a C++ scope specifier.
1787///
1788/// This routine is a convenience routine meant to be called from
1789/// contexts that receive a name and an optional C++ scope specifier
1790/// (e.g., "N::M::x"). It will then perform either qualified or
1791/// unqualified name lookup (with LookupQualifiedName or LookupName,
1792/// respectively) on the given name and return those results.
1793///
1794/// @param S The scope from which unqualified name lookup will
1795/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001796///
Douglas Gregore861bac2009-08-25 22:51:20 +00001797/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001798///
Douglas Gregore861bac2009-08-25 22:51:20 +00001799/// @param EnteringContext Indicates whether we are going to enter the
1800/// context of the scope-specifier SS (if present).
1801///
John McCall9f3059a2009-10-09 21:13:30 +00001802/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001803bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001804 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001805 if (SS && SS->isInvalid()) {
1806 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001807 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001808 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001809 }
Mike Stump11289f42009-09-09 15:08:12 +00001810
Douglas Gregore861bac2009-08-25 22:51:20 +00001811 if (SS && SS->isSet()) {
1812 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001813 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001814 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001815 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001816 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001817
John McCall27b18f82009-11-17 02:14:36 +00001818 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00001819 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001820 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001821
Douglas Gregore861bac2009-08-25 22:51:20 +00001822 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001823 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001824 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00001825 R.setNotFoundInCurrentInstantiation();
1826 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00001827 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001828 }
1829
Mike Stump11289f42009-09-09 15:08:12 +00001830 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001831 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001832}
1833
Douglas Gregor889ceb72009-02-03 19:21:40 +00001834
James Dennett41725122012-06-22 10:16:05 +00001835/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001836/// from name lookup.
1837///
James Dennett41725122012-06-22 10:16:05 +00001838/// \param Result The result of the ambiguous lookup to be diagnosed.
Serge Pavlov99292092013-08-29 07:23:24 +00001839void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001840 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1841
John McCall27b18f82009-11-17 02:14:36 +00001842 DeclarationName Name = Result.getLookupName();
1843 SourceLocation NameLoc = Result.getNameLoc();
1844 SourceRange LookupRange = Result.getContextRange();
1845
John McCall6538c932009-10-10 05:48:19 +00001846 switch (Result.getAmbiguityKind()) {
1847 case LookupResult::AmbiguousBaseSubobjects: {
1848 CXXBasePaths *Paths = Result.getBasePaths();
1849 QualType SubobjectType = Paths->front().back().Base->getType();
1850 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1851 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1852 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001853
David Blaikieff7d47a2012-12-19 00:45:41 +00001854 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6538c932009-10-10 05:48:19 +00001855 while (isa<CXXMethodDecl>(*Found) &&
1856 cast<CXXMethodDecl>(*Found)->isStatic())
1857 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001858
John McCall6538c932009-10-10 05:48:19 +00001859 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
Serge Pavlov99292092013-08-29 07:23:24 +00001860 break;
John McCall6538c932009-10-10 05:48:19 +00001861 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001862
John McCall6538c932009-10-10 05:48:19 +00001863 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001864 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1865 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001866
John McCall6538c932009-10-10 05:48:19 +00001867 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001868 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001869 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1870 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001871 Path != PathEnd; ++Path) {
David Blaikieff7d47a2012-12-19 00:45:41 +00001872 Decl *D = Path->Decls.front();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001873 if (DeclsPrinted.insert(D).second)
1874 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1875 }
Serge Pavlov99292092013-08-29 07:23:24 +00001876 break;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001877 }
1878
John McCall6538c932009-10-10 05:48:19 +00001879 case LookupResult::AmbiguousTagHiding: {
1880 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001881
John McCall6538c932009-10-10 05:48:19 +00001882 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1883
1884 LookupResult::iterator DI, DE = Result.end();
1885 for (DI = Result.begin(); DI != DE; ++DI)
1886 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1887 TagDecls.insert(TD);
1888 Diag(TD->getLocation(), diag::note_hidden_tag);
1889 }
1890
1891 for (DI = Result.begin(); DI != DE; ++DI)
1892 if (!isa<TagDecl>(*DI))
1893 Diag((*DI)->getLocation(), diag::note_hiding_object);
1894
1895 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001896 LookupResult::Filter F = Result.makeFilter();
1897 while (F.hasNext()) {
1898 if (TagDecls.count(F.next()))
1899 F.erase();
1900 }
1901 F.done();
Serge Pavlov99292092013-08-29 07:23:24 +00001902 break;
John McCall6538c932009-10-10 05:48:19 +00001903 }
1904
1905 case LookupResult::AmbiguousReference: {
1906 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001907
John McCall6538c932009-10-10 05:48:19 +00001908 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1909 for (; DI != DE; ++DI)
1910 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
Serge Pavlov99292092013-08-29 07:23:24 +00001911 break;
John McCall6538c932009-10-10 05:48:19 +00001912 }
Serge Pavlov99292092013-08-29 07:23:24 +00001913 }
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001914}
Douglas Gregore254f902009-02-04 00:32:51 +00001915
John McCallf24d7bb2010-05-28 18:45:08 +00001916namespace {
1917 struct AssociatedLookup {
John McCall7d8b0412012-08-24 20:38:34 +00001918 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallf24d7bb2010-05-28 18:45:08 +00001919 Sema::AssociatedNamespaceSet &Namespaces,
1920 Sema::AssociatedClassSet &Classes)
John McCall7d8b0412012-08-24 20:38:34 +00001921 : S(S), Namespaces(Namespaces), Classes(Classes),
1922 InstantiationLoc(InstantiationLoc) {
John McCallf24d7bb2010-05-28 18:45:08 +00001923 }
1924
1925 Sema &S;
1926 Sema::AssociatedNamespaceSet &Namespaces;
1927 Sema::AssociatedClassSet &Classes;
John McCall7d8b0412012-08-24 20:38:34 +00001928 SourceLocation InstantiationLoc;
John McCallf24d7bb2010-05-28 18:45:08 +00001929 };
1930}
1931
Mike Stump11289f42009-09-09 15:08:12 +00001932static void
John McCallf24d7bb2010-05-28 18:45:08 +00001933addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001934
Douglas Gregor8b895222010-04-30 07:08:38 +00001935static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1936 DeclContext *Ctx) {
1937 // Add the associated namespace for this class.
1938
1939 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1940 // be a locally scoped record.
1941
Sebastian Redlbd595762010-08-31 20:53:31 +00001942 // We skip out of inline namespaces. The innermost non-inline namespace
1943 // contains all names of all its nested inline namespaces anyway, so we can
1944 // replace the entire inline namespace tree with its root.
1945 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1946 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00001947 Ctx = Ctx->getParent();
1948
John McCallc7e8e792009-08-07 22:18:02 +00001949 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001950 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001951}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001952
Mike Stump11289f42009-09-09 15:08:12 +00001953// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001954// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001955static void
John McCallf24d7bb2010-05-28 18:45:08 +00001956addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1957 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001958 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001959 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001960 switch (Arg.getKind()) {
1961 case TemplateArgument::Null:
1962 break;
Mike Stump11289f42009-09-09 15:08:12 +00001963
Douglas Gregor197e5f72009-07-08 07:51:57 +00001964 case TemplateArgument::Type:
1965 // [...] the namespaces and classes associated with the types of the
1966 // template arguments provided for template type parameters (excluding
1967 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001968 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001969 break;
Mike Stump11289f42009-09-09 15:08:12 +00001970
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001971 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001972 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00001973 // [...] the namespaces in which any template template arguments are
1974 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001975 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001976 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00001977 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001978 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001979 DeclContext *Ctx = ClassTemplate->getDeclContext();
1980 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001981 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001982 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001983 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001984 }
1985 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001986 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001987
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001988 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001989 case TemplateArgument::Integral:
1990 case TemplateArgument::Expression:
Eli Friedmanb826a002012-09-26 02:36:12 +00001991 case TemplateArgument::NullPtr:
Mike Stump11289f42009-09-09 15:08:12 +00001992 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001993 // associated namespaces. ]
1994 break;
Mike Stump11289f42009-09-09 15:08:12 +00001995
Douglas Gregor197e5f72009-07-08 07:51:57 +00001996 case TemplateArgument::Pack:
1997 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1998 PEnd = Arg.pack_end();
1999 P != PEnd; ++P)
John McCallf24d7bb2010-05-28 18:45:08 +00002000 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002001 break;
2002 }
2003}
2004
Douglas Gregore254f902009-02-04 00:32:51 +00002005// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00002006// argument-dependent lookup with an argument of class type
2007// (C++ [basic.lookup.koenig]p2).
2008static void
John McCallf24d7bb2010-05-28 18:45:08 +00002009addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2010 CXXRecordDecl *Class) {
2011
2012 // Just silently ignore anything whose name is __va_list_tag.
2013 if (Class->getDeclName() == Result.S.VAListTagName)
2014 return;
2015
Douglas Gregore254f902009-02-04 00:32:51 +00002016 // C++ [basic.lookup.koenig]p2:
2017 // [...]
2018 // -- If T is a class type (including unions), its associated
2019 // classes are: the class itself; the class of which it is a
2020 // member, if any; and its direct and indirect base
2021 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00002022 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00002023
2024 // Add the class of which it is a member, if any.
2025 DeclContext *Ctx = Class->getDeclContext();
2026 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002027 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002028 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002029 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002030
Douglas Gregore254f902009-02-04 00:32:51 +00002031 // Add the class itself. If we've already seen this class, we don't
2032 // need to visit base classes.
Richard Smith594461f2014-03-14 22:07:27 +00002033 //
2034 // FIXME: That's not correct, we may have added this class only because it
2035 // was the enclosing class of another class, and in that case we won't have
2036 // added its base classes yet.
John McCallf24d7bb2010-05-28 18:45:08 +00002037 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00002038 return;
2039
Mike Stump11289f42009-09-09 15:08:12 +00002040 // -- If T is a template-id, its associated namespaces and classes are
2041 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002042 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00002043 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00002044 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00002045 // namespaces in which any template template arguments are defined; and
2046 // the classes in which any member templates used as template template
2047 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00002048 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00002049 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00002050 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2051 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2052 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002053 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002054 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002055 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002056
Douglas Gregor197e5f72009-07-08 07:51:57 +00002057 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2058 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00002059 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002060 }
Mike Stump11289f42009-09-09 15:08:12 +00002061
John McCall67da35c2010-02-04 22:26:26 +00002062 // Only recurse into base classes for complete types.
Richard Smith594461f2014-03-14 22:07:27 +00002063 if (!Class->hasDefinition())
2064 return;
John McCall67da35c2010-02-04 22:26:26 +00002065
Douglas Gregore254f902009-02-04 00:32:51 +00002066 // Add direct and indirect base classes along with their associated
2067 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002068 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00002069 Bases.push_back(Class);
2070 while (!Bases.empty()) {
2071 // Pop this class off the stack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002072 Class = Bases.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002073
2074 // Visit the base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +00002075 for (const auto &Base : Class->bases()) {
2076 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00002077 // In dependent contexts, we do ADL twice, and the first time around,
2078 // the base type might be a dependent TemplateSpecializationType, or a
2079 // TemplateTypeParmType. If that happens, simply ignore it.
2080 // FIXME: If we want to support export, we probably need to add the
2081 // namespace of the template in a TemplateSpecializationType, or even
2082 // the classes and namespaces of known non-dependent arguments.
2083 if (!BaseType)
2084 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002085 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002086 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00002087 // Find the associated namespace for this base class.
2088 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00002089 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00002090
2091 // Make sure we visit the bases of this base class.
2092 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2093 Bases.push_back(BaseDecl);
2094 }
2095 }
2096 }
2097}
2098
2099// \brief Add the associated classes and namespaces for
2100// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00002101// (C++ [basic.lookup.koenig]p2).
2102static void
John McCallf24d7bb2010-05-28 18:45:08 +00002103addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00002104 // C++ [basic.lookup.koenig]p2:
2105 //
2106 // For each argument type T in the function call, there is a set
2107 // of zero or more associated namespaces and a set of zero or more
2108 // associated classes to be considered. The sets of namespaces and
2109 // classes is determined entirely by the types of the function
2110 // arguments (and the namespace of any template template
2111 // argument). Typedef names and using-declarations used to specify
2112 // the types do not contribute to this set. The sets of namespaces
2113 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00002114
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002115 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00002116 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2117
Douglas Gregore254f902009-02-04 00:32:51 +00002118 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00002119 switch (T->getTypeClass()) {
2120
2121#define TYPE(Class, Base)
2122#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2123#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2124#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2125#define ABSTRACT_TYPE(Class, Base)
2126#include "clang/AST/TypeNodes.def"
2127 // T is canonical. We can also ignore dependent types because
2128 // we don't need to do ADL at the definition point, but if we
2129 // wanted to implement template export (or if we find some other
2130 // use for associated classes and namespaces...) this would be
2131 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00002132 break;
Douglas Gregore254f902009-02-04 00:32:51 +00002133
John McCall0af3d3b2010-05-28 06:08:54 +00002134 // -- If T is a pointer to U or an array of U, its associated
2135 // namespaces and classes are those associated with U.
2136 case Type::Pointer:
2137 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2138 continue;
2139 case Type::ConstantArray:
2140 case Type::IncompleteArray:
2141 case Type::VariableArray:
2142 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2143 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002144
John McCall0af3d3b2010-05-28 06:08:54 +00002145 // -- If T is a fundamental type, its associated sets of
2146 // namespaces and classes are both empty.
2147 case Type::Builtin:
2148 break;
2149
2150 // -- If T is a class type (including unions), its associated
2151 // classes are: the class itself; the class of which it is a
2152 // member, if any; and its direct and indirect base
2153 // classes. Its associated namespaces are the namespaces in
2154 // which its associated classes are defined.
2155 case Type::Record: {
Richard Smith594461f2014-03-14 22:07:27 +00002156 Result.S.RequireCompleteType(Result.InstantiationLoc, QualType(T, 0),
2157 /*no diagnostic*/ 0);
John McCall0af3d3b2010-05-28 06:08:54 +00002158 CXXRecordDecl *Class
2159 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002160 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00002161 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00002162 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00002163
John McCall0af3d3b2010-05-28 06:08:54 +00002164 // -- If T is an enumeration type, its associated namespace is
2165 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002166 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00002167 // it has no associated class.
2168 case Type::Enum: {
2169 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002170
John McCall0af3d3b2010-05-28 06:08:54 +00002171 DeclContext *Ctx = Enum->getDeclContext();
2172 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002173 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002174
John McCall0af3d3b2010-05-28 06:08:54 +00002175 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002176 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00002177
John McCall0af3d3b2010-05-28 06:08:54 +00002178 break;
2179 }
2180
2181 // -- If T is a function type, its associated namespaces and
2182 // classes are those associated with the function parameter
2183 // types and those associated with the return type.
2184 case Type::FunctionProto: {
2185 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002186 for (const auto &Arg : Proto->param_types())
2187 Queue.push_back(Arg.getTypePtr());
John McCall0af3d3b2010-05-28 06:08:54 +00002188 // fallthrough
2189 }
2190 case Type::FunctionNoProto: {
2191 const FunctionType *FnType = cast<FunctionType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00002192 T = FnType->getReturnType().getTypePtr();
John McCall0af3d3b2010-05-28 06:08:54 +00002193 continue;
2194 }
2195
2196 // -- If T is a pointer to a member function of a class X, its
2197 // associated namespaces and classes are those associated
2198 // with the function parameter types and return type,
2199 // together with those associated with X.
2200 //
2201 // -- If T is a pointer to a data member of class X, its
2202 // associated namespaces and classes are those associated
2203 // with the member type together with those associated with
2204 // X.
2205 case Type::MemberPointer: {
2206 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2207
2208 // Queue up the class type into which this points.
2209 Queue.push_back(MemberPtr->getClass());
2210
2211 // And directly continue with the pointee type.
2212 T = MemberPtr->getPointeeType().getTypePtr();
2213 continue;
2214 }
2215
2216 // As an extension, treat this like a normal pointer.
2217 case Type::BlockPointer:
2218 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2219 continue;
2220
2221 // References aren't covered by the standard, but that's such an
2222 // obvious defect that we cover them anyway.
2223 case Type::LValueReference:
2224 case Type::RValueReference:
2225 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2226 continue;
2227
2228 // These are fundamental types.
2229 case Type::Vector:
2230 case Type::ExtVector:
2231 case Type::Complex:
2232 break;
2233
Richard Smith27d807c2013-04-30 13:56:41 +00002234 // Non-deduced auto types only get here for error cases.
2235 case Type::Auto:
2236 break;
2237
Douglas Gregor8e936662011-04-12 01:02:45 +00002238 // If T is an Objective-C object or interface type, or a pointer to an
2239 // object or interface type, the associated namespace is the global
2240 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002241 case Type::ObjCObject:
2242 case Type::ObjCInterface:
2243 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002244 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002245 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002246
2247 // Atomic types are just wrappers; use the associations of the
2248 // contained type.
2249 case Type::Atomic:
2250 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2251 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002252 }
2253
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002254 if (Queue.empty())
2255 break;
2256 T = Queue.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002257 }
Douglas Gregore254f902009-02-04 00:32:51 +00002258}
2259
2260/// \brief Find the associated classes and namespaces for
2261/// argument-dependent lookup for a call with the given set of
2262/// arguments.
2263///
2264/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002265/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002266/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00002267void Sema::FindAssociatedClassesAndNamespaces(
2268 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2269 AssociatedNamespaceSet &AssociatedNamespaces,
2270 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002271 AssociatedNamespaces.clear();
2272 AssociatedClasses.clear();
2273
John McCall7d8b0412012-08-24 20:38:34 +00002274 AssociatedLookup Result(*this, InstantiationLoc,
2275 AssociatedNamespaces, AssociatedClasses);
John McCallf24d7bb2010-05-28 18:45:08 +00002276
Douglas Gregore254f902009-02-04 00:32:51 +00002277 // C++ [basic.lookup.koenig]p2:
2278 // For each argument type T in the function call, there is a set
2279 // of zero or more associated namespaces and a set of zero or more
2280 // associated classes to be considered. The sets of namespaces and
2281 // classes is determined entirely by the types of the function
2282 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002283 // argument).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002284 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregore254f902009-02-04 00:32:51 +00002285 Expr *Arg = Args[ArgIdx];
2286
2287 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002288 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002289 continue;
2290 }
2291
2292 // [...] In addition, if the argument is the name or address of a
2293 // set of overloaded functions and/or function templates, its
2294 // associated classes and namespaces are the union of those
2295 // associated with each of the members of the set: the namespace
2296 // in which the function or function template is defined and the
2297 // classes and namespaces associated with its (non-dependent)
2298 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002299 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002300 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002301 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002302 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002303
John McCallf24d7bb2010-05-28 18:45:08 +00002304 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2305 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002306
John McCallf24d7bb2010-05-28 18:45:08 +00002307 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2308 I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002309 // Look through any using declarations to find the underlying function.
Alp Tokera2794f92014-01-22 07:29:52 +00002310 FunctionDecl *FDecl = (*I)->getUnderlyingDecl()->getAsFunction();
Douglas Gregore254f902009-02-04 00:32:51 +00002311
2312 // Add the classes and namespaces associated with the parameter
2313 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002314 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002315 }
2316 }
2317}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002318
John McCall5cebab12009-11-18 07:57:50 +00002319NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002320 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002321 LookupNameKind NameKind,
2322 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002323 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002324 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002325 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002326}
2327
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002328/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002329ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002330 SourceLocation IdLoc,
2331 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002332 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002333 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002334 return cast_or_null<ObjCProtocolDecl>(D);
2335}
2336
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002337void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002338 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002339 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002340 // C++ [over.match.oper]p3:
2341 // -- The set of non-member candidates is the result of the
2342 // unqualified lookup of operator@ in the context of the
2343 // expression according to the usual rules for name lookup in
2344 // unqualified function calls (3.4.2) except that all member
Richard Smith100b24a2014-04-17 01:52:14 +00002345 // functions are ignored.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002346 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002347 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2348 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002349
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002350 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
Richard Smith100b24a2014-04-17 01:52:14 +00002351 Functions.append(Operators.begin(), Operators.end());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002352}
2353
Alexis Hunt1da39282011-06-24 02:11:39 +00002354Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002355 CXXSpecialMember SM,
2356 bool ConstArg,
2357 bool VolatileArg,
2358 bool RValueThis,
2359 bool ConstThis,
2360 bool VolatileThis) {
Richard Smith7d125a12012-11-27 21:20:31 +00002361 assert(CanDeclareSpecialMemberFunction(RD) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002362 "doing special member lookup into record that isn't fully complete");
Richard Smith7d125a12012-11-27 21:20:31 +00002363 RD = RD->getDefinition();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002364 if (RValueThis || ConstThis || VolatileThis)
2365 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2366 "constructors and destructors always have unqualified lvalue this");
2367 if (ConstArg || VolatileArg)
2368 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2369 "parameter-less special members can't have qualified arguments");
2370
2371 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002372 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002373 ID.AddInteger(SM);
2374 ID.AddInteger(ConstArg);
2375 ID.AddInteger(VolatileArg);
2376 ID.AddInteger(RValueThis);
2377 ID.AddInteger(ConstThis);
2378 ID.AddInteger(VolatileThis);
2379
2380 void *InsertPoint;
2381 SpecialMemberOverloadResult *Result =
2382 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2383
2384 // This was already cached
2385 if (Result)
2386 return Result;
2387
Alexis Huntba8e18d2011-06-07 00:11:58 +00002388 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2389 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002390 SpecialMemberCache.InsertNode(Result, InsertPoint);
2391
2392 if (SM == CXXDestructor) {
Richard Smith2be35f52012-12-01 02:35:44 +00002393 if (RD->needsImplicitDestructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002394 DeclareImplicitDestructor(RD);
2395 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002396 assert(DD && "record without a destructor");
2397 Result->setMethod(DD);
Richard Smith852265f2012-03-30 20:53:28 +00002398 Result->setKind(DD->isDeleted() ?
2399 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith83c478d2012-04-20 18:46:14 +00002400 SpecialMemberOverloadResult::Success);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002401 return Result;
2402 }
2403
Alexis Hunteef8ee02011-06-10 03:50:41 +00002404 // Prepare for overload resolution. Here we construct a synthetic argument
2405 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002406 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002407 DeclarationName Name;
2408 Expr *Arg = 0;
2409 unsigned NumArgs;
2410
Richard Smith83c478d2012-04-20 18:46:14 +00002411 QualType ArgType = CanTy;
2412 ExprValueKind VK = VK_LValue;
2413
Alexis Hunteef8ee02011-06-10 03:50:41 +00002414 if (SM == CXXDefaultConstructor) {
2415 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2416 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002417 if (RD->needsImplicitDefaultConstructor())
2418 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002419 } else {
2420 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2421 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smith2be35f52012-12-01 02:35:44 +00002422 if (RD->needsImplicitCopyConstructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002423 DeclareImplicitCopyConstructor(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002424 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002425 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002426 } else {
2427 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smith2be35f52012-12-01 02:35:44 +00002428 if (RD->needsImplicitCopyAssignment())
Alexis Hunt1da39282011-06-24 02:11:39 +00002429 DeclareImplicitCopyAssignment(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002430 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002431 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002432 }
2433
Alexis Hunteef8ee02011-06-10 03:50:41 +00002434 if (ConstArg)
2435 ArgType.addConst();
2436 if (VolatileArg)
2437 ArgType.addVolatile();
2438
2439 // This isn't /really/ specified by the standard, but it's implied
2440 // we should be working from an RValue in the case of move to ensure
2441 // that we prefer to bind to rvalue references, and an LValue in the
2442 // case of copy to ensure we don't bind to rvalue references.
2443 // Possibly an XValue is actually correct in the case of move, but
2444 // there is no semantic difference for class types in this restricted
2445 // case.
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002446 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002447 VK = VK_LValue;
2448 else
2449 VK = VK_RValue;
Richard Smith83c478d2012-04-20 18:46:14 +00002450 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00002451
Richard Smith83c478d2012-04-20 18:46:14 +00002452 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2453
2454 if (SM != CXXDefaultConstructor) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002455 NumArgs = 1;
Richard Smith83c478d2012-04-20 18:46:14 +00002456 Arg = &FakeArg;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002457 }
2458
2459 // Create the object argument
2460 QualType ThisTy = CanTy;
2461 if (ConstThis)
2462 ThisTy.addConst();
2463 if (VolatileThis)
2464 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002465 Expr::Classification Classification =
Richard Smith83c478d2012-04-20 18:46:14 +00002466 OpaqueValueExpr(SourceLocation(), ThisTy,
2467 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002468
2469 // Now we perform lookup on the name we computed earlier and do overload
2470 // resolution. Lookup is only performed directly into the class since there
2471 // will always be a (possibly implicit) declaration to shadow any others.
Richard Smith100b24a2014-04-17 01:52:14 +00002472 OverloadCandidateSet OCS(RD->getLocation(), OverloadCandidateSet::CSK_Normal);
David Blaikieff7d47a2012-12-19 00:45:41 +00002473 DeclContext::lookup_result R = RD->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00002474 assert(!R.empty() &&
Alexis Hunteef8ee02011-06-10 03:50:41 +00002475 "lookup for a constructor or assignment operator was empty");
Chandler Carruth7deaae72013-08-18 07:20:52 +00002476
2477 // Copy the candidates as our processing of them may load new declarations
2478 // from an external source and invalidate lookup_result.
2479 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2480
2481 for (SmallVectorImpl<NamedDecl *>::iterator I = Candidates.begin(),
Richard Smithd55889a2013-09-09 16:55:27 +00002482 E = Candidates.end();
Chandler Carruth7deaae72013-08-18 07:20:52 +00002483 I != E; ++I) {
2484 NamedDecl *Cand = *I;
Alexis Hunt080709f2011-06-23 00:26:20 +00002485
Alexis Hunt1da39282011-06-24 02:11:39 +00002486 if (Cand->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002487 continue;
2488
Alexis Hunt1da39282011-06-24 02:11:39 +00002489 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2490 // FIXME: [namespace.udecl]p15 says that we should only consider a
2491 // using declaration here if it does not match a declaration in the
2492 // derived class. We do not implement this correctly in other cases
2493 // either.
2494 Cand = U->getTargetDecl();
2495
2496 if (Cand->isInvalidDecl())
2497 continue;
2498 }
2499
2500 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002501 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Alexis Hunt1da39282011-06-24 02:11:39 +00002502 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002503 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2504 OCS, true);
Alexis Hunt080709f2011-06-23 00:26:20 +00002505 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002506 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2507 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt2949f022011-06-22 02:58:46 +00002508 } else if (FunctionTemplateDecl *Tmpl =
Alexis Hunt1da39282011-06-24 02:11:39 +00002509 dyn_cast<FunctionTemplateDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002510 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2511 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002512 RD, 0, ThisTy, Classification,
2513 llvm::makeArrayRef(&Arg, NumArgs),
Alexis Hunt080709f2011-06-23 00:26:20 +00002514 OCS, true);
2515 else
2516 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002517 0, llvm::makeArrayRef(&Arg, NumArgs),
2518 OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002519 } else {
2520 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002521 }
2522 }
2523
2524 OverloadCandidateSet::iterator Best;
2525 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2526 case OR_Success:
2527 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith83c478d2012-04-20 18:46:14 +00002528 Result->setKind(SpecialMemberOverloadResult::Success);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002529 break;
2530
2531 case OR_Deleted:
2532 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith852265f2012-03-30 20:53:28 +00002533 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002534 break;
2535
2536 case OR_Ambiguous:
Richard Smith852265f2012-03-30 20:53:28 +00002537 Result->setMethod(0);
2538 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2539 break;
2540
Alexis Hunteef8ee02011-06-10 03:50:41 +00002541 case OR_No_Viable_Function:
2542 Result->setMethod(0);
Richard Smith852265f2012-03-30 20:53:28 +00002543 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002544 break;
2545 }
2546
2547 return Result;
2548}
2549
2550/// \brief Look up the default constructor for the given class.
2551CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002552 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002553 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2554 false, false);
2555
2556 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002557}
2558
Alexis Hunt491ec602011-06-21 23:42:56 +00002559/// \brief Look up the copying constructor for the given class.
2560CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith83c478d2012-04-20 18:46:14 +00002561 unsigned Quals) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002562 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2563 "non-const, non-volatile qualifiers for copy ctor arg");
2564 SpecialMemberOverloadResult *Result =
2565 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2566 Quals & Qualifiers::Volatile, false, false, false);
2567
Alexis Hunt899bd442011-06-10 04:44:37 +00002568 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2569}
2570
Sebastian Redl22653ba2011-08-30 19:58:05 +00002571/// \brief Look up the moving constructor for the given class.
Richard Smith1c6461e2012-07-18 03:36:00 +00002572CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2573 unsigned Quals) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002574 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002575 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2576 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002577
2578 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2579}
2580
Douglas Gregor52b72822010-07-02 23:12:18 +00002581/// \brief Look up the constructors for the given class.
2582DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002583 // If the implicit constructors have not yet been declared, do so now.
Richard Smith7d125a12012-11-27 21:20:31 +00002584 if (CanDeclareSpecialMemberFunction(Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00002585 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002586 DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +00002587 if (Class->needsImplicitCopyConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002588 DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002589 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002590 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00002591 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002592
Douglas Gregor52b72822010-07-02 23:12:18 +00002593 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2594 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2595 return Class->lookup(Name);
2596}
2597
Alexis Hunt491ec602011-06-21 23:42:56 +00002598/// \brief Look up the copying assignment operator for the given class.
2599CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2600 unsigned Quals, bool RValueThis,
Richard Smith83c478d2012-04-20 18:46:14 +00002601 unsigned ThisQuals) {
Alexis Hunt491ec602011-06-21 23:42:56 +00002602 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2603 "non-const, non-volatile qualifiers for copy assignment arg");
2604 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2605 "non-const, non-volatile qualifiers for copy assignment this");
2606 SpecialMemberOverloadResult *Result =
2607 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2608 Quals & Qualifiers::Volatile, RValueThis,
2609 ThisQuals & Qualifiers::Const,
2610 ThisQuals & Qualifiers::Volatile);
2611
Alexis Hunt491ec602011-06-21 23:42:56 +00002612 return Result->getMethod();
2613}
2614
Sebastian Redl22653ba2011-08-30 19:58:05 +00002615/// \brief Look up the moving assignment operator for the given class.
2616CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith1c6461e2012-07-18 03:36:00 +00002617 unsigned Quals,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002618 bool RValueThis,
2619 unsigned ThisQuals) {
2620 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2621 "non-const, non-volatile qualifiers for copy assignment this");
2622 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002623 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2624 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002625 ThisQuals & Qualifiers::Const,
2626 ThisQuals & Qualifiers::Volatile);
2627
2628 return Result->getMethod();
2629}
2630
Douglas Gregore71edda2010-07-01 22:47:18 +00002631/// \brief Look for the destructor of the given class.
2632///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00002633/// During semantic analysis, this routine should be used in lieu of
2634/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00002635///
2636/// \returns The destructor for this class.
2637CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002638 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2639 false, false, false,
2640 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00002641}
2642
Richard Smithbcc22fc2012-03-09 08:00:36 +00002643/// LookupLiteralOperator - Determine which literal operator should be used for
2644/// a user-defined literal, per C++11 [lex.ext].
2645///
2646/// Normal overload resolution is not used to select which literal operator to
2647/// call for a user-defined literal. Look up the provided literal operator name,
2648/// and filter the results to the appropriate set for the given argument types.
2649Sema::LiteralOperatorLookupResult
2650Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2651 ArrayRef<QualType> ArgTys,
Richard Smithb8b41d32013-10-07 19:57:58 +00002652 bool AllowRaw, bool AllowTemplate,
2653 bool AllowStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002654 LookupName(R, S);
2655 assert(R.getResultKind() != LookupResult::Ambiguous &&
2656 "literal operator lookup can't be ambiguous");
2657
2658 // Filter the lookup results appropriately.
2659 LookupResult::Filter F = R.makeFilter();
2660
Richard Smithbcc22fc2012-03-09 08:00:36 +00002661 bool FoundRaw = false;
Richard Smithb8b41d32013-10-07 19:57:58 +00002662 bool FoundTemplate = false;
2663 bool FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002664 bool FoundExactMatch = false;
2665
2666 while (F.hasNext()) {
2667 Decl *D = F.next();
2668 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2669 D = USD->getTargetDecl();
2670
Douglas Gregorc1970572013-04-10 05:18:00 +00002671 // If the declaration we found is invalid, skip it.
2672 if (D->isInvalidDecl()) {
2673 F.erase();
2674 continue;
2675 }
2676
Richard Smithb8b41d32013-10-07 19:57:58 +00002677 bool IsRaw = false;
2678 bool IsTemplate = false;
2679 bool IsStringTemplate = false;
2680 bool IsExactMatch = false;
2681
Richard Smithbcc22fc2012-03-09 08:00:36 +00002682 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2683 if (FD->getNumParams() == 1 &&
2684 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2685 IsRaw = true;
Richard Smith550de452013-01-15 07:12:59 +00002686 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002687 IsExactMatch = true;
2688 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2689 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2690 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2691 IsExactMatch = false;
2692 break;
2693 }
2694 }
2695 }
2696 }
Richard Smithb8b41d32013-10-07 19:57:58 +00002697 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
2698 TemplateParameterList *Params = FD->getTemplateParameters();
2699 if (Params->size() == 1)
2700 IsTemplate = true;
2701 else
2702 IsStringTemplate = true;
2703 }
Richard Smithbcc22fc2012-03-09 08:00:36 +00002704
2705 if (IsExactMatch) {
2706 FoundExactMatch = true;
Richard Smithb8b41d32013-10-07 19:57:58 +00002707 AllowRaw = false;
2708 AllowTemplate = false;
2709 AllowStringTemplate = false;
2710 if (FoundRaw || FoundTemplate || FoundStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002711 // Go through again and remove the raw and template decls we've
2712 // already found.
2713 F.restart();
Richard Smithb8b41d32013-10-07 19:57:58 +00002714 FoundRaw = FoundTemplate = FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002715 }
Richard Smithb8b41d32013-10-07 19:57:58 +00002716 } else if (AllowRaw && IsRaw) {
2717 FoundRaw = true;
2718 } else if (AllowTemplate && IsTemplate) {
2719 FoundTemplate = true;
2720 } else if (AllowStringTemplate && IsStringTemplate) {
2721 FoundStringTemplate = true;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002722 } else {
2723 F.erase();
2724 }
2725 }
2726
2727 F.done();
2728
2729 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2730 // parameter type, that is used in preference to a raw literal operator
2731 // or literal operator template.
2732 if (FoundExactMatch)
2733 return LOLR_Cooked;
2734
2735 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2736 // operator template, but not both.
2737 if (FoundRaw && FoundTemplate) {
2738 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
Alp Tokera2794f92014-01-22 07:29:52 +00002739 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2740 NoteOverloadCandidate((*I)->getUnderlyingDecl()->getAsFunction());
Richard Smithbcc22fc2012-03-09 08:00:36 +00002741 return LOLR_Error;
2742 }
2743
2744 if (FoundRaw)
2745 return LOLR_Raw;
2746
2747 if (FoundTemplate)
2748 return LOLR_Template;
2749
Richard Smithb8b41d32013-10-07 19:57:58 +00002750 if (FoundStringTemplate)
2751 return LOLR_StringTemplate;
2752
Richard Smithbcc22fc2012-03-09 08:00:36 +00002753 // Didn't find anything we could use.
2754 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2755 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
Richard Smithb8b41d32013-10-07 19:57:58 +00002756 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
2757 << (AllowTemplate || AllowStringTemplate);
Richard Smithbcc22fc2012-03-09 08:00:36 +00002758 return LOLR_Error;
2759}
2760
John McCall8fe68082010-01-26 07:16:45 +00002761void ADLResult::insert(NamedDecl *New) {
2762 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2763
2764 // If we haven't yet seen a decl for this key, or the last decl
2765 // was exactly this one, we're done.
2766 if (Old == 0 || Old == New) {
2767 Old = New;
2768 return;
2769 }
2770
2771 // Otherwise, decide which is a more recent redeclaration.
Alp Tokera2794f92014-01-22 07:29:52 +00002772 FunctionDecl *OldFD = Old->getAsFunction();
2773 FunctionDecl *NewFD = New->getAsFunction();
John McCall8fe68082010-01-26 07:16:45 +00002774
2775 FunctionDecl *Cursor = NewFD;
2776 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002777 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00002778
2779 // If we got to the end without finding OldFD, OldFD is the newer
2780 // declaration; leave things as they are.
2781 if (!Cursor) return;
2782
2783 // If we do find OldFD, then NewFD is newer.
2784 if (Cursor == OldFD) break;
2785
2786 // Otherwise, keep looking.
2787 }
2788
2789 Old = New;
2790}
2791
Richard Smith100b24a2014-04-17 01:52:14 +00002792void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
2793 ArrayRef<Expr *> Args, ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002794 // Find all of the associated namespaces and classes based on the
2795 // arguments we have.
2796 AssociatedNamespaceSet AssociatedNamespaces;
2797 AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00002798 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCallc7e8e792009-08-07 22:18:02 +00002799 AssociatedNamespaces,
2800 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002801
2802 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002803 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2804 // and let Y be the lookup set produced by argument dependent
2805 // lookup (defined as follows). If X contains [...] then Y is
2806 // empty. Otherwise Y is the set of declarations found in the
2807 // namespaces associated with the argument types as described
2808 // below. The set of declarations found by the lookup of the name
2809 // is the union of X and Y.
2810 //
2811 // Here, we compute Y and add its members to the overloaded
2812 // candidate set.
2813 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00002814 NSEnd = AssociatedNamespaces.end();
2815 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002816 // When considering an associated namespace, the lookup is the
2817 // same as the lookup performed when the associated namespace is
2818 // used as a qualifier (3.4.3.2) except that:
2819 //
2820 // -- Any using-directives in the associated namespace are
2821 // ignored.
2822 //
John McCallc7e8e792009-08-07 22:18:02 +00002823 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002824 // associated classes are visible within their respective
2825 // namespaces even if they are not visible during an ordinary
2826 // lookup (11.4).
David Blaikieff7d47a2012-12-19 00:45:41 +00002827 DeclContext::lookup_result R = (*NS)->lookup(Name);
2828 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
2829 ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00002830 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00002831 // If the only declaration here is an ordinary friend, consider
2832 // it only if it was declared in an associated classes.
Richard Smith541b38b2013-09-20 01:15:31 +00002833 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) {
2834 // If it's neither ordinarily visible nor a friend, we can't find it.
2835 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0)
2836 continue;
2837
Richard Smith64017682013-07-17 23:53:16 +00002838 bool DeclaredInAssociatedClass = false;
2839 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
2840 DeclContext *LexDC = DI->getLexicalDeclContext();
2841 if (isa<CXXRecordDecl>(LexDC) &&
2842 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) {
2843 DeclaredInAssociatedClass = true;
2844 break;
2845 }
2846 }
2847 if (!DeclaredInAssociatedClass)
John McCalld1e9d832009-08-11 06:59:38 +00002848 continue;
2849 }
Mike Stump11289f42009-09-09 15:08:12 +00002850
John McCall91f61fc2010-01-26 06:04:06 +00002851 if (isa<UsingShadowDecl>(D))
2852 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002853
Richard Smith100b24a2014-04-17 01:52:14 +00002854 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D))
John McCall8fe68082010-01-26 07:16:45 +00002855 continue;
2856
2857 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002858 }
2859 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002860}
Douglas Gregor2d435302009-12-30 17:04:44 +00002861
2862//----------------------------------------------------------------------------
2863// Search for all visible declarations.
2864//----------------------------------------------------------------------------
2865VisibleDeclConsumer::~VisibleDeclConsumer() { }
2866
Richard Smithe156254d2013-08-20 20:35:18 +00002867bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
2868
Douglas Gregor2d435302009-12-30 17:04:44 +00002869namespace {
2870
2871class ShadowContextRAII;
2872
2873class VisibleDeclsRecord {
2874public:
2875 /// \brief An entry in the shadow map, which is optimized to store a
2876 /// single declaration (the common case) but can also store a list
2877 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002878 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00002879
2880private:
2881 /// \brief A mapping from declaration names to the declarations that have
2882 /// this name within a particular scope.
2883 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2884
2885 /// \brief A list of shadow maps, which is used to model name hiding.
2886 std::list<ShadowMap> ShadowMaps;
2887
2888 /// \brief The declaration contexts we have already visited.
2889 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2890
2891 friend class ShadowContextRAII;
2892
2893public:
2894 /// \brief Determine whether we have already visited this context
2895 /// (and, if not, note that we are going to visit that context now).
2896 bool visitedContext(DeclContext *Ctx) {
2897 return !VisitedContexts.insert(Ctx);
2898 }
2899
Douglas Gregor39982192010-08-15 06:18:01 +00002900 bool alreadyVisitedContext(DeclContext *Ctx) {
2901 return VisitedContexts.count(Ctx);
2902 }
2903
Douglas Gregor2d435302009-12-30 17:04:44 +00002904 /// \brief Determine whether the given declaration is hidden in the
2905 /// current scope.
2906 ///
2907 /// \returns the declaration that hides the given declaration, or
2908 /// NULL if no such declaration exists.
2909 NamedDecl *checkHidden(NamedDecl *ND);
2910
2911 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002912 void add(NamedDecl *ND) {
2913 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2914 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002915};
2916
2917/// \brief RAII object that records when we've entered a shadow context.
2918class ShadowContextRAII {
2919 VisibleDeclsRecord &Visible;
2920
2921 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2922
2923public:
2924 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2925 Visible.ShadowMaps.push_back(ShadowMap());
2926 }
2927
2928 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00002929 Visible.ShadowMaps.pop_back();
2930 }
2931};
2932
2933} // end anonymous namespace
2934
Douglas Gregor2d435302009-12-30 17:04:44 +00002935NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002936 // Look through using declarations.
2937 ND = ND->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002938
Douglas Gregor2d435302009-12-30 17:04:44 +00002939 unsigned IDNS = ND->getIdentifierNamespace();
2940 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2941 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2942 SM != SMEnd; ++SM) {
2943 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2944 if (Pos == SM->end())
2945 continue;
2946
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002947 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor2d435302009-12-30 17:04:44 +00002948 IEnd = Pos->second.end();
2949 I != IEnd; ++I) {
2950 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +00002951 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002952 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00002953 Decl::IDNS_ObjCProtocol)))
2954 continue;
2955
2956 // Protocols are in distinct namespaces from everything else.
2957 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2958 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2959 (*I)->getIdentifierNamespace() != IDNS)
2960 continue;
2961
Douglas Gregor09bbc652010-01-14 15:47:35 +00002962 // Functions and function templates in the same scope overload
2963 // rather than hide. FIXME: Look for hiding based on function
2964 // signatures!
Alp Tokera2794f92014-01-22 07:29:52 +00002965 if ((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
2966 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002967 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002968 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002969
Douglas Gregor2d435302009-12-30 17:04:44 +00002970 // We've found a declaration that hides this one.
2971 return *I;
2972 }
2973 }
2974
2975 return 0;
2976}
2977
2978static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2979 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002980 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002981 VisibleDeclConsumer &Consumer,
2982 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002983 if (!Ctx)
2984 return;
2985
Douglas Gregor2d435302009-12-30 17:04:44 +00002986 // Make sure we don't visit the same context twice.
2987 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2988 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002989
Douglas Gregor7454c562010-07-02 20:37:36 +00002990 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2991 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2992
Douglas Gregor2d435302009-12-30 17:04:44 +00002993 // Enumerate all of the results in this context.
Aaron Ballman576114e2014-03-14 15:28:49 +00002994 for (const auto &R : Ctx->lookups()) {
2995 for (auto *I : R) {
2996 if (NamedDecl *ND = dyn_cast<NamedDecl>(I)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00002997 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00002998 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002999 Visited.add(ND);
3000 }
Douglas Gregora3b23b02010-12-09 21:44:02 +00003001 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003002 }
3003 }
3004
3005 // Traverse using directives for qualified name lookup.
3006 if (QualifiedNameLookup) {
3007 ShadowContextRAII Shadow(Visited);
Aaron Ballman804a7fb2014-03-17 17:14:12 +00003008 for (auto I : Ctx->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00003009 LookupVisibleDecls(I->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003010 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003011 }
3012 }
3013
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003014 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00003015 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00003016 if (!Record->hasDefinition())
3017 return;
3018
Aaron Ballman574705e2014-03-13 15:41:46 +00003019 for (const auto &B : Record->bases()) {
3020 QualType BaseType = B.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003021
Douglas Gregor2d435302009-12-30 17:04:44 +00003022 // Don't look into dependent bases, because name lookup can't look
3023 // there anyway.
3024 if (BaseType->isDependentType())
3025 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003026
Douglas Gregor2d435302009-12-30 17:04:44 +00003027 const RecordType *Record = BaseType->getAs<RecordType>();
3028 if (!Record)
3029 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003030
Douglas Gregor2d435302009-12-30 17:04:44 +00003031 // FIXME: It would be nice to be able to determine whether referencing
3032 // a particular member would be ambiguous. For example, given
3033 //
3034 // struct A { int member; };
3035 // struct B { int member; };
3036 // struct C : A, B { };
3037 //
3038 // void f(C *c) { c->### }
3039 //
3040 // accessing 'member' would result in an ambiguity. However, we
3041 // could be smart enough to qualify the member with the base
3042 // class, e.g.,
3043 //
3044 // c->B::member
3045 //
3046 // or
3047 //
3048 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003049
Douglas Gregor2d435302009-12-30 17:04:44 +00003050 // Find results in this base class (and its bases).
3051 ShadowContextRAII Shadow(Visited);
3052 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003053 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003054 }
3055 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003056
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003057 // Traverse the contexts of Objective-C classes.
3058 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3059 // Traverse categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003060 for (auto *Cat : IFace->visible_categories()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003061 ShadowContextRAII Shadow(Visited);
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003062 LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003063 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003064 }
3065
3066 // Traverse protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003067 for (auto *I : IFace->all_referenced_protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003068 ShadowContextRAII Shadow(Visited);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003069 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003070 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003071 }
3072
3073 // Traverse the superclass.
3074 if (IFace->getSuperClass()) {
3075 ShadowContextRAII Shadow(Visited);
3076 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003077 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003078 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003079
Douglas Gregor0b59e802010-04-19 18:02:19 +00003080 // If there is an implementation, traverse it. We do this to find
3081 // synthesized ivars.
3082 if (IFace->getImplementation()) {
3083 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003084 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky13668f22012-04-03 20:26:45 +00003085 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor0b59e802010-04-19 18:02:19 +00003086 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003087 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003088 for (auto *I : Protocol->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003089 ShadowContextRAII Shadow(Visited);
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003090 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003091 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003092 }
3093 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003094 for (auto *I : Category->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003095 ShadowContextRAII Shadow(Visited);
Aaron Ballman19a41762014-03-14 12:55:57 +00003096 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003097 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003098 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003099
Douglas Gregor0b59e802010-04-19 18:02:19 +00003100 // If there is an implementation, traverse it.
3101 if (Category->getImplementation()) {
3102 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003103 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00003104 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003105 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003106 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003107}
3108
3109static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3110 UnqualUsingDirectiveSet &UDirs,
3111 VisibleDeclConsumer &Consumer,
3112 VisibleDeclsRecord &Visited) {
3113 if (!S)
3114 return;
3115
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003116 if (!S->getEntity() ||
3117 (!S->getParent() &&
Ted Kremenekc37877d2013-10-08 17:08:03 +00003118 !Visited.alreadyVisitedContext(S->getEntity())) ||
3119 (S->getEntity())->isFunctionOrMethod()) {
Richard Smith541b38b2013-09-20 01:15:31 +00003120 FindLocalExternScope FindLocals(Result);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003121 // Walk through the declarations in this Scope.
Aaron Ballman35c54952014-03-17 16:55:25 +00003122 for (auto *D : S->decls()) {
3123 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Douglas Gregor4a814562011-12-14 16:03:29 +00003124 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003125 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003126 Visited.add(ND);
3127 }
3128 }
3129 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003130
Douglas Gregor66230062010-03-15 14:33:29 +00003131 // FIXME: C++ [temp.local]p8
Douglas Gregor2d435302009-12-30 17:04:44 +00003132 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00003133 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003134 // Look into this scope's declaration context, along with any of its
3135 // parent lookup contexts (e.g., enclosing classes), up to the point
3136 // where we hit the context stored in the next outer scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00003137 Entity = S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00003138 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003139
Douglas Gregorea166062010-03-15 15:26:48 +00003140 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00003141 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003142 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3143 if (Method->isInstanceMethod()) {
3144 // For instance methods, look for ivars in the method's interface.
3145 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3146 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003147 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003148 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Richard Smithe156254d2013-08-20 20:35:18 +00003149 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003150 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003151 }
3152
3153 // We've already performed all of the name lookup that we need
3154 // to for Objective-C methods; the next context will be the
3155 // outer scope.
3156 break;
3157 }
3158
Douglas Gregor2d435302009-12-30 17:04:44 +00003159 if (Ctx->isFunctionOrMethod())
3160 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003161
3162 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003163 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003164 }
3165 } else if (!S->getParent()) {
3166 // Look into the translation unit scope. We walk through the translation
3167 // unit's declaration context, because the Scope itself won't have all of
3168 // the declarations if we loaded a precompiled header.
3169 // FIXME: We would like the translation unit's Scope object to point to the
3170 // translation unit, so we don't need this special "if" branch. However,
3171 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003172 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00003173 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003174 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00003175 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003176 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003177 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003178 }
3179
Douglas Gregor2d435302009-12-30 17:04:44 +00003180 if (Entity) {
3181 // Lookup visible declarations in any namespaces found by using
3182 // directives.
3183 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003184 std::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
Douglas Gregor2d435302009-12-30 17:04:44 +00003185 for (; UI != UEnd; ++UI)
3186 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003187 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003188 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003189 }
3190
3191 // Lookup names in the parent scope.
3192 ShadowContextRAII Shadow(Visited);
3193 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3194}
3195
3196void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003197 VisibleDeclConsumer &Consumer,
3198 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003199 // Determine the set of using directives available during
3200 // unqualified name lookup.
3201 Scope *Initial = S;
3202 UnqualUsingDirectiveSet UDirs;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003203 if (getLangOpts().CPlusPlus) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003204 // Find the first namespace or translation-unit scope.
3205 while (S && !isNamespaceOrTranslationUnitScope(S))
3206 S = S->getParent();
3207
3208 UDirs.visitScopeChain(Initial, S);
3209 }
3210 UDirs.done();
3211
3212 // Look for visible declarations.
3213 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003214 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003215 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003216 if (!IncludeGlobalScope)
3217 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003218 ShadowContextRAII Shadow(Visited);
3219 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3220}
3221
3222void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003223 VisibleDeclConsumer &Consumer,
3224 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003225 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003226 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003227 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003228 if (!IncludeGlobalScope)
3229 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003230 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003231 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003232 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003233}
3234
Chris Lattner43e7f312011-02-18 02:08:43 +00003235/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003236/// If GnuLabelLoc is a valid source location, then this is a definition
3237/// of an __label__ label name, otherwise it is a normal label definition
3238/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003239LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003240 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003241 // Do a lookup to see if we have a label with this name already.
Chris Lattner43e7f312011-02-18 02:08:43 +00003242 NamedDecl *Res = 0;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003243
3244 if (GnuLabelLoc.isValid()) {
3245 // Local label definitions always shadow existing labels.
3246 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3247 Scope *S = CurScope;
3248 PushOnScopeChains(Res, S, true);
3249 return cast<LabelDecl>(Res);
3250 }
3251
3252 // Not a GNU local label.
3253 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3254 // If we found a label, check to see if it is in the same context as us.
3255 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003256 if (Res && Res->getDeclContext() != CurContext)
3257 Res = 0;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003258 if (Res == 0) {
3259 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003260 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3261 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003262 assert(S && "Not in a function?");
3263 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003264 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003265 return cast<LabelDecl>(Res);
3266}
3267
3268//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003269// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003270//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003271
3272namespace {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003273
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003274typedef SmallVector<TypoCorrection, 1> TypoResultList;
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003275typedef llvm::StringMap<TypoResultList, llvm::BumpPtrAllocator> TypoResultsMap;
Benjamin Kramer73faad62012-04-14 08:26:28 +00003276typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003277
3278static const unsigned MaxTypoDistanceResultSets = 5;
3279
Douglas Gregor2d435302009-12-30 17:04:44 +00003280class TypoCorrectionConsumer : public VisibleDeclConsumer {
3281 /// \brief The name written that is a typo in the source.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003282 StringRef Typo;
Douglas Gregor2d435302009-12-30 17:04:44 +00003283
3284 /// \brief The results found that have the smallest edit distance
3285 /// found (so far) with the typo name.
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003286 ///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003287 /// The pointer value being set to the current DeclContext indicates
3288 /// whether there is a keyword with this name.
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003289 TypoEditDistanceMap CorrectionResults;
Douglas Gregor2d435302009-12-30 17:04:44 +00003290
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003291 Sema &SemaRef;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003292
Douglas Gregor2d435302009-12-30 17:04:44 +00003293public:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003294 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003295 : Typo(Typo->getName()),
Richard Smithe156254d2013-08-20 20:35:18 +00003296 SemaRef(SemaRef) {}
3297
Craig Toppere14c0f82014-03-12 04:55:44 +00003298 bool includeHiddenDecls() const override { return true; }
Douglas Gregor2d435302009-12-30 17:04:44 +00003299
Craig Toppere14c0f82014-03-12 04:55:44 +00003300 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3301 bool InBaseClass) override;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003302 void FoundName(StringRef Name);
3303 void addKeywordResult(StringRef Keyword);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003304 void addName(StringRef Name, NamedDecl *ND, NestedNameSpecifier *NNS = NULL,
3305 bool isKeyword = false);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003306 void addCorrection(TypoCorrection Correction);
Douglas Gregor2d435302009-12-30 17:04:44 +00003307
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003308 typedef TypoResultsMap::iterator result_iterator;
3309 typedef TypoEditDistanceMap::iterator distance_iterator;
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003310 distance_iterator begin() { return CorrectionResults.begin(); }
3311 distance_iterator end() { return CorrectionResults.end(); }
3312 void erase(distance_iterator I) { CorrectionResults.erase(I); }
3313 unsigned size() const { return CorrectionResults.size(); }
3314 bool empty() const { return CorrectionResults.empty(); }
Douglas Gregor2d435302009-12-30 17:04:44 +00003315
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003316 TypoResultList &operator[](StringRef Name) {
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003317 return CorrectionResults.begin()->second[Name];
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003318 }
3319
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003320 unsigned getBestEditDistance(bool Normalized) {
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003321 if (CorrectionResults.empty())
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003322 return (std::numeric_limits<unsigned>::max)();
3323
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003324 unsigned BestED = CorrectionResults.begin()->first;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003325 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003326 }
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003327
3328 TypoResultsMap &getBestResults() {
3329 return CorrectionResults.begin()->second;
3330 }
3331
Douglas Gregor2d435302009-12-30 17:04:44 +00003332};
3333
3334}
3335
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003336void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003337 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003338 // Don't consider hidden names for typo correction.
3339 if (Hiding)
3340 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003341
Douglas Gregor2d435302009-12-30 17:04:44 +00003342 // Only consider entities with identifiers for names, ignoring
3343 // special names (constructors, overloaded operators, selectors,
3344 // etc.).
3345 IdentifierInfo *Name = ND->getIdentifier();
3346 if (!Name)
3347 return;
3348
Richard Smithe156254d2013-08-20 20:35:18 +00003349 // Only consider visible declarations and declarations from modules with
3350 // names that exactly match.
3351 if (!LookupResult::isVisible(SemaRef, ND) && Name->getName() != Typo &&
3352 !findAcceptableDecl(SemaRef, ND))
3353 return;
3354
Douglas Gregor57756ea2010-10-14 22:11:03 +00003355 FoundName(Name->getName());
3356}
3357
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003358void TypoCorrectionConsumer::FoundName(StringRef Name) {
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003359 // Compute the edit distance between the typo and the name of this
3360 // entity, and add the identifier to the list of results.
3361 addName(Name, NULL);
3362}
3363
3364void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3365 // Compute the edit distance between the typo and this keyword,
3366 // and add the keyword to the list of results.
3367 addName(Keyword, NULL, NULL, true);
3368}
3369
3370void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
3371 NestedNameSpecifier *NNS, bool isKeyword) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003372 // Use a simple length-based heuristic to determine the minimum possible
3373 // edit distance. If the minimum isn't good enough, bail out early.
3374 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003375 if (MinED && Typo.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00003376 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003377
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003378 // Compute an upper bound on the allowable edit distance, so that the
3379 // edit-distance algorithm can short-circuit.
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003380 unsigned UpperBound = (Typo.size() + 2) / 3 + 1;
3381 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
3382 if (ED >= UpperBound) return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003383
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003384 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003385 if (isKeyword) TC.makeKeyword();
3386 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003387}
3388
3389void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003390 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003391 TypoResultList &CList =
3392 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003393
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003394 if (!CList.empty() && !CList.back().isResolved())
3395 CList.pop_back();
3396 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3397 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3398 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3399 RI != RIEnd; ++RI) {
3400 // If the Correction refers to a decl already in the result list,
3401 // replace the existing result if the string representation of Correction
3402 // comes before the current result alphabetically, then stop as there is
3403 // nothing more to be done to add Correction to the candidate set.
3404 if (RI->getCorrectionDecl() == NewND) {
3405 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3406 *RI = Correction;
3407 return;
3408 }
3409 }
3410 }
3411 if (CList.empty() || Correction.isResolved())
3412 CList.push_back(Correction);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003413
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003414 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
Benjamin Kramer167e9992014-03-02 12:20:24 +00003415 erase(std::prev(CorrectionResults.end()));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003416}
3417
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003418// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3419// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3420// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3421static void getNestedNameSpecifierIdentifiers(
3422 NestedNameSpecifier *NNS,
3423 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3424 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3425 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3426 else
3427 Identifiers.clear();
3428
3429 const IdentifierInfo *II = NULL;
3430
3431 switch (NNS->getKind()) {
3432 case NestedNameSpecifier::Identifier:
3433 II = NNS->getAsIdentifier();
3434 break;
3435
3436 case NestedNameSpecifier::Namespace:
3437 if (NNS->getAsNamespace()->isAnonymousNamespace())
3438 return;
3439 II = NNS->getAsNamespace()->getIdentifier();
3440 break;
3441
3442 case NestedNameSpecifier::NamespaceAlias:
3443 II = NNS->getAsNamespaceAlias()->getIdentifier();
3444 break;
3445
3446 case NestedNameSpecifier::TypeSpecWithTemplate:
3447 case NestedNameSpecifier::TypeSpec:
3448 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3449 break;
3450
3451 case NestedNameSpecifier::Global:
3452 return;
3453 }
3454
3455 if (II)
3456 Identifiers.push_back(II);
3457}
3458
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003459namespace {
3460
3461class SpecifierInfo {
3462 public:
3463 DeclContext* DeclCtx;
3464 NestedNameSpecifier* NameSpecifier;
3465 unsigned EditDistance;
3466
3467 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3468 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3469};
3470
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003471typedef SmallVector<DeclContext*, 4> DeclContextList;
3472typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003473
3474class NamespaceSpecifierSet {
3475 ASTContext &Context;
3476 DeclContextList CurContextChain;
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003477 std::string CurNameSpecifier;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003478 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3479 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003480 bool isSorted;
3481
3482 SpecifierInfoList Specifiers;
3483 llvm::SmallSetVector<unsigned, 4> Distances;
3484 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3485
3486 /// \brief Helper for building the list of DeclContexts between the current
3487 /// context and the top of the translation unit
3488 static DeclContextList BuildContextChain(DeclContext *Start);
3489
3490 void SortNamespaces();
3491
3492 public:
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003493 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3494 CXXScopeSpec *CurScopeSpec)
Benjamin Kramerde1d6232011-07-05 09:46:31 +00003495 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
Kaelyn Uhrain52dd02d2013-06-24 17:49:03 +00003496 isSorted(false) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003497 if (NestedNameSpecifier *NNS =
3498 CurScopeSpec ? CurScopeSpec->getScopeRep() : 0) {
3499 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
3500 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3501
3502 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
3503 }
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003504 // Build the list of identifiers that would be used for an absolute
Benjamin Kramer474261a2012-06-02 10:20:41 +00003505 // (from the global context) NestedNameSpecifier referring to the current
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003506 // context.
3507 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3508 CEnd = CurContextChain.rend();
3509 C != CEnd; ++C) {
3510 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3511 CurContextIdentifiers.push_back(ND->getIdentifier());
3512 }
Kaelyn Uhrain52dd02d2013-06-24 17:49:03 +00003513
3514 // Add the global context as a NestedNameSpecifier
3515 Distances.insert(1);
3516 DistanceMap[1].push_back(
3517 SpecifierInfo(cast<DeclContext>(Context.getTranslationUnitDecl()),
3518 NestedNameSpecifier::GlobalSpecifier(Context), 1));
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003519 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003520
Kaelyn Uhrain5315a462013-10-19 00:04:49 +00003521 /// \brief Add the DeclContext (a namespace or record) to the set, computing
3522 /// the corresponding NestedNameSpecifier and its distance in the process.
3523 void AddNameSpecifier(DeclContext *Ctx);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003524
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003525 typedef SpecifierInfoList::iterator iterator;
3526 iterator begin() {
3527 if (!isSorted) SortNamespaces();
3528 return Specifiers.begin();
3529 }
3530 iterator end() { return Specifiers.end(); }
3531};
3532
3533}
3534
3535DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Nick Lewycky0d9b3192013-04-08 21:55:21 +00003536 assert(Start && "Building a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003537 DeclContextList Chain;
3538 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3539 DC = DC->getLookupParent()) {
3540 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3541 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3542 !(ND && ND->isAnonymousNamespace()))
3543 Chain.push_back(DC->getPrimaryContext());
3544 }
3545 return Chain;
3546}
3547
3548void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003549 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003550 sortedDistances.append(Distances.begin(), Distances.end());
3551
3552 if (sortedDistances.size() > 1)
3553 std::sort(sortedDistances.begin(), sortedDistances.end());
3554
3555 Specifiers.clear();
Craig Topper2341c0d2013-07-04 03:08:24 +00003556 for (SmallVectorImpl<unsigned>::iterator DI = sortedDistances.begin(),
3557 DIEnd = sortedDistances.end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003558 DI != DIEnd; ++DI) {
3559 SpecifierInfoList &SpecList = DistanceMap[*DI];
3560 Specifiers.append(SpecList.begin(), SpecList.end());
3561 }
3562
3563 isSorted = true;
3564}
3565
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003566static unsigned BuildNestedNameSpecifier(ASTContext &Context,
3567 DeclContextList &DeclChain,
3568 NestedNameSpecifier *&NNS) {
3569 unsigned NumSpecifiers = 0;
3570 for (DeclContextList::reverse_iterator C = DeclChain.rbegin(),
3571 CEnd = DeclChain.rend();
3572 C != CEnd; ++C) {
3573 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) {
3574 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3575 ++NumSpecifiers;
3576 } else if (RecordDecl *RD = dyn_cast_or_null<RecordDecl>(*C)) {
3577 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
3578 RD->getTypeForDecl());
3579 ++NumSpecifiers;
3580 }
3581 }
3582 return NumSpecifiers;
3583}
3584
Kaelyn Uhrain5315a462013-10-19 00:04:49 +00003585void NamespaceSpecifierSet::AddNameSpecifier(DeclContext *Ctx) {
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003586 NestedNameSpecifier *NNS = NULL;
3587 unsigned NumSpecifiers = 0;
3588 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
3589 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
3590
3591 // Eliminate common elements from the two DeclContext chains.
3592 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3593 CEnd = CurContextChain.rend();
3594 C != CEnd && !NamespaceDeclChain.empty() &&
3595 NamespaceDeclChain.back() == *C; ++C) {
3596 NamespaceDeclChain.pop_back();
3597 }
3598
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003599 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3600 NumSpecifiers = BuildNestedNameSpecifier(Context, NamespaceDeclChain, NNS);
3601
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003602 // Add an explicit leading '::' specifier if needed.
3603 if (NamespaceDeclChain.empty()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003604 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003605 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003606 NumSpecifiers =
3607 BuildNestedNameSpecifier(Context, FullNamespaceDeclChain, NNS);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003608 } else if (NamedDecl *ND =
3609 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003610 IdentifierInfo *Name = ND->getIdentifier();
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003611 bool SameNameSpecifier = false;
3612 if (std::find(CurNameSpecifierIdentifiers.begin(),
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003613 CurNameSpecifierIdentifiers.end(),
3614 Name) != CurNameSpecifierIdentifiers.end()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003615 std::string NewNameSpecifier;
3616 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
3617 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
3618 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3619 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3620 SpecifierOStream.flush();
3621 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003622 }
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003623 if (SameNameSpecifier ||
3624 std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3625 Name) != CurContextIdentifiers.end()) {
3626 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
3627 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3628 NumSpecifiers =
3629 BuildNestedNameSpecifier(Context, FullNamespaceDeclChain, NNS);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003630 }
3631 }
3632
3633 // If the built NestedNameSpecifier would be replacing an existing
3634 // NestedNameSpecifier, use the number of component identifiers that
3635 // would need to be changed as the edit distance instead of the number
3636 // of components in the built NestedNameSpecifier.
3637 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3638 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3639 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3640 NumSpecifiers = llvm::ComputeEditDistance(
3641 ArrayRef<const IdentifierInfo *>(CurNameSpecifierIdentifiers),
3642 ArrayRef<const IdentifierInfo *>(NewNameSpecifierIdentifiers));
3643 }
3644
3645 isSorted = false;
3646 Distances.insert(NumSpecifiers);
3647 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
3648}
3649
Douglas Gregord507d772010-10-20 03:06:34 +00003650/// \brief Perform name lookup for a possible result for typo correction.
3651static void LookupPotentialTypoResult(Sema &SemaRef,
3652 LookupResult &Res,
3653 IdentifierInfo *Name,
3654 Scope *S, CXXScopeSpec *SS,
3655 DeclContext *MemberContext,
3656 bool EnteringContext,
Richard Smithe156254d2013-08-20 20:35:18 +00003657 bool isObjCIvarLookup,
3658 bool FindHidden) {
Douglas Gregord507d772010-10-20 03:06:34 +00003659 Res.suppressDiagnostics();
3660 Res.clear();
3661 Res.setLookupName(Name);
Richard Smithe156254d2013-08-20 20:35:18 +00003662 Res.setAllowHidden(FindHidden);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003663 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00003664 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003665 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00003666 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3667 Res.addDecl(Ivar);
3668 Res.resolveKind();
3669 return;
3670 }
3671 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003672
Douglas Gregord507d772010-10-20 03:06:34 +00003673 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3674 Res.addDecl(Prop);
3675 Res.resolveKind();
3676 return;
3677 }
3678 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003679
Douglas Gregord507d772010-10-20 03:06:34 +00003680 SemaRef.LookupQualifiedName(Res, MemberContext);
3681 return;
3682 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003683
3684 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00003685 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003686
Douglas Gregord507d772010-10-20 03:06:34 +00003687 // Fake ivar lookup; this should really be part of
3688 // LookupParsedName.
3689 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3690 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003691 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00003692 (Res.isSingleResult() &&
3693 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003694 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00003695 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3696 Res.addDecl(IV);
3697 Res.resolveKind();
3698 }
3699 }
3700 }
3701}
3702
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003703/// \brief Add keywords to the consumer as possible typo corrections.
3704static void AddKeywordsToConsumer(Sema &SemaRef,
3705 TypoCorrectionConsumer &Consumer,
Richard Smithb3a1df02012-06-08 21:35:42 +00003706 Scope *S, CorrectionCandidateCallback &CCC,
3707 bool AfterNestedNameSpecifier) {
3708 if (AfterNestedNameSpecifier) {
3709 // For 'X::', we know exactly which keywords can appear next.
3710 Consumer.addKeywordResult("template");
3711 if (CCC.WantExpressionKeywords)
3712 Consumer.addKeywordResult("operator");
3713 return;
3714 }
3715
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003716 if (CCC.WantObjCSuper)
3717 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003718
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003719 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003720 // Add type-specifier keywords to the set of results.
Craig Topperd6d31ac2013-07-15 08:24:27 +00003721 static const char *const CTypeSpecs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003722 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00003723 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003724 "_Complex", "_Imaginary",
3725 // storage-specifiers as well
3726 "extern", "inline", "static", "typedef"
3727 };
3728
Craig Toppere5ce8312013-07-15 03:38:40 +00003729 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003730 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3731 Consumer.addKeywordResult(CTypeSpecs[I]);
3732
David Blaikiebbafb8a2012-03-11 07:00:24 +00003733 if (SemaRef.getLangOpts().C99)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003734 Consumer.addKeywordResult("restrict");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003735 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003736 Consumer.addKeywordResult("bool");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003737 else if (SemaRef.getLangOpts().C99)
Douglas Gregor3b22a882011-07-01 21:27:45 +00003738 Consumer.addKeywordResult("_Bool");
3739
David Blaikiebbafb8a2012-03-11 07:00:24 +00003740 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003741 Consumer.addKeywordResult("class");
3742 Consumer.addKeywordResult("typename");
3743 Consumer.addKeywordResult("wchar_t");
3744
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003745 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003746 Consumer.addKeywordResult("char16_t");
3747 Consumer.addKeywordResult("char32_t");
3748 Consumer.addKeywordResult("constexpr");
3749 Consumer.addKeywordResult("decltype");
3750 Consumer.addKeywordResult("thread_local");
3751 }
3752 }
3753
David Blaikiebbafb8a2012-03-11 07:00:24 +00003754 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003755 Consumer.addKeywordResult("typeof");
3756 }
3757
David Blaikiebbafb8a2012-03-11 07:00:24 +00003758 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003759 Consumer.addKeywordResult("const_cast");
3760 Consumer.addKeywordResult("dynamic_cast");
3761 Consumer.addKeywordResult("reinterpret_cast");
3762 Consumer.addKeywordResult("static_cast");
3763 }
3764
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003765 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003766 Consumer.addKeywordResult("sizeof");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003767 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003768 Consumer.addKeywordResult("false");
3769 Consumer.addKeywordResult("true");
3770 }
3771
David Blaikiebbafb8a2012-03-11 07:00:24 +00003772 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topperd6d31ac2013-07-15 08:24:27 +00003773 static const char *const CXXExprs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003774 "delete", "new", "operator", "throw", "typeid"
3775 };
Craig Toppere5ce8312013-07-15 03:38:40 +00003776 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003777 for (unsigned I = 0; I != NumCXXExprs; ++I)
3778 Consumer.addKeywordResult(CXXExprs[I]);
3779
3780 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3781 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3782 Consumer.addKeywordResult("this");
3783
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003784 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003785 Consumer.addKeywordResult("alignof");
3786 Consumer.addKeywordResult("nullptr");
3787 }
3788 }
Jordan Rose58d54722012-06-30 21:33:57 +00003789
3790 if (SemaRef.getLangOpts().C11) {
3791 // FIXME: We should not suggest _Alignof if the alignof macro
3792 // is present.
3793 Consumer.addKeywordResult("_Alignof");
3794 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003795 }
3796
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003797 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003798 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3799 // Statements.
Craig Topperd6d31ac2013-07-15 08:24:27 +00003800 static const char *const CStmts[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003801 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Toppere5ce8312013-07-15 03:38:40 +00003802 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003803 for (unsigned I = 0; I != NumCStmts; ++I)
3804 Consumer.addKeywordResult(CStmts[I]);
3805
David Blaikiebbafb8a2012-03-11 07:00:24 +00003806 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003807 Consumer.addKeywordResult("catch");
3808 Consumer.addKeywordResult("try");
3809 }
3810
3811 if (S && S->getBreakParent())
3812 Consumer.addKeywordResult("break");
3813
3814 if (S && S->getContinueParent())
3815 Consumer.addKeywordResult("continue");
3816
3817 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3818 Consumer.addKeywordResult("case");
3819 Consumer.addKeywordResult("default");
3820 }
3821 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003822 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003823 Consumer.addKeywordResult("namespace");
3824 Consumer.addKeywordResult("template");
3825 }
3826
3827 if (S && S->isClassScope()) {
3828 Consumer.addKeywordResult("explicit");
3829 Consumer.addKeywordResult("friend");
3830 Consumer.addKeywordResult("mutable");
3831 Consumer.addKeywordResult("private");
3832 Consumer.addKeywordResult("protected");
3833 Consumer.addKeywordResult("public");
3834 Consumer.addKeywordResult("virtual");
3835 }
3836 }
3837
David Blaikiebbafb8a2012-03-11 07:00:24 +00003838 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003839 Consumer.addKeywordResult("using");
3840
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003841 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003842 Consumer.addKeywordResult("static_assert");
3843 }
3844 }
3845}
3846
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003847static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3848 TypoCorrection &Candidate) {
3849 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3850 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3851}
3852
Richard Smithe156254d2013-08-20 20:35:18 +00003853/// \brief Check whether the declarations found for a typo correction are
3854/// visible, and if none of them are, convert the correction to an 'import
3855/// a module' correction.
3856static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC,
3857 DeclarationName TypoName) {
3858 if (TC.begin() == TC.end())
3859 return;
3860
3861 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3862
3863 for (/**/; DI != DE; ++DI)
3864 if (!LookupResult::isVisible(SemaRef, *DI))
3865 break;
3866 // Nothing to do if all decls are visible.
3867 if (DI == DE)
3868 return;
3869
3870 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3871 bool AnyVisibleDecls = !NewDecls.empty();
3872
3873 for (/**/; DI != DE; ++DI) {
3874 NamedDecl *VisibleDecl = *DI;
3875 if (!LookupResult::isVisible(SemaRef, *DI))
3876 VisibleDecl = findAcceptableDecl(SemaRef, *DI);
3877
3878 if (VisibleDecl) {
3879 if (!AnyVisibleDecls) {
3880 // Found a visible decl, discard all hidden ones.
3881 AnyVisibleDecls = true;
3882 NewDecls.clear();
3883 }
3884 NewDecls.push_back(VisibleDecl);
3885 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
3886 NewDecls.push_back(*DI);
3887 }
3888
3889 if (NewDecls.empty())
3890 TC = TypoCorrection();
3891 else {
3892 TC.setCorrectionDecls(NewDecls);
3893 TC.setRequiresImport(!AnyVisibleDecls);
3894 }
3895}
3896
Douglas Gregor2d435302009-12-30 17:04:44 +00003897/// \brief Try to "correct" a typo in the source code by finding
3898/// visible declarations whose names are similar to the name that was
3899/// present in the source code.
3900///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003901/// \param TypoName the \c DeclarationNameInfo structure that contains
3902/// the name that was present in the source code along with its location.
3903///
3904/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00003905///
3906/// \param S the scope in which name lookup occurs.
3907///
3908/// \param SS the nested-name-specifier that precedes the name we're
3909/// looking for, if present.
3910///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003911/// \param CCC A CorrectionCandidateCallback object that provides further
3912/// validation of typo correction candidates. It also provides flags for
3913/// determining the set of keywords permitted.
3914///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003915/// \param MemberContext if non-NULL, the context in which to look for
3916/// a member access expression.
3917///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003918/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00003919/// the nested-name-specifier SS.
3920///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003921/// \param OPT when non-NULL, the search for visible declarations will
3922/// also walk the protocols in the qualified interfaces of \p OPT.
3923///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003924/// \returns a \c TypoCorrection containing the corrected name if the typo
3925/// along with information such as the \c NamedDecl where the corrected name
3926/// was declared, and any additional \c NestedNameSpecifier needed to access
3927/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3928TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3929 Sema::LookupNameKind LookupKind,
3930 Scope *S, CXXScopeSpec *SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00003931 CorrectionCandidateCallback &CCC,
John Thompson2255f2c2014-04-23 12:57:01 +00003932 CorrectTypoKind Mode,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003933 DeclContext *MemberContext,
3934 bool EnteringContext,
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00003935 const ObjCObjectPointerType *OPT,
3936 bool RecordFailure) {
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00003937 // Always let the ExternalSource have the first chance at correction, even
3938 // if we would otherwise have given up.
3939 if (ExternalSource) {
3940 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
3941 TypoName, LookupKind, S, SS, CCC, MemberContext, EnteringContext, OPT))
3942 return Correction;
3943 }
3944
Richard Smith1fff95c2013-09-12 23:28:08 +00003945 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
3946 DisableTypoCorrection)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003947 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003948
Francois Pichet9c391132011-12-03 15:55:29 +00003949 // In Microsoft mode, don't perform typo correction in a template member
3950 // function dependent context because it interferes with the "lookup into
3951 // dependent bases of class templates" feature.
Alp Tokerbfa39342014-01-14 12:51:41 +00003952 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
Francois Pichet9c391132011-12-03 15:55:29 +00003953 isa<CXXMethodDecl>(CurContext))
3954 return TypoCorrection();
3955
Douglas Gregor2d435302009-12-30 17:04:44 +00003956 // We only attempt to correct typos for identifiers.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003957 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor2d435302009-12-30 17:04:44 +00003958 if (!Typo)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003959 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00003960
3961 // If the scope specifier itself was invalid, don't try to correct
3962 // typos.
3963 if (SS && SS->isInvalid())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003964 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00003965
3966 // Never try to correct typos during template deduction or
3967 // instantiation.
3968 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003969 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003970
Argyrios Kyrtzidis3e56dd42013-03-14 22:56:43 +00003971 // Don't try to correct 'super'.
3972 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
3973 return TypoCorrection();
3974
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00003975 // Abort if typo correction already failed for this specific typo.
3976 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
3977 if (locs != TypoCorrectionFailures.end() &&
Aaron Ballman7fc6e1b2013-10-05 19:56:07 +00003978 locs->second.count(TypoName.getLoc()))
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00003979 return TypoCorrection();
3980
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003981 // Don't try to correct the identifier "vector" when in AltiVec mode.
3982 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
3983 // remove this workaround.
3984 if (getLangOpts().AltiVec && Typo->isStr("vector"))
3985 return TypoCorrection();
3986
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003987 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003988
John Thompson2255f2c2014-04-23 12:57:01 +00003989 // Get the module loader (usually compiler instance).
3990 ModuleLoader &Loader = PP.getModuleLoader();
3991
3992 // Look for the symbol in non-imported modules, but only if an error
3993 // actually occurred.
3994 if ((Mode == CTK_ErrorRecovery) && !Loader.buildingModule() &&
3995 getLangOpts().Modules && getLangOpts().ModulesSearchAll) {
3996 // Load global module index, or retrieve a previously loaded one.
3997 GlobalModuleIndex *GlobalIndex = Loader.loadGlobalModuleIndex(
3998 TypoName.getLocStart());
3999
4000 // Only if we have a global index.
4001 if (GlobalIndex) {
4002 GlobalModuleIndex::HitSet FoundModules;
4003
4004 // Find the modules that reference the identifier.
4005 // Note that this only finds top-level modules.
4006 // We'll let diagnoseTypo find the actual declaration module.
4007 if (GlobalIndex->lookupIdentifier(Typo->getName(), FoundModules)) {
4008 TypoCorrection TC(TypoName.getName(), (NestedNameSpecifier *)0, 0);
4009 TC.setCorrectionRange(SS, TypoName);
4010 TC.setRequiresImport(true);
4011 }
4012 }
4013 }
4014
4015 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
4016
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00004017 // If a callback object considers an empty typo correction candidate to be
4018 // viable, assume it does not do any actual validation of the candidates.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004019 TypoCorrection EmptyCorrection;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00004020 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004021
Douglas Gregor280e1ee2010-04-14 20:04:41 +00004022 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor87074f12010-10-20 01:32:02 +00004023 bool IsUnqualifiedLookup = false;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004024 DeclContext *QualifiedDC = MemberContext;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004025 if (MemberContext) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004026 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004027
4028 // Look in qualified interfaces.
4029 if (OPT) {
Aaron Ballman83731462014-03-17 16:14:00 +00004030 for (auto *I : OPT->quals())
4031 LookupVisibleDecls(I, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004032 }
4033 } else if (SS && SS->isSet()) {
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004034 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4035 if (!QualifiedDC)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004036 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004037
Douglas Gregor87074f12010-10-20 01:32:02 +00004038 // Provide a stop gap for files that are just seriously broken. Trying
4039 // to correct all typos can turn into a HUGE performance penalty, causing
4040 // some files to take minutes to get rejected by the parser.
4041 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004042 return TypoCorrection();
Douglas Gregor87074f12010-10-20 01:32:02 +00004043 ++TyposCorrected;
4044
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004045 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
Douglas Gregor2d435302009-12-30 17:04:44 +00004046 } else {
Douglas Gregor87074f12010-10-20 01:32:02 +00004047 IsUnqualifiedLookup = true;
4048 UnqualifiedTyposCorrectedMap::iterator Cached
4049 = UnqualifiedTyposCorrected.find(Typo);
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004050 if (Cached != UnqualifiedTyposCorrected.end()) {
4051 // Add the cached value, unless it's a keyword or fails validation. In the
4052 // keyword case, we'll end up adding the keyword below.
4053 if (Cached->second) {
4054 if (!Cached->second.isKeyword() &&
Serge Pavlovc0cd80f2013-10-14 14:05:48 +00004055 isCandidateViable(CCC, Cached->second)) {
4056 // Do not use correction that is unaccessible in the given scope.
Serge Pavlove8ae13f2013-10-15 14:24:32 +00004057 NamedDecl *CorrectionDecl = Cached->second.getCorrectionDecl();
Serge Pavlovc0cd80f2013-10-14 14:05:48 +00004058 DeclarationNameInfo NameInfo(CorrectionDecl->getDeclName(),
4059 CorrectionDecl->getLocation());
4060 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4061 if (LookupName(R, S))
4062 Consumer.addCorrection(Cached->second);
4063 }
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004064 } else {
4065 // Only honor no-correction cache hits when a callback that will validate
4066 // correction candidates is not being used.
4067 if (!ValidatingCallback)
4068 return TypoCorrection();
4069 }
4070 }
4071 if (Cached == UnqualifiedTyposCorrected.end()) {
Douglas Gregor87074f12010-10-20 01:32:02 +00004072 // Provide a stop gap for files that are just seriously broken. Trying
4073 // to correct all typos can turn into a HUGE performance penalty, causing
4074 // some files to take minutes to get rejected by the parser.
4075 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004076 return TypoCorrection();
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004077 }
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004078 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004079
Douglas Gregorb11f9452012-03-26 16:54:18 +00004080 // Determine whether we are going to search in the various namespaces for
4081 // corrections.
4082 bool SearchNamespaces
Kaelyn Uhrainf4657d52012-04-03 18:20:11 +00004083 = getLangOpts().CPlusPlus &&
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00004084 (IsUnqualifiedLookup || (SS && SS->isSet()));
Richard Smithe156254d2013-08-20 20:35:18 +00004085 // In a few cases we *only* want to search for corrections based on just
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004086 // adding or changing the nested name specifier.
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004087 unsigned TypoLen = Typo->getName().size();
4088 bool AllowOnlyNNSChanges = TypoLen < 3;
4089
Douglas Gregorb11f9452012-03-26 16:54:18 +00004090 if (IsUnqualifiedLookup || SearchNamespaces) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004091 // For unqualified lookup, look through all of the names that we have
4092 // seen in this translation unit.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00004093 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004094 for (IdentifierTable::iterator I = Context.Idents.begin(),
4095 IEnd = Context.Idents.end();
4096 I != IEnd; ++I)
4097 Consumer.FoundName(I->getKey());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004098
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004099 // Walk through identifiers in external identifier sources.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00004100 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004101 if (IdentifierInfoLookup *External
4102 = Context.Idents.getExternalIdentifierLookup()) {
Ahmed Charlesb8984322014-03-07 20:03:18 +00004103 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004104 do {
4105 StringRef Name = Iter->Next();
4106 if (Name.empty())
4107 break;
Douglas Gregor57756ea2010-10-14 22:11:03 +00004108
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004109 Consumer.FoundName(Name);
4110 } while (true);
Douglas Gregor57756ea2010-10-14 22:11:03 +00004111 }
Douglas Gregor2d435302009-12-30 17:04:44 +00004112 }
4113
Richard Smithb3a1df02012-06-08 21:35:42 +00004114 AddKeywordsToConsumer(*this, Consumer, S, CCC, SS && SS->isNotEmpty());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004115
Douglas Gregor280e1ee2010-04-14 20:04:41 +00004116 // If we haven't found anything, we're done.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004117 if (Consumer.empty())
4118 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4119 IsUnqualifiedLookup);
Douglas Gregor2d435302009-12-30 17:04:44 +00004120
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004121 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4122 // is not more that about a third of the length of the typo's identifier.
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00004123 unsigned ED = Consumer.getBestEditDistance(true);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004124 if (ED > 0 && TypoLen / ED < 3)
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004125 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4126 IsUnqualifiedLookup);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004127
Douglas Gregorb11f9452012-03-26 16:54:18 +00004128 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4129 // to search those namespaces.
4130 if (SearchNamespaces) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004131 // Load any externally-known namespaces.
4132 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004133 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004134 LoadedExternalKnownNamespaces = true;
4135 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4136 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
4137 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
4138 }
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004139
Kaelyn Uhrainbbfc0572014-03-21 21:54:22 +00004140 for (auto KNPair : KnownNamespaces)
4141 Namespaces.AddNameSpecifier(KNPair.first);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004142
Kaelyn Uhrain0e353552014-02-09 21:47:04 +00004143 bool SSIsTemplate = false;
4144 if (NestedNameSpecifier *NNS =
4145 (SS && SS->isValid()) ? SS->getScopeRep() : 0) {
4146 if (const Type *T = NNS->getAsType())
4147 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
4148 }
Aaron Ballmane42430e2014-03-14 21:11:14 +00004149 for (const auto *TI : Context.types()) {
4150 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
Kaelyn Uhrain5315a462013-10-19 00:04:49 +00004151 CD = CD->getCanonicalDecl();
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004152 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
Kaelyn Uhrain21a66172014-02-05 18:57:51 +00004153 !CD->isUnion() && CD->getIdentifier() &&
Kaelyn Uhrain0e353552014-02-09 21:47:04 +00004154 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
Kaelyn Uhrain5315a462013-10-19 00:04:49 +00004155 (CD->isBeingDefined() || CD->isCompleteDefinition()))
4156 Namespaces.AddNameSpecifier(CD);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004157 }
4158 }
Douglas Gregor87074f12010-10-20 01:32:02 +00004159 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004160
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004161 // Weed out any names that could not be found by name lookup or, if a
4162 // CorrectionCandidateCallback object was provided, failed validation.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004163 SmallVector<TypoCorrection, 16> QualifiedResults;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004164 LookupResult TmpRes(*this, TypoName, LookupKind);
4165 TmpRes.suppressDiagnostics();
4166 while (!Consumer.empty()) {
4167 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
Benjamin Kramer73faad62012-04-14 08:26:28 +00004168 for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(),
4169 IEnd = DI->second.end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004170 I != IEnd; /* Increment in loop. */) {
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004171 // If we only want nested name specifier corrections, ignore potential
Kaelyn Uhrainec262992014-03-21 21:54:25 +00004172 // corrections that have a different base identifier from the typo or
4173 // which have a normalized edit distance longer than the typo itself.
4174 if (AllowOnlyNNSChanges) {
4175 TypoCorrection &TC = I->second.front();
4176 if (TC.getCorrectionAsIdentifierInfo() != Typo ||
4177 TC.getEditDistance(true) > TypoLen) {
4178 TypoCorrectionConsumer::result_iterator Prev = I;
4179 ++I;
4180 DI->second.erase(Prev);
4181 continue;
4182 }
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004183 }
4184
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004185 // If the item already has been looked up or is a keyword, keep it.
4186 // If a validator callback object was given, drop the correction
4187 // unless it passes validation.
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004188 bool Viable = false;
Benjamin Kramera2dcac12012-07-27 10:21:08 +00004189 for (TypoResultList::iterator RI = I->second.begin();
4190 RI != I->second.end(); /* Increment in loop. */) {
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004191 TypoResultList::iterator Prev = RI;
4192 ++RI;
4193 if (Prev->isResolved()) {
4194 if (!isCandidateViable(CCC, *Prev))
Benjamin Kramera2dcac12012-07-27 10:21:08 +00004195 RI = I->second.erase(Prev);
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004196 else
4197 Viable = true;
4198 }
4199 }
4200 if (Viable || I->second.empty()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004201 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004202 ++I;
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004203 if (!Viable)
Benjamin Kramer73faad62012-04-14 08:26:28 +00004204 DI->second.erase(Prev);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004205 continue;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004206 }
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004207 assert(I->second.size() == 1 && "Expected a single unresolved candidate");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004208
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004209 // Perform name lookup on this name.
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004210 TypoCorrection &Candidate = I->second.front();
4211 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00004212 DeclContext *TempMemberContext = MemberContext;
4213 CXXScopeSpec *TempSS = SS;
4214retry_lookup:
4215 LookupPotentialTypoResult(*this, TmpRes, Name, S, TempSS,
4216 TempMemberContext, EnteringContext,
Richard Smithe156254d2013-08-20 20:35:18 +00004217 CCC.IsObjCIvarLookup,
4218 Name == TypoName.getName() &&
4219 !Candidate.WillReplaceSpecifier());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004220
4221 switch (TmpRes.getResultKind()) {
4222 case LookupResult::NotFound:
4223 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain5a43b462011-09-07 20:25:59 +00004224 case LookupResult::FoundUnresolvedValue:
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00004225 if (TempSS) {
4226 // Immediately retry the lookup without the given CXXScopeSpec
4227 TempSS = NULL;
4228 Candidate.WillReplaceSpecifier(true);
4229 goto retry_lookup;
4230 }
4231 if (TempMemberContext) {
4232 if (SS && !TempSS)
4233 TempSS = SS;
4234 TempMemberContext = NULL;
4235 goto retry_lookup;
4236 }
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004237 QualifiedResults.push_back(Candidate);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004238 // We didn't find this name in our scope, or didn't like what we found;
4239 // ignore it.
4240 {
4241 TypoCorrectionConsumer::result_iterator Next = I;
4242 ++Next;
Benjamin Kramer73faad62012-04-14 08:26:28 +00004243 DI->second.erase(I);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004244 I = Next;
4245 }
4246 break;
4247
4248 case LookupResult::Ambiguous:
4249 // We don't deal with ambiguities.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004250 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004251
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004252 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004253 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004254 // Store all of the Decls for overloaded symbols
Kaelyn Uhrainbbfc0572014-03-21 21:54:22 +00004255 for (auto *TRD : TmpRes)
4256 Candidate.addCorrectionDecl(TRD);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004257 ++I;
Kaelyn Uhrainb18b0c02013-07-02 23:47:35 +00004258 if (!isCandidateViable(CCC, Candidate)) {
4259 QualifiedResults.push_back(Candidate);
Benjamin Kramer73faad62012-04-14 08:26:28 +00004260 DI->second.erase(Prev);
Kaelyn Uhrainb18b0c02013-07-02 23:47:35 +00004261 }
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004262 break;
4263 }
4264
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004265 case LookupResult::Found: {
4266 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004267 Candidate.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004268 ++I;
Kaelyn Uhrainb18b0c02013-07-02 23:47:35 +00004269 if (!isCandidateViable(CCC, Candidate)) {
4270 QualifiedResults.push_back(Candidate);
Benjamin Kramer73faad62012-04-14 08:26:28 +00004271 DI->second.erase(Prev);
Kaelyn Uhrainb18b0c02013-07-02 23:47:35 +00004272 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004273 break;
4274 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004275
4276 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004277 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004278
Benjamin Kramer73faad62012-04-14 08:26:28 +00004279 if (DI->second.empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004280 Consumer.erase(DI);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004281 else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !DI->first)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004282 // If there are results in the closest possible bucket, stop
4283 break;
4284
4285 // Only perform the qualified lookups for C++
Douglas Gregorb11f9452012-03-26 16:54:18 +00004286 if (SearchNamespaces) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004287 TmpRes.suppressDiagnostics();
Kaelyn Uhrainbbfc0572014-03-21 21:54:22 +00004288 for (auto QR : QualifiedResults) {
4289 for (auto NSI : Namespaces) {
4290 DeclContext *Ctx = NSI.DeclCtx;
4291 const Type *NSType = NSI.NameSpecifier->getAsType();
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004292
4293 // If the current NestedNameSpecifier refers to a class and the
4294 // current correction candidate is the name of that class, then skip
4295 // it as it is unlikely a qualified version of the class' constructor
4296 // is an appropriate correction.
4297 if (CXXRecordDecl *NSDecl =
4298 NSType ? NSType->getAsCXXRecordDecl() : 0) {
Kaelyn Uhrainbbfc0572014-03-21 21:54:22 +00004299 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004300 continue;
4301 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004302
Kaelyn Uhrainbbfc0572014-03-21 21:54:22 +00004303 TypoCorrection TC(QR);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004304 TC.ClearCorrectionDecls();
Kaelyn Uhrainbbfc0572014-03-21 21:54:22 +00004305 TC.setCorrectionSpecifier(NSI.NameSpecifier);
4306 TC.setQualifierDistance(NSI.EditDistance);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004307 TC.setCallbackDistance(0); // Reset the callback distance
4308
4309 // If the current correction candidate and namespace combination are
4310 // too far away from the original typo based on the normalized edit
4311 // distance, then skip performing a qualified name lookup.
4312 unsigned TmpED = TC.getEditDistance(true);
Kaelyn Uhrainbbfc0572014-03-21 21:54:22 +00004313 if (QR.getCorrectionAsIdentifierInfo() != Typo &&
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004314 TmpED && TypoLen / TmpED < 3)
4315 continue;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004316
4317 TmpRes.clear();
Kaelyn Uhrainbbfc0572014-03-21 21:54:22 +00004318 TmpRes.setLookupName(QR.getCorrectionAsIdentifierInfo());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004319 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
4320
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004321 // Any corrections added below will be validated in subsequent
4322 // iterations of the main while() loop over the Consumer's contents.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004323 switch (TmpRes.getResultKind()) {
Kaelyn Uhrainb18b0c02013-07-02 23:47:35 +00004324 case LookupResult::Found:
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004325 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00004326 if (SS && SS->isValid()) {
4327 std::string NewQualified = TC.getAsString(getLangOpts());
4328 std::string OldQualified;
4329 llvm::raw_string_ostream OldOStream(OldQualified);
4330 SS->getScopeRep()->print(OldOStream, getPrintingPolicy());
4331 OldOStream << TypoName;
4332 // If correction candidate would be an identical written qualified
4333 // identifer, then the existing CXXScopeSpec probably included a
4334 // typedef that didn't get accounted for properly.
4335 if (OldOStream.str() == NewQualified)
4336 break;
4337 }
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004338 for (LookupResult::iterator TRD = TmpRes.begin(),
4339 TRDEnd = TmpRes.end();
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004340 TRD != TRDEnd; ++TRD) {
4341 if (CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4342 NSType ? NSType->getAsCXXRecordDecl() : 0,
Eli Friedman3be1a1c2013-10-01 02:44:48 +00004343 TRD.getPair()) == AR_accessible)
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004344 TC.addCorrectionDecl(*TRD);
4345 }
4346 if (TC.isResolved())
4347 Consumer.addCorrection(TC);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004348 break;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004349 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004350 case LookupResult::NotFound:
4351 case LookupResult::NotFoundInCurrentInstantiation:
4352 case LookupResult::Ambiguous:
Kaelyn Uhrain5a43b462011-09-07 20:25:59 +00004353 case LookupResult::FoundUnresolvedValue:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004354 break;
4355 }
4356 }
4357 }
4358 }
4359
4360 QualifiedResults.clear();
4361 }
4362
4363 // No corrections remain...
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004364 if (Consumer.empty())
4365 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004366
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00004367 TypoResultsMap &BestResults = Consumer.getBestResults();
4368 ED = Consumer.getBestEditDistance(true);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004369
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004370 if (!AllowOnlyNNSChanges && ED > 0 && TypoLen / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004371 // If this was an unqualified lookup and we believe the callback
4372 // object wouldn't have filtered out possible corrections, note
4373 // that no correction was found.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004374 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4375 IsUnqualifiedLookup && !ValidatingCallback);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004376 }
4377
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004378 // If only a single name remains, return that result.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004379 if (BestResults.size() == 1) {
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004380 const TypoResultList &CorrectionList = BestResults.begin()->second;
4381 const TypoCorrection &Result = CorrectionList.front();
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004382 if (CorrectionList.size() != 1)
4383 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004384
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00004385 // Don't correct to a keyword that's the same as the typo; the keyword
4386 // wasn't actually in scope.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004387 if (ED == 0 && Result.isKeyword())
4388 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004389
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004390 // Record the correction for unqualified lookup.
4391 if (IsUnqualifiedLookup)
4392 UnqualifiedTyposCorrected[Typo] = Result;
4393
David Blaikie04ea41c2012-10-12 20:00:44 +00004394 TypoCorrection TC = Result;
4395 TC.setCorrectionRange(SS, TypoName);
Richard Smithe156254d2013-08-20 20:35:18 +00004396 checkCorrectionVisibility(*this, TC, TypoName.getName());
David Blaikie04ea41c2012-10-12 20:00:44 +00004397 return TC;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004398 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004399 else if (BestResults.size() > 1
4400 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4401 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4402 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4403 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00004404 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004405 && BestResults["super"].front().isKeyword()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004406 // Prefer 'super' when we're completing in a message-receiver
4407 // context.
4408
4409 // Don't correct to a keyword that's the same as the typo; the keyword
4410 // wasn't actually in scope.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004411 if (ED == 0)
4412 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004413
Douglas Gregor87074f12010-10-20 01:32:02 +00004414 // Record the correction for unqualified lookup.
4415 if (IsUnqualifiedLookup)
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004416 UnqualifiedTyposCorrected[Typo] = BestResults["super"].front();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004417
David Blaikie04ea41c2012-10-12 20:00:44 +00004418 TypoCorrection TC = BestResults["super"].front();
4419 TC.setCorrectionRange(SS, TypoName);
4420 return TC;
Douglas Gregoraf9eb592010-10-15 13:35:25 +00004421 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004422
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004423 // If this was an unqualified lookup and we believe the callback object did
4424 // not filter out possible corrections, note that no correction was found.
4425 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregor87074f12010-10-20 01:32:02 +00004426 (void)UnqualifiedTyposCorrected[Typo];
4427
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004428 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004429}
4430
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004431void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4432 if (!CDecl) return;
4433
4434 if (isKeyword())
4435 CorrectionDecls.clear();
4436
Kaelyn Uhrainf60b55a2012-11-19 18:49:53 +00004437 CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004438
4439 if (!CorrectionName)
4440 CorrectionName = CDecl->getDeclName();
4441}
4442
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004443std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4444 if (CorrectionNameSpec) {
4445 std::string tmpBuffer;
4446 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4447 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikied4da8722013-05-14 21:04:00 +00004448 PrefixOStream << CorrectionName;
Benjamin Kramer73faad62012-04-14 08:26:28 +00004449 return PrefixOStream.str();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004450 }
4451
4452 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00004453}
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004454
4455bool CorrectionCandidateCallback::ValidateCandidate(const TypoCorrection &candidate) {
4456 if (!candidate.isResolved())
4457 return true;
4458
4459 if (candidate.isKeyword())
4460 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4461 WantRemainingKeywords || WantObjCSuper;
4462
4463 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
4464 CDeclEnd = candidate.end();
4465 CDecl != CDeclEnd; ++CDecl) {
4466 if (!isa<TypeDecl>(*CDecl))
4467 return true;
4468 }
4469
4470 return WantTypeSpecifiers;
4471}
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004472
4473FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004474 bool HasExplicitTemplateArgs,
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004475 MemberExpr *ME)
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004476 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004477 CurContext(SemaRef.CurContext), MemberFn(ME) {
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004478 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
4479 WantRemainingKeywords = false;
4480}
4481
4482bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4483 if (!candidate.getCorrectionDecl())
4484 return candidate.isKeyword();
4485
4486 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
4487 DIEnd = candidate.end();
4488 DI != DIEnd; ++DI) {
4489 FunctionDecl *FD = 0;
4490 NamedDecl *ND = (*DI)->getUnderlyingDecl();
4491 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4492 FD = FTD->getTemplatedDecl();
4493 if (!HasExplicitTemplateArgs && !FD) {
4494 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4495 // If the Decl is neither a function nor a template function,
4496 // determine if it is a pointer or reference to a function. If so,
4497 // check against the number of arguments expected for the pointee.
4498 QualType ValType = cast<ValueDecl>(ND)->getType();
4499 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4500 ValType = ValType->getPointeeType();
4501 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
Alp Toker9cacbab2014-01-20 20:26:09 +00004502 if (FPT->getNumParams() == NumArgs)
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004503 return true;
4504 }
4505 }
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004506
4507 // Skip the current candidate if it is not a FunctionDecl or does not accept
4508 // the current number of arguments.
4509 if (!FD || !(FD->getNumParams() >= NumArgs &&
4510 FD->getMinRequiredArguments() <= NumArgs))
4511 continue;
4512
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004513 // If the current candidate is a non-static C++ method, skip the candidate
4514 // unless the method being corrected--or the current DeclContext, if the
4515 // function being corrected is not a method--is a method in the same class
4516 // or a descendent class of the candidate's parent class.
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004517 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004518 if (MemberFn || !MD->isStatic()) {
4519 CXXMethodDecl *CurMD =
4520 MemberFn
4521 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
4522 : dyn_cast_or_null<CXXMethodDecl>(CurContext);
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004523 CXXRecordDecl *CurRD =
4524 CurMD ? CurMD->getParent()->getCanonicalDecl() : 0;
4525 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
4526 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
4527 continue;
4528 }
4529 }
4530 return true;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004531 }
4532 return false;
4533}
Richard Smithf9b15102013-08-17 00:46:16 +00004534
4535void Sema::diagnoseTypo(const TypoCorrection &Correction,
4536 const PartialDiagnostic &TypoDiag,
4537 bool ErrorRecovery) {
4538 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
4539 ErrorRecovery);
4540}
4541
Richard Smithe156254d2013-08-20 20:35:18 +00004542/// Find which declaration we should import to provide the definition of
4543/// the given declaration.
4544static const NamedDecl *getDefinitionToImport(const NamedDecl *D) {
4545 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4546 return VD->getDefinition();
4547 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4548 return FD->isDefined(FD) ? FD : 0;
4549 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
4550 return TD->getDefinition();
4551 if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
4552 return ID->getDefinition();
4553 if (const ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
4554 return PD->getDefinition();
4555 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
4556 return getDefinitionToImport(TD->getTemplatedDecl());
4557 return 0;
4558}
4559
Richard Smithf9b15102013-08-17 00:46:16 +00004560/// \brief Diagnose a successfully-corrected typo. Separated from the correction
4561/// itself to allow external validation of the result, etc.
4562///
4563/// \param Correction The result of performing typo correction.
4564/// \param TypoDiag The diagnostic to produce. This will have the corrected
4565/// string added to it (and usually also a fixit).
4566/// \param PrevNote A note to use when indicating the location of the entity to
4567/// which we are correcting. Will have the correction string added to it.
4568/// \param ErrorRecovery If \c true (the default), the caller is going to
4569/// recover from the typo as if the corrected string had been typed.
4570/// In this case, \c PDiag must be an error, and we will attach a fixit
4571/// to it.
4572void Sema::diagnoseTypo(const TypoCorrection &Correction,
4573 const PartialDiagnostic &TypoDiag,
4574 const PartialDiagnostic &PrevNote,
4575 bool ErrorRecovery) {
4576 std::string CorrectedStr = Correction.getAsString(getLangOpts());
4577 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
4578 FixItHint FixTypo = FixItHint::CreateReplacement(
4579 Correction.getCorrectionRange(), CorrectedStr);
4580
Richard Smithe156254d2013-08-20 20:35:18 +00004581 // Maybe we're just missing a module import.
4582 if (Correction.requiresImport()) {
4583 NamedDecl *Decl = Correction.getCorrectionDecl();
4584 assert(Decl && "import required but no declaration to import");
4585
4586 // Suggest importing a module providing the definition of this entity, if
4587 // possible.
4588 const NamedDecl *Def = getDefinitionToImport(Decl);
4589 if (!Def)
4590 Def = Decl;
4591 Module *Owner = Def->getOwningModule();
4592 assert(Owner && "definition of hidden declaration is not in a module");
4593
4594 Diag(Correction.getCorrectionRange().getBegin(),
4595 diag::err_module_private_declaration)
4596 << Def << Owner->getFullModuleName();
4597 Diag(Def->getLocation(), diag::note_previous_declaration);
4598
4599 // Recover by implicitly importing this module.
4600 if (!isSFINAEContext() && ErrorRecovery)
4601 createImplicitModuleImport(Correction.getCorrectionRange().getBegin(),
4602 Owner);
4603 return;
4604 }
4605
Richard Smithf9b15102013-08-17 00:46:16 +00004606 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
4607 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
4608
4609 NamedDecl *ChosenDecl =
4610 Correction.isKeyword() ? 0 : Correction.getCorrectionDecl();
4611 if (PrevNote.getDiagID() && ChosenDecl)
4612 Diag(ChosenDecl->getLocation(), PrevNote)
4613 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
4614}