blob: 8edbc1871b430d77eab203f534be4d732fb96fc5 [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"
Alp Tokerb6cc5922014-05-03 03:45:55 +000026#include "clang/Lex/ModuleLoader.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "clang/Sema/DeclSpec.h"
28#include "clang/Sema/ExternalSemaSource.h"
29#include "clang/Sema/Overload.h"
30#include "clang/Sema/Scope.h"
31#include "clang/Sema/ScopeInfo.h"
32#include "clang/Sema/Sema.h"
33#include "clang/Sema/SemaInternal.h"
34#include "clang/Sema/TemplateDeduction.h"
35#include "clang/Sema/TypoCorrection.h"
Douglas Gregor34074322009-01-14 22:20:51 +000036#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "llvm/ADT/SetVector.h"
Douglas Gregore254f902009-02-04 00:32:51 +000038#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0afa7f62010-10-14 20:34:08 +000039#include "llvm/ADT/StringMap.h"
Chris Lattner83cfc7c2011-07-18 01:54:02 +000040#include "llvm/ADT/TinyPtrVector.h"
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +000041#include "llvm/ADT/edit_distance.h"
John McCall6538c932009-10-10 05:48:19 +000042#include "llvm/Support/ErrorHandling.h"
Nick Lewycky13668f22012-04-03 20:26:45 +000043#include <algorithm>
44#include <iterator>
Douglas Gregor0afa7f62010-10-14 20:34:08 +000045#include <limits>
Douglas Gregor2d435302009-12-30 17:04:44 +000046#include <list>
Douglas Gregorc2fa1692011-06-28 16:20:02 +000047#include <map>
Nick Lewycky13668f22012-04-03 20:26:45 +000048#include <set>
49#include <utility>
50#include <vector>
Douglas Gregor34074322009-01-14 22:20:51 +000051
52using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000053using namespace sema;
Douglas Gregor34074322009-01-14 22:20:51 +000054
John McCallf6c8a4e2009-11-10 07:01:13 +000055namespace {
56 class UnqualUsingEntry {
57 const DeclContext *Nominated;
58 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000059
John McCallf6c8a4e2009-11-10 07:01:13 +000060 public:
61 UnqualUsingEntry(const DeclContext *Nominated,
62 const DeclContext *CommonAncestor)
63 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
64 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000065
John McCallf6c8a4e2009-11-10 07:01:13 +000066 const DeclContext *getCommonAncestor() const {
67 return CommonAncestor;
68 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000069
John McCallf6c8a4e2009-11-10 07:01:13 +000070 const DeclContext *getNominatedNamespace() const {
71 return Nominated;
72 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000073
John McCallf6c8a4e2009-11-10 07:01:13 +000074 // Sort by the pointer value of the common ancestor.
75 struct Comparator {
76 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
77 return L.getCommonAncestor() < R.getCommonAncestor();
78 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000079
John McCallf6c8a4e2009-11-10 07:01:13 +000080 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
81 return E.getCommonAncestor() < DC;
82 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000083
John McCallf6c8a4e2009-11-10 07:01:13 +000084 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
85 return DC < E.getCommonAncestor();
86 }
87 };
88 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000089
John McCallf6c8a4e2009-11-10 07:01:13 +000090 /// A collection of using directives, as used by C++ unqualified
91 /// lookup.
92 class UnqualUsingDirectiveSet {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000093 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000094
John McCallf6c8a4e2009-11-10 07:01:13 +000095 ListTy list;
96 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000097
John McCallf6c8a4e2009-11-10 07:01:13 +000098 public:
99 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +0000100
John McCallf6c8a4e2009-11-10 07:01:13 +0000101 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000102 // C++ [namespace.udir]p1:
John McCallf6c8a4e2009-11-10 07:01:13 +0000103 // During unqualified name lookup, the names appear as if they
104 // were declared in the nearest enclosing namespace which contains
105 // both the using-directive and the nominated namespace.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000106 DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
John McCallf6c8a4e2009-11-10 07:01:13 +0000107 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +0000108
John McCallf6c8a4e2009-11-10 07:01:13 +0000109 for (; S; S = S->getParent()) {
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000110 // C++ [namespace.udir]p1:
111 // A using-directive shall not appear in class scope, but may
112 // appear in namespace scope or in block scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000113 DeclContext *Ctx = S->getEntity();
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000114 if (Ctx && Ctx->isFileContext()) {
115 visit(Ctx, Ctx);
116 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
Aaron Ballman5df6aa42014-03-17 17:03:37 +0000117 for (auto *I : S->using_directives())
118 visit(I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000119 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000120 }
121 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000122
123 // Visits a context and collect all of its using directives
124 // recursively. Treats all using directives as if they were
125 // declared in the context.
126 //
127 // A given context is only every visited once, so it is important
128 // that contexts be visited from the inside out in order to get
129 // the effective DCs right.
130 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
David Blaikie82e95a32014-11-19 07:49:47 +0000131 if (!visited.insert(DC).second)
John McCallf6c8a4e2009-11-10 07:01:13 +0000132 return;
133
134 addUsingDirectives(DC, EffectiveDC);
135 }
136
137 // Visits a using directive and collects all of its using
138 // directives recursively. Treats all using directives as if they
139 // were declared in the effective DC.
140 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
141 DeclContext *NS = UD->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +0000142 if (!visited.insert(NS).second)
John McCallf6c8a4e2009-11-10 07:01:13 +0000143 return;
144
145 addUsingDirective(UD, EffectiveDC);
146 addUsingDirectives(NS, EffectiveDC);
147 }
148
149 // Adds all the using directives in a context (and those nominated
150 // by its using directives, transitively) as if they appeared in
151 // the given effective context.
152 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000153 SmallVector<DeclContext*,4> queue;
John McCallf6c8a4e2009-11-10 07:01:13 +0000154 while (true) {
Aaron Ballman804a7fb2014-03-17 17:14:12 +0000155 for (auto UD : DC->using_directives()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000156 DeclContext *NS = UD->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +0000157 if (visited.insert(NS).second) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000158 addUsingDirective(UD, EffectiveDC);
159 queue.push_back(NS);
160 }
161 }
162
163 if (queue.empty())
164 return;
165
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000166 DC = queue.pop_back_val();
John McCallf6c8a4e2009-11-10 07:01:13 +0000167 }
168 }
169
170 // Add a using directive as if it had been declared in the given
171 // context. This helps implement C++ [namespace.udir]p3:
172 // The using-directive is transitive: if a scope contains a
173 // using-directive that nominates a second namespace that itself
174 // contains using-directives, the effect is as if the
175 // using-directives from the second namespace also appeared in
176 // the first.
177 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
178 // Find the common ancestor between the effective context and
179 // the nominated namespace.
180 DeclContext *Common = UD->getNominatedNamespace();
181 while (!Common->Encloses(EffectiveDC))
182 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000183 Common = Common->getPrimaryContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000184
John McCallf6c8a4e2009-11-10 07:01:13 +0000185 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
186 }
187
188 void done() {
189 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
190 }
191
John McCallf6c8a4e2009-11-10 07:01:13 +0000192 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000193
John McCallf6c8a4e2009-11-10 07:01:13 +0000194 const_iterator begin() const { return list.begin(); }
195 const_iterator end() const { return list.end(); }
196
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000197 llvm::iterator_range<const_iterator>
John McCallf6c8a4e2009-11-10 07:01:13 +0000198 getNamespacesFor(DeclContext *DC) const {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000199 return llvm::make_range(std::equal_range(begin(), end(),
200 DC->getPrimaryContext(),
201 UnqualUsingEntry::Comparator()));
John McCallf6c8a4e2009-11-10 07:01:13 +0000202 }
203 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000204}
205
Douglas Gregor889ceb72009-02-03 19:21:40 +0000206// Retrieve the set of identifier namespaces that correspond to a
207// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000208static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
209 bool CPlusPlus,
210 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000211 unsigned IDNS = 0;
212 switch (NameKind) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +0000213 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000214 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000215 case Sema::LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +0000216 case Sema::LookupLocalFriendName:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000217 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000218 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000219 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000220 if (Redeclaration)
221 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCallea305ed2009-12-18 10:40:03 +0000222 }
Richard Smith541b38b2013-09-20 01:15:31 +0000223 if (Redeclaration)
224 IDNS |= Decl::IDNS_LocalExtern;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000225 break;
226
John McCallb9467b62010-04-24 01:30:58 +0000227 case Sema::LookupOperatorName:
228 // Operator lookup is its own crazy thing; it is not the same
229 // as (e.g.) looking up an operator name for redeclaration.
230 assert(!Redeclaration && "cannot do redeclaration operator lookup");
231 IDNS = Decl::IDNS_NonMemberOperator;
232 break;
233
Douglas Gregor889ceb72009-02-03 19:21:40 +0000234 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000235 if (CPlusPlus) {
236 IDNS = Decl::IDNS_Type;
237
238 // When looking for a redeclaration of a tag name, we add:
239 // 1) TagFriend to find undeclared friend decls
240 // 2) Namespace because they can't "overload" with tag decls.
241 // 3) Tag because it includes class templates, which can't
242 // "overload" with tag decls.
243 if (Redeclaration)
244 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
245 } else {
246 IDNS = Decl::IDNS_Tag;
247 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000248 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000249
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000250 case Sema::LookupLabel:
251 IDNS = Decl::IDNS_Label;
252 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000253
Douglas Gregor889ceb72009-02-03 19:21:40 +0000254 case Sema::LookupMemberName:
255 IDNS = Decl::IDNS_Member;
256 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000257 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000258 break;
259
260 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000261 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
262 break;
263
Douglas Gregor889ceb72009-02-03 19:21:40 +0000264 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000265 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000266 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000267
John McCall84d87672009-12-10 09:41:52 +0000268 case Sema::LookupUsingDeclName:
Richard Smith83e78f52014-04-11 01:03:38 +0000269 assert(Redeclaration && "should only be used for redecl lookup");
270 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |
271 Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend |
272 Decl::IDNS_LocalExtern;
John McCall84d87672009-12-10 09:41:52 +0000273 break;
274
Douglas Gregor79947a22009-04-24 00:11:27 +0000275 case Sema::LookupObjCProtocolName:
276 IDNS = Decl::IDNS_ObjCProtocol;
277 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000278
Douglas Gregor39982192010-08-15 06:18:01 +0000279 case Sema::LookupAnyName:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000280 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor39982192010-08-15 06:18:01 +0000281 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
282 | Decl::IDNS_Type;
283 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000284 }
285 return IDNS;
286}
287
John McCallea305ed2009-12-18 10:40:03 +0000288void LookupResult::configure() {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000289 IDNS = getIDNS(LookupKind, getSema().getLangOpts().CPlusPlus,
John McCallea305ed2009-12-18 10:40:03 +0000290 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000291
Richard Smithbdd14642014-02-04 01:14:30 +0000292 // If we're looking for one of the allocation or deallocation
293 // operators, make sure that the implicitly-declared new and delete
294 // operators can be found.
295 switch (NameInfo.getName().getCXXOverloadedOperator()) {
296 case OO_New:
297 case OO_Delete:
298 case OO_Array_New:
299 case OO_Array_Delete:
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000300 getSema().DeclareGlobalNewDelete();
Richard Smithbdd14642014-02-04 01:14:30 +0000301 break;
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000302
Richard Smithbdd14642014-02-04 01:14:30 +0000303 default:
304 break;
305 }
Douglas Gregor15197662013-04-03 23:06:26 +0000306
Richard Smithbdd14642014-02-04 01:14:30 +0000307 // Compiler builtins are always visible, regardless of where they end
308 // up being declared.
309 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
310 if (unsigned BuiltinID = Id->getBuiltinID()) {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000311 if (!getSema().Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
Richard Smithbdd14642014-02-04 01:14:30 +0000312 AllowHidden = true;
Douglas Gregor15197662013-04-03 23:06:26 +0000313 }
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000314 }
John McCallea305ed2009-12-18 10:40:03 +0000315}
316
Alp Tokerc1086762013-12-07 13:51:35 +0000317bool LookupResult::sanity() const {
Richard Smithf97ad222014-04-01 18:33:50 +0000318 // This function is never called by NDEBUG builds.
John McCall19c1bfd2010-08-25 05:32:35 +0000319 assert(ResultKind != NotFound || Decls.size() == 0);
320 assert(ResultKind != Found || Decls.size() == 1);
321 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
322 (Decls.size() == 1 &&
323 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
324 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
325 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000326 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
327 Ambiguity == AmbiguousBaseSubobjectTypes)));
Craig Topperc3ec1492014-05-26 06:22:03 +0000328 assert((Paths != nullptr) == (ResultKind == Ambiguous &&
329 (Ambiguity == AmbiguousBaseSubobjectTypes ||
330 Ambiguity == AmbiguousBaseSubobjects)));
Alp Tokerc1086762013-12-07 13:51:35 +0000331 return true;
John McCall19c1bfd2010-08-25 05:32:35 +0000332}
John McCall19c1bfd2010-08-25 05:32:35 +0000333
John McCall9f3059a2009-10-09 21:13:30 +0000334// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000335void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000336 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000337}
338
Richard Smith3876cc82013-10-30 01:02:04 +0000339/// Get a representative context for a declaration such that two declarations
340/// will have the same context if they were found within the same scope.
Benjamin Kramerfc58b042013-11-01 11:50:55 +0000341static DeclContext *getContextForScopeMatching(Decl *D) {
Richard Smith3876cc82013-10-30 01:02:04 +0000342 // For function-local declarations, use that function as the context. This
343 // doesn't account for scopes within the function; the caller must deal with
344 // those.
345 DeclContext *DC = D->getLexicalDeclContext();
346 if (DC->isFunctionOrMethod())
347 return DC;
348
349 // Otherwise, look at the semantic context of the declaration. The
350 // declaration must have been found there.
351 return D->getDeclContext()->getRedeclContext();
352}
353
John McCall283b9012009-11-22 00:44:51 +0000354/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000355void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000356 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000357
John McCall9f3059a2009-10-09 21:13:30 +0000358 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000359 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000360 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000361 return;
362 }
363
John McCall283b9012009-11-22 00:44:51 +0000364 // If there's a single decl, we need to examine it to decide what
365 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000366 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000367 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
368 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000369 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000370 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000371 ResultKind = FoundUnresolvedValue;
372 return;
373 }
John McCall9f3059a2009-10-09 21:13:30 +0000374
John McCall6538c932009-10-10 05:48:19 +0000375 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000376 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000377
John McCall9f3059a2009-10-09 21:13:30 +0000378 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor13e65872010-08-11 14:45:53 +0000379 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000380
John McCall9f3059a2009-10-09 21:13:30 +0000381 bool Ambiguous = false;
382 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000383 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000384
385 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000386
John McCall9f3059a2009-10-09 21:13:30 +0000387 unsigned I = 0;
388 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000389 NamedDecl *D = Decls[I]->getUnderlyingDecl();
390 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000391
Argyrios Kyrtzidis1fcd7fd2013-02-22 06:58:37 +0000392 // Ignore an invalid declaration unless it's the only one left.
393 if (D->isInvalidDecl() && I < N-1) {
394 Decls[I] = Decls[--N];
395 continue;
396 }
397
Douglas Gregor13e65872010-08-11 14:45:53 +0000398 // Redeclarations of types via typedef can occur both within a scope
399 // and, through using declarations and directives, across scopes. There is
400 // no ambiguity if they all refer to the same type, so unique based on the
401 // canonical type.
402 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
403 if (!TD->getDeclContext()->isRecord()) {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000404 QualType T = getSema().Context.getTypeDeclType(TD);
David Blaikie82e95a32014-11-19 07:49:47 +0000405 if (!UniqueTypes.insert(getSema().Context.getCanonicalType(T)).second) {
Douglas Gregor13e65872010-08-11 14:45:53 +0000406 // The type is not unique; pull something off the back and continue
407 // at this index.
408 Decls[I] = Decls[--N];
409 continue;
410 }
411 }
412 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000413
David Blaikie82e95a32014-11-19 07:49:47 +0000414 if (!Unique.insert(D).second) {
John McCall9f3059a2009-10-09 21:13:30 +0000415 // If it's not unique, pull something off the back (and
416 // continue at this index).
417 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000418 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000419 }
420
Douglas Gregor13e65872010-08-11 14:45:53 +0000421 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000422
Douglas Gregor13e65872010-08-11 14:45:53 +0000423 if (isa<UnresolvedUsingValueDecl>(D)) {
424 HasUnresolved = true;
425 } else if (isa<TagDecl>(D)) {
426 if (HasTag)
427 Ambiguous = true;
428 UniqueTagIndex = I;
429 HasTag = true;
430 } else if (isa<FunctionTemplateDecl>(D)) {
431 HasFunction = true;
432 HasFunctionTemplate = true;
433 } else if (isa<FunctionDecl>(D)) {
434 HasFunction = true;
435 } else {
436 if (HasNonFunction)
437 Ambiguous = true;
438 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000439 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000440 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000441 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000442
John McCall9f3059a2009-10-09 21:13:30 +0000443 // C++ [basic.scope.hiding]p2:
444 // A class name or enumeration name can be hidden by the name of
445 // an object, function, or enumerator declared in the same
446 // scope. If a class or enumeration name and an object, function,
447 // or enumerator are declared in the same scope (in any order)
448 // with the same name, the class or enumeration name is hidden
449 // wherever the object, function, or enumerator name is visible.
450 // But it's still an error if there are distinct tag types found,
451 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000452 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000453 (HasFunction || HasNonFunction || HasUnresolved)) {
Richard Smith3876cc82013-10-30 01:02:04 +0000454 if (getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
455 getContextForScopeMatching(Decls[UniqueTagIndex ? 0 : N - 1])))
Douglas Gregore63d0872010-10-23 16:06:17 +0000456 Decls[UniqueTagIndex] = Decls[--N];
457 else
458 Ambiguous = true;
459 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000460
John McCall9f3059a2009-10-09 21:13:30 +0000461 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000462
John McCall80053822009-12-03 00:58:24 +0000463 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000464 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000465
John McCall9f3059a2009-10-09 21:13:30 +0000466 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000467 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000468 else if (HasUnresolved)
469 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000470 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000471 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000472 else
John McCall27b18f82009-11-17 02:14:36 +0000473 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000474}
475
John McCall5cebab12009-11-18 07:57:50 +0000476void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000477 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000478 for (I = P.begin(), E = P.end(); I != E; ++I)
David Blaikieff7d47a2012-12-19 00:45:41 +0000479 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
480 DE = I->Decls.end(); DI != DE; ++DI)
John McCall9f3059a2009-10-09 21:13:30 +0000481 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000482}
483
John McCall5cebab12009-11-18 07:57:50 +0000484void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000485 Paths = new CXXBasePaths;
486 Paths->swap(P);
487 addDeclsFromBasePaths(*Paths);
488 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000489 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000490}
491
John McCall5cebab12009-11-18 07:57:50 +0000492void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000493 Paths = new CXXBasePaths;
494 Paths->swap(P);
495 addDeclsFromBasePaths(*Paths);
496 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000497 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000498}
499
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000500void LookupResult::print(raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000501 Out << Decls.size() << " result(s)";
502 if (isAmbiguous()) Out << ", ambiguous";
503 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000504
John McCall9f3059a2009-10-09 21:13:30 +0000505 for (iterator I = begin(), E = end(); I != E; ++I) {
506 Out << "\n";
507 (*I)->print(Out, 2);
508 }
509}
510
Douglas Gregord3a59182010-02-12 05:48:04 +0000511/// \brief Lookup a builtin function, when name lookup would otherwise
512/// fail.
513static bool LookupBuiltin(Sema &S, LookupResult &R) {
514 Sema::LookupNameKind NameKind = R.getLookupKind();
515
516 // If we didn't find a use of this identifier, and if the identifier
517 // corresponds to a compiler builtin, create the decl object for the builtin
518 // now, injecting it into translation unit scope, and return it.
519 if (NameKind == Sema::LookupOrdinaryName ||
520 NameKind == Sema::LookupRedeclarationWithLinkage) {
521 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
522 if (II) {
Nico Webere1687c52013-06-20 21:44:55 +0000523 if (S.getLangOpts().CPlusPlus11 && S.getLangOpts().GNUMode &&
524 II == S.getFloat128Identifier()) {
525 // libstdc++4.7's type_traits expects type __float128 to exist, so
526 // insert a dummy type to make that header build in gnu++11 mode.
527 R.addDecl(S.getASTContext().getFloat128StubType());
528 return true;
529 }
530
Douglas Gregord3a59182010-02-12 05:48:04 +0000531 // If this is a builtin on this (or all) targets, create the decl.
532 if (unsigned BuiltinID = II->getBuiltinID()) {
533 // In C++, we don't have any predefined library functions like
534 // 'malloc'. Instead, we'll just error.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000535 if (S.getLangOpts().CPlusPlus &&
Douglas Gregord3a59182010-02-12 05:48:04 +0000536 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
537 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000538
539 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
540 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000541 R.isForRedeclaration(),
542 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000543 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000544 return true;
545 }
Douglas Gregord3a59182010-02-12 05:48:04 +0000546 }
547 }
548 }
549
550 return false;
551}
552
Douglas Gregor7454c562010-07-02 20:37:36 +0000553/// \brief Determine whether we can declare a special member function within
554/// the class at this point.
Richard Smith7d125a12012-11-27 21:20:31 +0000555static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +0000556 // We need to have a definition for the class.
557 if (!Class->getDefinition() || Class->isDependentContext())
558 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000559
Douglas Gregor7454c562010-07-02 20:37:36 +0000560 // We can't be in the middle of defining the class.
Richard Smith7d125a12012-11-27 21:20:31 +0000561 return !Class->isBeingDefined();
Douglas Gregor7454c562010-07-02 20:37:36 +0000562}
563
564void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smith7d125a12012-11-27 21:20:31 +0000565 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregora6d69502010-07-02 23:41:54 +0000566 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000567
568 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000569 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000570 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000571
Douglas Gregora6d69502010-07-02 23:41:54 +0000572 // If the copy constructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000573 if (Class->needsImplicitCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +0000574 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000575
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000576 // If the copy assignment operator has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000577 if (Class->needsImplicitCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000578 DeclareImplicitCopyAssignment(Class);
579
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000580 if (getLangOpts().CPlusPlus11) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000581 // If the move constructor has not yet been declared, do so now.
582 if (Class->needsImplicitMoveConstructor())
583 DeclareImplicitMoveConstructor(Class); // might not actually do it
584
585 // If the move assignment operator has not yet been declared, do so now.
586 if (Class->needsImplicitMoveAssignment())
587 DeclareImplicitMoveAssignment(Class); // might not actually do it
588 }
589
Douglas Gregor7454c562010-07-02 20:37:36 +0000590 // If the destructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000591 if (Class->needsImplicitDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000592 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000593}
594
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000595/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000596/// special member function.
597static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
598 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000599 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000600 case DeclarationName::CXXDestructorName:
601 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000602
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000603 case DeclarationName::CXXOperatorName:
604 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000605
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000606 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000607 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000608 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000609
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000610 return false;
611}
612
613/// \brief If there are any implicit member functions with the given name
614/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000615static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000616 DeclarationName Name,
617 const DeclContext *DC) {
618 if (!DC)
619 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000620
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000621 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000622 case DeclarationName::CXXConstructorName:
623 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith7d125a12012-11-27 21:20:31 +0000624 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000625 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000626 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000627 S.DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +0000628 if (Record->needsImplicitCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000629 S.DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000630 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000631 Record->needsImplicitMoveConstructor())
632 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000633 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000634 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000635
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000636 case DeclarationName::CXXDestructorName:
637 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith2be35f52012-12-01 02:35:44 +0000638 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smith7d125a12012-11-27 21:20:31 +0000639 CanDeclareSpecialMemberFunction(Record))
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000640 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000641 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000642
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000643 case DeclarationName::CXXOperatorName:
644 if (Name.getCXXOverloadedOperator() != OO_Equal)
645 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000646
Sebastian Redl22653ba2011-08-30 19:58:05 +0000647 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smith7d125a12012-11-27 21:20:31 +0000648 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000649 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smith2be35f52012-12-01 02:35:44 +0000650 if (Record->needsImplicitCopyAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000651 S.DeclareImplicitCopyAssignment(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000652 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000653 Record->needsImplicitMoveAssignment())
654 S.DeclareImplicitMoveAssignment(Class);
655 }
656 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000657 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000658
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000659 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000660 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000661 }
662}
Douglas Gregor7454c562010-07-02 20:37:36 +0000663
John McCall9f3059a2009-10-09 21:13:30 +0000664// Adds all qualifying matches for a name within a decl context to the
665// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000666static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000667 bool Found = false;
668
Douglas Gregor7454c562010-07-02 20:37:36 +0000669 // Lazily declare C++ special member functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000670 if (S.getLangOpts().CPlusPlus)
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000671 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000672
Douglas Gregor7454c562010-07-02 20:37:36 +0000673 // Perform lookup into this declaration context.
David Blaikieff7d47a2012-12-19 00:45:41 +0000674 DeclContext::lookup_const_result DR = DC->lookup(R.getLookupName());
675 for (DeclContext::lookup_const_iterator I = DR.begin(), E = DR.end(); I != E;
676 ++I) {
John McCall401982f2010-01-20 21:53:11 +0000677 NamedDecl *D = *I;
Douglas Gregor4a814562011-12-14 16:03:29 +0000678 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000679 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000680 Found = true;
681 }
682 }
John McCall9f3059a2009-10-09 21:13:30 +0000683
Douglas Gregord3a59182010-02-12 05:48:04 +0000684 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
685 return true;
686
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000687 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000688 != DeclarationName::CXXConversionFunctionName ||
689 R.getLookupName().getCXXNameType()->isDependentType() ||
690 !isa<CXXRecordDecl>(DC))
691 return Found;
692
693 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000694 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000695 // name lookup. Instead, any conversion function templates visible in the
696 // context of the use are considered. [...]
697 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000698 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000699 return Found;
700
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +0000701 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
702 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruth3a693b72010-01-31 11:44:02 +0000703 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
704 if (!ConvTemplate)
705 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000706
Chandler Carruth3a693b72010-01-31 11:44:02 +0000707 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000708 // add the conversion function template. When we deduce template
709 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000710 // type of the new declaration with the type of the function template.
711 if (R.isForRedeclaration()) {
712 R.addDecl(ConvTemplate);
713 Found = true;
714 continue;
715 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000716
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000717 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000718 // [...] For each such operator, if argument deduction succeeds
719 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000720 // name lookup.
721 //
722 // When referencing a conversion function for any purpose other than
723 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000724 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000725 // specialization into the result set. We do this to avoid forcing all
726 // callers to perform special deduction for conversion functions.
Craig Toppere6706e42012-09-19 02:26:47 +0000727 TemplateDeductionInfo Info(R.getNameLoc());
Craig Topperc3ec1492014-05-26 06:22:03 +0000728 FunctionDecl *Specialization = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000729
730 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000731 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
732 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000733
Chandler Carruth3a693b72010-01-31 11:44:02 +0000734 // Compute the type of the function that we would expect the conversion
735 // function to have, if it were to match the name given.
736 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000737 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
Reid Kleckner78af0702013-08-27 23:08:25 +0000738 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
Richard Smith8acb4282014-07-31 21:57:55 +0000739 EPI.ExceptionSpec = EST_None;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000740 QualType ExpectedType
741 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000742 None, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000743
Chandler Carruth3a693b72010-01-31 11:44:02 +0000744 // Perform template argument deduction against the type that we would
745 // expect the function to have.
Craig Topperc3ec1492014-05-26 06:22:03 +0000746 if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
Chandler Carruth3a693b72010-01-31 11:44:02 +0000747 Specialization, Info)
748 == Sema::TDK_Success) {
749 R.addDecl(Specialization);
750 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000751 }
752 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000753
John McCall9f3059a2009-10-09 21:13:30 +0000754 return Found;
755}
756
John McCallf6c8a4e2009-11-10 07:01:13 +0000757// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000758static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000759CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000760 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000761
762 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
763
John McCallf6c8a4e2009-11-10 07:01:13 +0000764 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000765 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000766
John McCallf6c8a4e2009-11-10 07:01:13 +0000767 // Perform direct name lookup into the namespaces nominated by the
768 // using directives whose common ancestor is this namespace.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000769 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
770 if (LookupDirect(S, R, UUE.getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000771 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000772
773 R.resolveKind();
774
775 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000776}
777
778static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000779 if (DeclContext *Ctx = S->getEntity())
Douglas Gregor700792c2009-02-05 19:25:20 +0000780 return Ctx->isFileContext();
781 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000782}
Douglas Gregored8f2882009-01-30 01:04:22 +0000783
Douglas Gregor66230062010-03-15 14:33:29 +0000784// Find the next outer declaration context from this scope. This
785// routine actually returns the semantic outer context, which may
786// differ from the lexical context (encoded directly in the Scope
787// stack) when we are parsing a member of a class template. In this
788// case, the second element of the pair will be true, to indicate that
789// name lookup should continue searching in this semantic context when
790// it leaves the current template parameter scope.
791static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000792 DeclContext *DC = S->getEntity();
Craig Topperc3ec1492014-05-26 06:22:03 +0000793 DeclContext *Lexical = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000794 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000795 OuterS = OuterS->getParent()) {
796 if (OuterS->getEntity()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000797 Lexical = OuterS->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +0000798 break;
799 }
800 }
801
802 // C++ [temp.local]p8:
803 // In the definition of a member of a class template that appears
804 // outside of the namespace containing the class template
805 // definition, the name of a template-parameter hides the name of
806 // a member of this namespace.
807 //
808 // Example:
809 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000810 // namespace N {
811 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000812 //
813 // template<class T> class B {
814 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000815 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000816 // }
817 //
818 // template<class C> void N::B<C>::f(C) {
819 // C b; // C is the template parameter, not N::C
820 // }
821 //
822 // In this example, the lexical context we return is the
823 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000824 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000825 !S->getParent()->isTemplateParamScope())
826 return std::make_pair(Lexical, false);
827
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000828 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000829 // For the example, this is the scope for the template parameters of
830 // template<class C>.
831 Scope *OutermostTemplateScope = S->getParent();
832 while (OutermostTemplateScope->getParent() &&
833 OutermostTemplateScope->getParent()->isTemplateParamScope())
834 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000835
Douglas Gregor66230062010-03-15 14:33:29 +0000836 // Find the namespace context in which the original scope occurs. In
837 // the example, this is namespace N.
838 DeclContext *Semantic = DC;
839 while (!Semantic->isFileContext())
840 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000841
Douglas Gregor66230062010-03-15 14:33:29 +0000842 // Find the declaration context just outside of the template
843 // parameter scope. This is the context in which the template is
844 // being lexically declaration (a namespace context). In the
845 // example, this is the global scope.
846 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
847 Lexical->Encloses(Semantic))
848 return std::make_pair(Semantic, true);
849
850 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000851}
852
Richard Smith541b38b2013-09-20 01:15:31 +0000853namespace {
854/// An RAII object to specify that we want to find block scope extern
855/// declarations.
856struct FindLocalExternScope {
857 FindLocalExternScope(LookupResult &R)
858 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
859 Decl::IDNS_LocalExtern) {
860 R.setFindLocalExtern(R.getIdentifierNamespace() & Decl::IDNS_Ordinary);
861 }
862 void restore() {
863 R.setFindLocalExtern(OldFindLocalExtern);
864 }
865 ~FindLocalExternScope() {
866 restore();
867 }
868 LookupResult &R;
869 bool OldFindLocalExtern;
870};
871}
872
John McCall27b18f82009-11-17 02:14:36 +0000873bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000874 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000875
876 DeclarationName Name = R.getLookupName();
Richard Smith1c34fb72013-08-13 18:18:50 +0000877 Sema::LookupNameKind NameKind = R.getLookupKind();
John McCall27b18f82009-11-17 02:14:36 +0000878
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000879 // If this is the name of an implicitly-declared special member function,
880 // go through the scope stack to implicitly declare
881 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
882 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +0000883 if (DeclContext *DC = PreS->getEntity())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000884 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
885 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000886
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000887 // Implicitly declare member functions with the name we're looking for, if in
888 // fact we are in a scope where it matters.
889
Douglas Gregor889ceb72009-02-03 19:21:40 +0000890 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000891 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000892 I = IdResolver.begin(Name),
893 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000894
Douglas Gregor889ceb72009-02-03 19:21:40 +0000895 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000896 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000897 // ...During unqualified name lookup (3.4.1), the names appear as if
898 // they were declared in the nearest enclosing namespace which contains
899 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000900 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000901 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000902 //
903 // For example:
904 // namespace A { int i; }
905 // void foo() {
906 // int i;
907 // {
908 // using namespace A;
909 // ++i; // finds local 'i', A::i appears at global scope
910 // }
911 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000912 //
Douglas Gregorcc9406c2013-04-08 23:11:25 +0000913 UnqualUsingDirectiveSet UDirs;
914 bool VisitedUsingDirectives = false;
Richard Smith1c34fb72013-08-13 18:18:50 +0000915 bool LeftStartingScope = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000916 DeclContext *OutsideOfTemplateParamDC = nullptr;
Richard Smith541b38b2013-09-20 01:15:31 +0000917
918 // When performing a scope lookup, we want to find local extern decls.
919 FindLocalExternScope FindLocals(R);
920
Douglas Gregor700792c2009-02-05 19:25:20 +0000921 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000922 DeclContext *Ctx = S->getEntity();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000923
Douglas Gregor889ceb72009-02-03 19:21:40 +0000924 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000925 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000926 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000927 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Richard Smith1c34fb72013-08-13 18:18:50 +0000928 if (NameKind == LookupRedeclarationWithLinkage) {
929 // Determine whether this (or a previous) declaration is
930 // out-of-scope.
931 if (!LeftStartingScope && !Initial->isDeclScope(*I))
932 LeftStartingScope = true;
933
934 // If we found something outside of our starting scope that
Richard Smith9a00bbf2013-10-16 21:12:00 +0000935 // does not have linkage, skip it. If it's a template parameter,
936 // we still find it, so we can diagnose the invalid redeclaration.
937 if (LeftStartingScope && !((*I)->hasLinkage()) &&
938 !(*I)->isTemplateParameter()) {
Richard Smith1c34fb72013-08-13 18:18:50 +0000939 R.setShadowed();
940 continue;
941 }
942 }
943
John McCall9f3059a2009-10-09 21:13:30 +0000944 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +0000945 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000946 }
947 }
John McCall9f3059a2009-10-09 21:13:30 +0000948 if (Found) {
949 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000950 if (S->isClassScope())
951 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
952 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000953 return true;
954 }
955
Richard Smith1c34fb72013-08-13 18:18:50 +0000956 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
Richard Smith114394f2013-08-09 04:35:01 +0000957 // C++11 [class.friend]p11:
958 // If a friend declaration appears in a local class and the name
959 // specified is an unqualified name, a prior declaration is
960 // looked up without considering scopes that are outside the
961 // innermost enclosing non-class scope.
962 return false;
963 }
964
Douglas Gregor66230062010-03-15 14:33:29 +0000965 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
966 S->getParent() && !S->getParent()->isTemplateParamScope()) {
967 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000968 // found nothing, so look into the contexts between the
Douglas Gregor66230062010-03-15 14:33:29 +0000969 // lexical and semantic declaration contexts returned by
970 // findOuterContext(). This implements the name lookup behavior
971 // of C++ [temp.local]p8.
972 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +0000973 OutsideOfTemplateParamDC = nullptr;
Douglas Gregor66230062010-03-15 14:33:29 +0000974 }
975
976 if (Ctx) {
977 DeclContext *OuterCtx;
978 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000979 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregor66230062010-03-15 14:33:29 +0000980 if (SearchAfterTemplateScope)
981 OutsideOfTemplateParamDC = OuterCtx;
982
Douglas Gregorea166062010-03-15 15:26:48 +0000983 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000984 // We do not directly look into transparent contexts, since
985 // those entities will be found in the nearest enclosing
986 // non-transparent context.
987 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000988 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000989
990 // We do not look directly into function or method contexts,
991 // since all of the local variables and parameters of the
992 // function/method are present within the Scope.
993 if (Ctx->isFunctionOrMethod()) {
994 // If we have an Objective-C instance method, look for ivars
995 // in the corresponding interface.
996 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
997 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
998 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
999 ObjCInterfaceDecl *ClassDeclared;
1000 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001001 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +00001002 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001003 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1004 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +00001005 R.resolveKind();
1006 return true;
1007 }
1008 }
1009 }
1010 }
1011
1012 continue;
1013 }
1014
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001015 // If this is a file context, we need to perform unqualified name
1016 // lookup considering using directives.
1017 if (Ctx->isFileContext()) {
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001018 // If we haven't handled using directives yet, do so now.
1019 if (!VisitedUsingDirectives) {
1020 // Add using directives from this context up to the top level.
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001021 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1022 if (UCtx->isTransparentContext())
1023 continue;
1024
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001025 UDirs.visit(UCtx, UCtx);
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001026 }
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001027
1028 // Find the innermost file scope, so we can add using directives
1029 // from local scopes.
1030 Scope *InnermostFileScope = S;
1031 while (InnermostFileScope &&
1032 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1033 InnermostFileScope = InnermostFileScope->getParent();
1034 UDirs.visitScopeChain(Initial, InnermostFileScope);
1035
1036 UDirs.done();
1037
1038 VisitedUsingDirectives = true;
1039 }
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001040
1041 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1042 R.resolveKind();
1043 return true;
1044 }
1045
1046 continue;
1047 }
1048
Douglas Gregor7f737c02009-09-10 16:57:35 +00001049 // Perform qualified name lookup into this context.
1050 // FIXME: In some cases, we know that every name that could be found by
1051 // this qualified name lookup will also be on the identifier chain. For
1052 // example, inside a class without any base classes, we never need to
1053 // perform qualified lookup because all of the members are on top of the
1054 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001055 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +00001056 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +00001057 }
Douglas Gregor700792c2009-02-05 19:25:20 +00001058 }
Douglas Gregored8f2882009-01-30 01:04:22 +00001059 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001060
John McCallf6c8a4e2009-11-10 07:01:13 +00001061 // Stop if we ran out of scopes.
1062 // FIXME: This really, really shouldn't be happening.
1063 if (!S) return false;
1064
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001065 // If we are looking for members, no need to look into global/namespace scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00001066 if (NameKind == LookupMemberName)
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001067 return false;
1068
Douglas Gregor700792c2009-02-05 19:25:20 +00001069 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +00001070 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +00001071 //
Mike Stump87c57ac2009-05-16 07:39:55 +00001072 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1073 // don't build it for each lookup!
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001074 if (!VisitedUsingDirectives) {
1075 UDirs.visitScopeChain(Initial, S);
1076 UDirs.done();
1077 }
Richard Smith541b38b2013-09-20 01:15:31 +00001078
1079 // If we're not performing redeclaration lookup, do not look for local
1080 // extern declarations outside of a function scope.
1081 if (!R.isForRedeclaration())
1082 FindLocals.restore();
1083
Douglas Gregor700792c2009-02-05 19:25:20 +00001084 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +00001085 // Unqualified name lookup in C++ requires looking into scopes
1086 // that aren't strictly lexical, and therefore we walk through the
1087 // context as well as walking through the scopes.
1088 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001089 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +00001090 bool Found = false;
John McCall48871652010-08-21 09:40:31 +00001091 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001092 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001093 // We found something. Look for anything else in our scope
1094 // with this same name and in an acceptable identifier
1095 // namespace, so that we can construct an overload set if we
1096 // need to.
John McCall9f3059a2009-10-09 21:13:30 +00001097 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +00001098 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001099 }
1100 }
1101
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001102 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +00001103 R.resolveKind();
1104 return true;
1105 }
1106
Ted Kremenekc37877d2013-10-08 17:08:03 +00001107 DeclContext *Ctx = S->getEntity();
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001108 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1109 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1110 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001111 // found nothing, so look into the contexts between the
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001112 // lexical and semantic declaration contexts returned by
1113 // findOuterContext(). This implements the name lookup behavior
1114 // of C++ [temp.local]p8.
1115 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +00001116 OutsideOfTemplateParamDC = nullptr;
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001117 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001118
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001119 if (Ctx) {
1120 DeclContext *OuterCtx;
1121 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001122 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001123 if (SearchAfterTemplateScope)
1124 OutsideOfTemplateParamDC = OuterCtx;
1125
1126 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1127 // We do not directly look into transparent contexts, since
1128 // those entities will be found in the nearest enclosing
1129 // non-transparent context.
1130 if (Ctx->isTransparentContext())
1131 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001132
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001133 // If we have a context, and it's not a context stashed in the
1134 // template parameter scope for an out-of-line definition, also
1135 // look into that context.
1136 if (!(Found && S && S->isTemplateParamScope())) {
1137 assert(Ctx->isFileContext() &&
1138 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001139
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001140 // Look into context considering using-directives.
1141 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1142 Found = true;
1143 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001144
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001145 if (Found) {
1146 R.resolveKind();
1147 return true;
1148 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001149
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001150 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1151 return false;
1152 }
1153 }
1154
Douglas Gregor3ce74932010-02-05 07:07:10 +00001155 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001156 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001157 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001158
John McCall9f3059a2009-10-09 21:13:30 +00001159 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001160}
1161
Richard Smith0e5d7b82013-07-25 23:08:39 +00001162/// \brief Find the declaration that a class temploid member specialization was
1163/// instantiated from, or the member itself if it is an explicit specialization.
1164static Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) {
1165 return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom();
1166}
1167
1168/// \brief Find the module in which the given declaration was defined.
1169static Module *getDefiningModule(Decl *Entity) {
1170 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1171 // If this function was instantiated from a template, the defining module is
1172 // the module containing the pattern.
1173 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1174 Entity = Pattern;
1175 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
Reid Klecknere7367d62014-10-14 20:28:40 +00001176 if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
1177 Entity = Pattern;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001178 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1179 if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo())
1180 Entity = getInstantiatedFrom(ED, MSInfo);
1181 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1182 // FIXME: Map from variable template specializations back to the template.
1183 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo())
1184 Entity = getInstantiatedFrom(VD, MSInfo);
1185 }
1186
1187 // Walk up to the containing context. That might also have been instantiated
1188 // from a template.
1189 DeclContext *Context = Entity->getDeclContext();
1190 if (Context->isFileContext())
1191 return Entity->getOwningModule();
1192 return getDefiningModule(cast<Decl>(Context));
1193}
1194
1195llvm::DenseSet<Module*> &Sema::getLookupModules() {
1196 unsigned N = ActiveTemplateInstantiations.size();
1197 for (unsigned I = ActiveTemplateInstantiationLookupModules.size();
1198 I != N; ++I) {
1199 Module *M = getDefiningModule(ActiveTemplateInstantiations[I].Entity);
1200 if (M && !LookupModulesCache.insert(M).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00001201 M = nullptr;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001202 ActiveTemplateInstantiationLookupModules.push_back(M);
1203 }
1204 return LookupModulesCache;
1205}
1206
1207/// \brief Determine whether a declaration is visible to name lookup.
1208///
1209/// This routine determines whether the declaration D is visible in the current
1210/// lookup context, taking into account the current template instantiation
1211/// stack. During template instantiation, a declaration is visible if it is
1212/// visible from a module containing any entity on the template instantiation
1213/// path (by instantiating a template, you allow it to see the declarations that
1214/// your module can see, including those later on in your module).
1215bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
1216 assert(D->isHidden() && !SemaRef.ActiveTemplateInstantiations.empty() &&
1217 "should not call this: not in slow case");
1218 Module *DeclModule = D->getOwningModule();
1219 assert(DeclModule && "hidden decl not from a module");
1220
1221 // Find the extra places where we need to look.
1222 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
1223 if (LookupModules.empty())
1224 return false;
1225
1226 // If our lookup set contains the decl's module, it's visible.
1227 if (LookupModules.count(DeclModule))
1228 return true;
1229
1230 // If the declaration isn't exported, it's not visible in any other module.
1231 if (D->isModulePrivate())
1232 return false;
1233
1234 // Check whether DeclModule is transitively exported to an import of
1235 // the lookup set.
1236 for (llvm::DenseSet<Module *>::iterator I = LookupModules.begin(),
1237 E = LookupModules.end();
1238 I != E; ++I)
1239 if ((*I)->isModuleVisible(DeclModule))
1240 return true;
1241 return false;
1242}
1243
Douglas Gregor4a814562011-12-14 16:03:29 +00001244/// \brief Retrieve the visible declaration corresponding to D, if any.
1245///
1246/// This routine determines whether the declaration D is visible in the current
1247/// module, with the current imports. If not, it checks whether any
1248/// redeclaration of D is visible, and if so, returns that declaration.
Richard Smith0e5d7b82013-07-25 23:08:39 +00001249///
Douglas Gregor4a814562011-12-14 16:03:29 +00001250/// \returns D, or a visible previous declaration of D, whichever is more recent
1251/// and visible. If no declaration of D is visible, returns null.
Richard Smithe156254d2013-08-20 20:35:18 +00001252static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
1253 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
Richard Smith0e5d7b82013-07-25 23:08:39 +00001254
Aaron Ballman86c93902014-03-06 23:45:36 +00001255 for (auto RD : D->redecls()) {
1256 if (auto ND = dyn_cast<NamedDecl>(RD)) {
Richard Smithe156254d2013-08-20 20:35:18 +00001257 if (LookupResult::isVisible(SemaRef, ND))
Douglas Gregor54079202012-01-06 22:05:37 +00001258 return ND;
1259 }
Douglas Gregor4a814562011-12-14 16:03:29 +00001260 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001261
Craig Topperc3ec1492014-05-26 06:22:03 +00001262 return nullptr;
Douglas Gregor4a814562011-12-14 16:03:29 +00001263}
1264
Richard Smithe156254d2013-08-20 20:35:18 +00001265NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +00001266 return findAcceptableDecl(getSema(), D);
Richard Smithe156254d2013-08-20 20:35:18 +00001267}
1268
Douglas Gregor34074322009-01-14 22:20:51 +00001269/// @brief Perform unqualified name lookup starting from a given
1270/// scope.
1271///
1272/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1273/// used to find names within the current scope. For example, 'x' in
1274/// @code
1275/// int x;
1276/// int f() {
1277/// return x; // unqualified name look finds 'x' in the global scope
1278/// }
1279/// @endcode
1280///
1281/// Different lookup criteria can find different names. For example, a
1282/// particular scope can have both a struct and a function of the same
1283/// name, and each can be found by certain lookup criteria. For more
1284/// information about lookup criteria, see the documentation for the
1285/// class LookupCriteria.
1286///
1287/// @param S The scope from which unqualified name lookup will
1288/// begin. If the lookup criteria permits, name lookup may also search
1289/// in the parent scopes.
1290///
James Dennett91738ff2012-06-22 10:32:46 +00001291/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1292/// look up and the lookup kind), and is updated with the results of lookup
1293/// including zero or more declarations and possibly additional information
1294/// used to diagnose ambiguities.
Douglas Gregor34074322009-01-14 22:20:51 +00001295///
James Dennett91738ff2012-06-22 10:32:46 +00001296/// @returns \c true if lookup succeeded and false otherwise.
John McCall27b18f82009-11-17 02:14:36 +00001297bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1298 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001299 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001300
John McCall27b18f82009-11-17 02:14:36 +00001301 LookupNameKind NameKind = R.getLookupKind();
1302
David Blaikiebbafb8a2012-03-11 07:00:24 +00001303 if (!getLangOpts().CPlusPlus) {
Douglas Gregor34074322009-01-14 22:20:51 +00001304 // Unqualified name lookup in C/Objective-C is purely lexical, so
1305 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001306 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001307 // Find the nearest non-transparent declaration scope.
1308 while (!(S->getFlags() & Scope::DeclScope) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001309 (S->getEntity() && S->getEntity()->isTransparentContext()))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001310 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001311 }
1312
Richard Smith541b38b2013-09-20 01:15:31 +00001313 // When performing a scope lookup, we want to find local extern decls.
1314 FindLocalExternScope FindLocals(R);
1315
Douglas Gregor34074322009-01-14 22:20:51 +00001316 // Scan up the scope chain looking for a decl that matches this
1317 // identifier that is in the appropriate namespace. This search
1318 // should not take long, as shadowing of names is uncommon, and
1319 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001320 bool LeftStartingScope = false;
1321
Douglas Gregored8f2882009-01-30 01:04:22 +00001322 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001323 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001324 I != IEnd; ++I)
Richard Smith0e5d7b82013-07-25 23:08:39 +00001325 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001326 if (NameKind == LookupRedeclarationWithLinkage) {
1327 // Determine whether this (or a previous) declaration is
1328 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001329 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001330 LeftStartingScope = true;
1331
1332 // If we found something outside of our starting scope that
1333 // does not have linkage, skip it.
Richard Smith1c34fb72013-08-13 18:18:50 +00001334 if (LeftStartingScope && !((*I)->hasLinkage())) {
1335 R.setShadowed();
Douglas Gregoreddf4332009-02-24 20:03:32 +00001336 continue;
Richard Smith1c34fb72013-08-13 18:18:50 +00001337 }
Douglas Gregoreddf4332009-02-24 20:03:32 +00001338 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001339 else if (NameKind == LookupObjCImplicitSelfParam &&
1340 !isa<ImplicitParamDecl>(*I))
1341 continue;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001342
Douglas Gregor4a814562011-12-14 16:03:29 +00001343 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001344
Douglas Gregorb59643b2012-01-03 23:26:26 +00001345 // Check whether there are any other declarations with the same name
1346 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001347 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001348 // Find the scope in which this declaration was declared (if it
1349 // actually exists in a Scope).
1350 while (S && !S->isDeclScope(D))
1351 S = S->getParent();
1352
1353 // If the scope containing the declaration is the translation unit,
1354 // then we'll need to perform our checks based on the matching
1355 // DeclContexts rather than matching scopes.
1356 if (S && isNamespaceOrTranslationUnitScope(S))
Craig Topperc3ec1492014-05-26 06:22:03 +00001357 S = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001358
1359 // Compute the DeclContext, if we need it.
Craig Topperc3ec1492014-05-26 06:22:03 +00001360 DeclContext *DC = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001361 if (!S)
1362 DC = (*I)->getDeclContext()->getRedeclContext();
1363
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001364 IdentifierResolver::iterator LastI = I;
1365 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001366 if (S) {
1367 // Match based on scope.
1368 if (!S->isDeclScope(*LastI))
1369 break;
1370 } else {
1371 // Match based on DeclContext.
1372 DeclContext *LastDC
1373 = (*LastI)->getDeclContext()->getRedeclContext();
1374 if (!LastDC->Equals(DC))
1375 break;
1376 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001377
1378 // If the declaration is in the right namespace and visible, add it.
1379 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1380 R.addDecl(LastD);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001381 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001382
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001383 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001384 }
Richard Smith541b38b2013-09-20 01:15:31 +00001385
John McCall9f3059a2009-10-09 21:13:30 +00001386 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001387 }
Douglas Gregor34074322009-01-14 22:20:51 +00001388 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001389 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001390 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001391 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001392 }
1393
1394 // If we didn't find a use of this identifier, and if the identifier
1395 // corresponds to a compiler builtin, create the decl object for the builtin
1396 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001397 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1398 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001399
Axel Naumann016538a2011-02-24 16:47:47 +00001400 // If we didn't find a use of this identifier, the ExternalSource
1401 // may be able to handle the situation.
1402 // Note: some lookup failures are expected!
1403 // See e.g. R.isForRedeclaration().
1404 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001405}
1406
John McCall6538c932009-10-10 05:48:19 +00001407/// @brief Perform qualified name lookup in the namespaces nominated by
1408/// using directives by the given context.
1409///
1410/// C++98 [namespace.qual]p2:
James Dennett51a8d8b2012-06-19 21:05:49 +00001411/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6538c932009-10-10 05:48:19 +00001412/// (where X is the global namespace), let S be the set of all
1413/// declarations of m in X and in the transitive closure of all
1414/// namespaces nominated by using-directives in X and its used
1415/// namespaces, except that using-directives are ignored in any
1416/// namespace, including X, directly containing one or more
1417/// declarations of m. No namespace is searched more than once in
1418/// the lookup of a name. If S is the empty set, the program is
1419/// ill-formed. Otherwise, if S has exactly one member, or if the
1420/// context of the reference is a using-declaration
1421/// (namespace.udecl), S is the required set of declarations of
1422/// m. Otherwise if the use of m is not one that allows a unique
1423/// declaration to be chosen from S, the program is ill-formed.
James Dennett51a8d8b2012-06-19 21:05:49 +00001424///
John McCall6538c932009-10-10 05:48:19 +00001425/// C++98 [namespace.qual]p5:
1426/// During the lookup of a qualified namespace member name, if the
1427/// lookup finds more than one declaration of the member, and if one
1428/// declaration introduces a class name or enumeration name and the
1429/// other declarations either introduce the same object, the same
1430/// enumerator or a set of functions, the non-type name hides the
1431/// class or enumeration name if and only if the declarations are
1432/// from the same namespace; otherwise (the declarations are from
1433/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001434static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001435 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001436 assert(StartDC->isFileContext() && "start context is not a file context");
1437
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001438 DeclContext::udir_range UsingDirectives = StartDC->using_directives();
1439 if (UsingDirectives.begin() == UsingDirectives.end()) return false;
John McCall6538c932009-10-10 05:48:19 +00001440
1441 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001442 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001443 Visited.insert(StartDC);
1444
1445 // We have not yet looked into these namespaces, much less added
1446 // their "using-children" to the queue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001447 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001448
1449 // We have already looked into the initial namespace; seed the queue
1450 // with its using-children.
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001451 for (auto *I : UsingDirectives) {
1452 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +00001453 if (Visited.insert(ND).second)
John McCall6538c932009-10-10 05:48:19 +00001454 Queue.push_back(ND);
1455 }
1456
1457 // The easiest way to implement the restriction in [namespace.qual]p5
1458 // is to check whether any of the individual results found a tag
1459 // and, if so, to declare an ambiguity if the final result is not
1460 // a tag.
1461 bool FoundTag = false;
1462 bool FoundNonTag = false;
1463
John McCall5cebab12009-11-18 07:57:50 +00001464 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001465
1466 bool Found = false;
1467 while (!Queue.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001468 NamespaceDecl *ND = Queue.pop_back_val();
John McCall6538c932009-10-10 05:48:19 +00001469
1470 // We go through some convolutions here to avoid copying results
1471 // between LookupResults.
1472 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001473 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001474 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001475
1476 if (FoundDirect) {
1477 // First do any local hiding.
1478 DirectR.resolveKind();
1479
1480 // If the local result is a tag, remember that.
1481 if (DirectR.isSingleTagDecl())
1482 FoundTag = true;
1483 else
1484 FoundNonTag = true;
1485
1486 // Append the local results to the total results if necessary.
1487 if (UseLocal) {
1488 R.addAllDecls(LocalR);
1489 LocalR.clear();
1490 }
1491 }
1492
1493 // If we find names in this namespace, ignore its using directives.
1494 if (FoundDirect) {
1495 Found = true;
1496 continue;
1497 }
1498
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001499 for (auto I : ND->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00001500 NamespaceDecl *Nom = I->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +00001501 if (Visited.insert(Nom).second)
John McCall6538c932009-10-10 05:48:19 +00001502 Queue.push_back(Nom);
1503 }
1504 }
1505
1506 if (Found) {
1507 if (FoundTag && FoundNonTag)
1508 R.setAmbiguousQualifiedTagHiding();
1509 else
1510 R.resolveKind();
1511 }
1512
1513 return Found;
1514}
1515
Douglas Gregor39982192010-08-15 06:18:01 +00001516/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001517static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor39982192010-08-15 06:18:01 +00001518 CXXBasePath &Path,
1519 void *Name) {
1520 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001521
Douglas Gregor39982192010-08-15 06:18:01 +00001522 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1523 Path.Decls = BaseRecord->lookup(N);
David Blaikieff7d47a2012-12-19 00:45:41 +00001524 return !Path.Decls.empty();
Douglas Gregor39982192010-08-15 06:18:01 +00001525}
1526
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001527/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001528/// static members, nested types, and enumerators.
1529template<typename InputIterator>
1530static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1531 Decl *D = (*First)->getUnderlyingDecl();
1532 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1533 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001534
Douglas Gregorc0d24902010-10-22 22:08:47 +00001535 if (isa<CXXMethodDecl>(D)) {
1536 // Determine whether all of the methods are static.
1537 bool AllMethodsAreStatic = true;
1538 for(; First != Last; ++First) {
1539 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001540
Douglas Gregorc0d24902010-10-22 22:08:47 +00001541 if (!isa<CXXMethodDecl>(D)) {
1542 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1543 break;
1544 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001545
Douglas Gregorc0d24902010-10-22 22:08:47 +00001546 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1547 AllMethodsAreStatic = false;
1548 break;
1549 }
1550 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001551
Douglas Gregorc0d24902010-10-22 22:08:47 +00001552 if (AllMethodsAreStatic)
1553 return true;
1554 }
1555
1556 return false;
1557}
1558
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001559/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001560///
1561/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1562/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001563/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001564///
1565/// Different lookup criteria can find different names. For example, a
1566/// particular scope can have both a struct and a function of the same
1567/// name, and each can be found by certain lookup criteria. For more
1568/// information about lookup criteria, see the documentation for the
1569/// class LookupCriteria.
1570///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001571/// \param R captures both the lookup criteria and any lookup results found.
1572///
1573/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001574/// search. If the lookup criteria permits, name lookup may also search
1575/// in the parent contexts or (for C++ classes) base classes.
1576///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001577/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001578/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001579///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001580/// \returns true if lookup succeeded, false if it failed.
1581bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1582 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001583 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001584
John McCall27b18f82009-11-17 02:14:36 +00001585 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001586 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001587
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001588 // Make sure that the declaration context is complete.
1589 assert((!isa<TagDecl>(LookupCtx) ||
1590 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00001591 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith7d137e32012-03-23 03:33:32 +00001592 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001593 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001594
Douglas Gregor34074322009-01-14 22:20:51 +00001595 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001596 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001597 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001598 if (isa<CXXRecordDecl>(LookupCtx))
1599 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001600 return true;
1601 }
Douglas Gregor34074322009-01-14 22:20:51 +00001602
John McCall6538c932009-10-10 05:48:19 +00001603 // Don't descend into implied contexts for redeclarations.
1604 // C++98 [namespace.qual]p6:
1605 // In a declaration for a namespace member in which the
1606 // declarator-id is a qualified-id, given that the qualified-id
1607 // for the namespace member has the form
1608 // nested-name-specifier unqualified-id
1609 // the unqualified-id shall name a member of the namespace
1610 // designated by the nested-name-specifier.
1611 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001612 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001613 return false;
1614
John McCall27b18f82009-11-17 02:14:36 +00001615 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001616 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001617 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001618
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001619 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001620 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001621 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001622 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001623 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001624
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001625 // If we're performing qualified name lookup into a dependent class,
1626 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001627 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001628 // template instantiation time (at which point all bases will be available)
1629 // or we have to fail.
1630 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1631 LookupRec->hasAnyDependentBases()) {
1632 R.setNotFoundInCurrentInstantiation();
1633 return false;
1634 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001635
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001636 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001637 CXXBasePaths Paths;
1638 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001639
1640 // Look for this member in our base classes
Craig Topperc3ec1492014-05-26 06:22:03 +00001641 CXXRecordDecl::BaseMatchesCallback *BaseCallback = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00001642 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001643 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001644 case LookupOrdinaryName:
1645 case LookupMemberName:
1646 case LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +00001647 case LookupLocalFriendName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001648 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1649 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001650
Douglas Gregor36d1b142009-10-06 17:59:45 +00001651 case LookupTagName:
1652 BaseCallback = &CXXRecordDecl::FindTagMember;
1653 break;
John McCall84d87672009-12-10 09:41:52 +00001654
Douglas Gregor39982192010-08-15 06:18:01 +00001655 case LookupAnyName:
1656 BaseCallback = &LookupAnyMember;
1657 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001658
John McCall84d87672009-12-10 09:41:52 +00001659 case LookupUsingDeclName:
1660 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001661
Douglas Gregor36d1b142009-10-06 17:59:45 +00001662 case LookupOperatorName:
1663 case LookupNamespaceName:
1664 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001665 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001666 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001667 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001668
Douglas Gregor36d1b142009-10-06 17:59:45 +00001669 case LookupNestedNameSpecifierName:
1670 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1671 break;
1672 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001673
John McCall27b18f82009-11-17 02:14:36 +00001674 if (!LookupRec->lookupInBases(BaseCallback,
1675 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001676 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001677
John McCall553c0792010-01-23 00:46:32 +00001678 R.setNamingClass(LookupRec);
1679
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001680 // C++ [class.member.lookup]p2:
1681 // [...] If the resulting set of declarations are not all from
1682 // sub-objects of the same type, or the set has a nonstatic member
1683 // and includes members from distinct sub-objects, there is an
1684 // ambiguity and the program is ill-formed. Otherwise that set is
1685 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001686 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001687 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001688 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001689
Douglas Gregor36d1b142009-10-06 17:59:45 +00001690 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001691 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001692 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001693
John McCall401982f2010-01-20 21:53:11 +00001694 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1695 // across all paths.
1696 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001697
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001698 // Determine whether we're looking at a distinct sub-object or not.
1699 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001700 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001701 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1702 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001703 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001704 }
1705
Douglas Gregorc0d24902010-10-22 22:08:47 +00001706 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001707 != Context.getCanonicalType(PathElement.Base->getType())) {
1708 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001709 // different types. If the declaration sets aren't the same, this
Nikola Smiljanic1c125682014-07-09 05:42:35 +00001710 // lookup is ambiguous.
David Blaikieff7d47a2012-12-19 00:45:41 +00001711 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00001712 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikieff7d47a2012-12-19 00:45:41 +00001713 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
1714 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001715
David Blaikieff7d47a2012-12-19 00:45:41 +00001716 while (FirstD != FirstPath->Decls.end() &&
1717 CurrentD != Path->Decls.end()) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00001718 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1719 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1720 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001721
Douglas Gregorc0d24902010-10-22 22:08:47 +00001722 ++FirstD;
1723 ++CurrentD;
1724 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001725
David Blaikieff7d47a2012-12-19 00:45:41 +00001726 if (FirstD == FirstPath->Decls.end() &&
1727 CurrentD == Path->Decls.end())
Douglas Gregorc0d24902010-10-22 22:08:47 +00001728 continue;
1729 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001730
John McCall9f3059a2009-10-09 21:13:30 +00001731 R.setAmbiguousBaseSubobjectTypes(Paths);
1732 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001733 }
1734
Douglas Gregorc0d24902010-10-22 22:08:47 +00001735 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001736 // We have a different subobject of the same type.
1737
1738 // C++ [class.member.lookup]p5:
1739 // A static member, a nested type or an enumerator defined in
1740 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001741 // has more than one base class subobject of type T.
David Blaikieff7d47a2012-12-19 00:45:41 +00001742 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001743 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001744
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001745 // We have found a nonstatic member name in multiple, distinct
1746 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001747 R.setAmbiguousBaseSubobjects(Paths);
1748 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001749 }
1750 }
1751
1752 // Lookup in a base class succeeded; return these results.
1753
Aaron Ballman1e606f42014-07-15 22:03:49 +00001754 for (auto *D : Paths.front().Decls) {
John McCall553c0792010-01-23 00:46:32 +00001755 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1756 D->getAccess());
1757 R.addDecl(D, AS);
1758 }
John McCall9f3059a2009-10-09 21:13:30 +00001759 R.resolveKind();
1760 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001761}
1762
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00001763/// \brief Performs qualified name lookup or special type of lookup for
1764/// "__super::" scope specifier.
1765///
1766/// This routine is a convenience overload meant to be called from contexts
1767/// that need to perform a qualified name lookup with an optional C++ scope
1768/// specifier that might require special kind of lookup.
1769///
1770/// \param R captures both the lookup criteria and any lookup results found.
1771///
1772/// \param LookupCtx The context in which qualified name lookup will
1773/// search.
1774///
1775/// \param SS An optional C++ scope-specifier.
1776///
1777/// \returns true if lookup succeeded, false if it failed.
1778bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1779 CXXScopeSpec &SS) {
1780 auto *NNS = SS.getScopeRep();
1781 if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
1782 return LookupInSuper(R, NNS->getAsRecordDecl());
1783 else
1784
1785 return LookupQualifiedName(R, LookupCtx);
1786}
1787
Douglas Gregor34074322009-01-14 22:20:51 +00001788/// @brief Performs name lookup for a name that was parsed in the
1789/// source code, and may contain a C++ scope specifier.
1790///
1791/// This routine is a convenience routine meant to be called from
1792/// contexts that receive a name and an optional C++ scope specifier
1793/// (e.g., "N::M::x"). It will then perform either qualified or
1794/// unqualified name lookup (with LookupQualifiedName or LookupName,
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00001795/// respectively) on the given name and return those results. It will
1796/// perform a special type of lookup for "__super::" scope specifier.
Douglas Gregor34074322009-01-14 22:20:51 +00001797///
1798/// @param S The scope from which unqualified name lookup will
1799/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001800///
Douglas Gregore861bac2009-08-25 22:51:20 +00001801/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001802///
Douglas Gregore861bac2009-08-25 22:51:20 +00001803/// @param EnteringContext Indicates whether we are going to enter the
1804/// context of the scope-specifier SS (if present).
1805///
John McCall9f3059a2009-10-09 21:13:30 +00001806/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001807bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001808 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001809 if (SS && SS->isInvalid()) {
1810 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001811 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001812 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001813 }
Mike Stump11289f42009-09-09 15:08:12 +00001814
Douglas Gregore861bac2009-08-25 22:51:20 +00001815 if (SS && SS->isSet()) {
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00001816 NestedNameSpecifier *NNS = SS->getScopeRep();
1817 if (NNS->getKind() == NestedNameSpecifier::Super)
1818 return LookupInSuper(R, NNS->getAsRecordDecl());
1819
Douglas Gregore861bac2009-08-25 22:51:20 +00001820 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001821 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001822 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001823 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001824 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001825
John McCall27b18f82009-11-17 02:14:36 +00001826 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00001827 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001828 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001829
Douglas Gregore861bac2009-08-25 22:51:20 +00001830 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001831 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001832 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00001833 R.setNotFoundInCurrentInstantiation();
1834 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00001835 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001836 }
1837
Mike Stump11289f42009-09-09 15:08:12 +00001838 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001839 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001840}
1841
Nikola Smiljanic67860242014-09-26 00:28:20 +00001842/// \brief Perform qualified name lookup into all base classes of the given
1843/// class.
1844///
1845/// \param R captures both the lookup criteria and any lookup results found.
1846///
1847/// \param Class The context in which qualified name lookup will
1848/// search. Name lookup will search in all base classes merging the results.
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00001849///
1850/// @returns True if any decls were found (but possibly ambiguous)
1851bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
Nikola Smiljanic67860242014-09-26 00:28:20 +00001852 for (const auto &BaseSpec : Class->bases()) {
1853 CXXRecordDecl *RD = cast<CXXRecordDecl>(
1854 BaseSpec.getType()->castAs<RecordType>()->getDecl());
1855 LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
1856 Result.setBaseObjectType(Context.getRecordType(Class));
1857 LookupQualifiedName(Result, RD);
1858 for (auto *Decl : Result)
1859 R.addDecl(Decl);
1860 }
1861
1862 R.resolveKind();
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00001863
1864 return !R.empty();
Nikola Smiljanic67860242014-09-26 00:28:20 +00001865}
Douglas Gregor889ceb72009-02-03 19:21:40 +00001866
James Dennett41725122012-06-22 10:16:05 +00001867/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001868/// from name lookup.
1869///
James Dennett41725122012-06-22 10:16:05 +00001870/// \param Result The result of the ambiguous lookup to be diagnosed.
Serge Pavlov99292092013-08-29 07:23:24 +00001871void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001872 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1873
John McCall27b18f82009-11-17 02:14:36 +00001874 DeclarationName Name = Result.getLookupName();
1875 SourceLocation NameLoc = Result.getNameLoc();
1876 SourceRange LookupRange = Result.getContextRange();
1877
John McCall6538c932009-10-10 05:48:19 +00001878 switch (Result.getAmbiguityKind()) {
1879 case LookupResult::AmbiguousBaseSubobjects: {
1880 CXXBasePaths *Paths = Result.getBasePaths();
1881 QualType SubobjectType = Paths->front().back().Base->getType();
1882 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1883 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1884 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001885
David Blaikieff7d47a2012-12-19 00:45:41 +00001886 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6538c932009-10-10 05:48:19 +00001887 while (isa<CXXMethodDecl>(*Found) &&
1888 cast<CXXMethodDecl>(*Found)->isStatic())
1889 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001890
John McCall6538c932009-10-10 05:48:19 +00001891 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
Serge Pavlov99292092013-08-29 07:23:24 +00001892 break;
John McCall6538c932009-10-10 05:48:19 +00001893 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001894
John McCall6538c932009-10-10 05:48:19 +00001895 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001896 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1897 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001898
John McCall6538c932009-10-10 05:48:19 +00001899 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001900 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001901 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1902 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001903 Path != PathEnd; ++Path) {
David Blaikieff7d47a2012-12-19 00:45:41 +00001904 Decl *D = Path->Decls.front();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001905 if (DeclsPrinted.insert(D).second)
1906 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1907 }
Serge Pavlov99292092013-08-29 07:23:24 +00001908 break;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001909 }
1910
John McCall6538c932009-10-10 05:48:19 +00001911 case LookupResult::AmbiguousTagHiding: {
1912 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001913
John McCall6538c932009-10-10 05:48:19 +00001914 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1915
Aaron Ballman1e606f42014-07-15 22:03:49 +00001916 for (auto *D : Result)
1917 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
John McCall6538c932009-10-10 05:48:19 +00001918 TagDecls.insert(TD);
1919 Diag(TD->getLocation(), diag::note_hidden_tag);
1920 }
1921
Aaron Ballman1e606f42014-07-15 22:03:49 +00001922 for (auto *D : Result)
1923 if (!isa<TagDecl>(D))
1924 Diag(D->getLocation(), diag::note_hiding_object);
John McCall6538c932009-10-10 05:48:19 +00001925
1926 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001927 LookupResult::Filter F = Result.makeFilter();
1928 while (F.hasNext()) {
1929 if (TagDecls.count(F.next()))
1930 F.erase();
1931 }
1932 F.done();
Serge Pavlov99292092013-08-29 07:23:24 +00001933 break;
John McCall6538c932009-10-10 05:48:19 +00001934 }
1935
1936 case LookupResult::AmbiguousReference: {
1937 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001938
Aaron Ballman1e606f42014-07-15 22:03:49 +00001939 for (auto *D : Result)
1940 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
Serge Pavlov99292092013-08-29 07:23:24 +00001941 break;
John McCall6538c932009-10-10 05:48:19 +00001942 }
Serge Pavlov99292092013-08-29 07:23:24 +00001943 }
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001944}
Douglas Gregore254f902009-02-04 00:32:51 +00001945
John McCallf24d7bb2010-05-28 18:45:08 +00001946namespace {
1947 struct AssociatedLookup {
John McCall7d8b0412012-08-24 20:38:34 +00001948 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallf24d7bb2010-05-28 18:45:08 +00001949 Sema::AssociatedNamespaceSet &Namespaces,
1950 Sema::AssociatedClassSet &Classes)
John McCall7d8b0412012-08-24 20:38:34 +00001951 : S(S), Namespaces(Namespaces), Classes(Classes),
1952 InstantiationLoc(InstantiationLoc) {
John McCallf24d7bb2010-05-28 18:45:08 +00001953 }
1954
1955 Sema &S;
1956 Sema::AssociatedNamespaceSet &Namespaces;
1957 Sema::AssociatedClassSet &Classes;
John McCall7d8b0412012-08-24 20:38:34 +00001958 SourceLocation InstantiationLoc;
John McCallf24d7bb2010-05-28 18:45:08 +00001959 };
1960}
1961
Mike Stump11289f42009-09-09 15:08:12 +00001962static void
John McCallf24d7bb2010-05-28 18:45:08 +00001963addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001964
Douglas Gregor8b895222010-04-30 07:08:38 +00001965static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1966 DeclContext *Ctx) {
1967 // Add the associated namespace for this class.
1968
1969 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1970 // be a locally scoped record.
1971
Sebastian Redlbd595762010-08-31 20:53:31 +00001972 // We skip out of inline namespaces. The innermost non-inline namespace
1973 // contains all names of all its nested inline namespaces anyway, so we can
1974 // replace the entire inline namespace tree with its root.
1975 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1976 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00001977 Ctx = Ctx->getParent();
1978
John McCallc7e8e792009-08-07 22:18:02 +00001979 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001980 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001981}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001982
Mike Stump11289f42009-09-09 15:08:12 +00001983// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001984// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001985static void
John McCallf24d7bb2010-05-28 18:45:08 +00001986addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1987 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001988 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001989 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001990 switch (Arg.getKind()) {
1991 case TemplateArgument::Null:
1992 break;
Mike Stump11289f42009-09-09 15:08:12 +00001993
Douglas Gregor197e5f72009-07-08 07:51:57 +00001994 case TemplateArgument::Type:
1995 // [...] the namespaces and classes associated with the types of the
1996 // template arguments provided for template type parameters (excluding
1997 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001998 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001999 break;
Mike Stump11289f42009-09-09 15:08:12 +00002000
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002001 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002002 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00002003 // [...] the namespaces in which any template template arguments are
2004 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00002005 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002006 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00002007 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002008 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002009 DeclContext *Ctx = ClassTemplate->getDeclContext();
2010 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002011 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002012 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002013 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002014 }
2015 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002016 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002017
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002018 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00002019 case TemplateArgument::Integral:
2020 case TemplateArgument::Expression:
Eli Friedmanb826a002012-09-26 02:36:12 +00002021 case TemplateArgument::NullPtr:
Mike Stump11289f42009-09-09 15:08:12 +00002022 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00002023 // associated namespaces. ]
2024 break;
Mike Stump11289f42009-09-09 15:08:12 +00002025
Douglas Gregor197e5f72009-07-08 07:51:57 +00002026 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00002027 for (const auto &P : Arg.pack_elements())
2028 addAssociatedClassesAndNamespaces(Result, P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002029 break;
2030 }
2031}
2032
Douglas Gregore254f902009-02-04 00:32:51 +00002033// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00002034// argument-dependent lookup with an argument of class type
2035// (C++ [basic.lookup.koenig]p2).
2036static void
John McCallf24d7bb2010-05-28 18:45:08 +00002037addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2038 CXXRecordDecl *Class) {
2039
2040 // Just silently ignore anything whose name is __va_list_tag.
2041 if (Class->getDeclName() == Result.S.VAListTagName)
2042 return;
2043
Douglas Gregore254f902009-02-04 00:32:51 +00002044 // C++ [basic.lookup.koenig]p2:
2045 // [...]
2046 // -- If T is a class type (including unions), its associated
2047 // classes are: the class itself; the class of which it is a
2048 // member, if any; and its direct and indirect base
2049 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00002050 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00002051
2052 // Add the class of which it is a member, if any.
2053 DeclContext *Ctx = Class->getDeclContext();
2054 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002055 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002056 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002057 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002058
Douglas Gregore254f902009-02-04 00:32:51 +00002059 // Add the class itself. If we've already seen this class, we don't
2060 // need to visit base classes.
Richard Smith594461f2014-03-14 22:07:27 +00002061 //
2062 // FIXME: That's not correct, we may have added this class only because it
2063 // was the enclosing class of another class, and in that case we won't have
2064 // added its base classes yet.
David Blaikie82e95a32014-11-19 07:49:47 +00002065 if (!Result.Classes.insert(Class).second)
Douglas Gregore254f902009-02-04 00:32:51 +00002066 return;
2067
Mike Stump11289f42009-09-09 15:08:12 +00002068 // -- If T is a template-id, its associated namespaces and classes are
2069 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002070 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00002071 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00002072 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00002073 // namespaces in which any template template arguments are defined; and
2074 // the classes in which any member templates used as template template
2075 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00002076 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00002077 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00002078 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2079 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2080 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002081 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002082 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002083 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002084
Douglas Gregor197e5f72009-07-08 07:51:57 +00002085 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2086 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00002087 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002088 }
Mike Stump11289f42009-09-09 15:08:12 +00002089
John McCall67da35c2010-02-04 22:26:26 +00002090 // Only recurse into base classes for complete types.
Richard Smith594461f2014-03-14 22:07:27 +00002091 if (!Class->hasDefinition())
2092 return;
John McCall67da35c2010-02-04 22:26:26 +00002093
Douglas Gregore254f902009-02-04 00:32:51 +00002094 // Add direct and indirect base classes along with their associated
2095 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002096 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00002097 Bases.push_back(Class);
2098 while (!Bases.empty()) {
2099 // Pop this class off the stack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002100 Class = Bases.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002101
2102 // Visit the base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +00002103 for (const auto &Base : Class->bases()) {
2104 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00002105 // In dependent contexts, we do ADL twice, and the first time around,
2106 // the base type might be a dependent TemplateSpecializationType, or a
2107 // TemplateTypeParmType. If that happens, simply ignore it.
2108 // FIXME: If we want to support export, we probably need to add the
2109 // namespace of the template in a TemplateSpecializationType, or even
2110 // the classes and namespaces of known non-dependent arguments.
2111 if (!BaseType)
2112 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002113 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
David Blaikie82e95a32014-11-19 07:49:47 +00002114 if (Result.Classes.insert(BaseDecl).second) {
Douglas Gregore254f902009-02-04 00:32:51 +00002115 // Find the associated namespace for this base class.
2116 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00002117 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00002118
2119 // Make sure we visit the bases of this base class.
2120 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2121 Bases.push_back(BaseDecl);
2122 }
2123 }
2124 }
2125}
2126
2127// \brief Add the associated classes and namespaces for
2128// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00002129// (C++ [basic.lookup.koenig]p2).
2130static void
John McCallf24d7bb2010-05-28 18:45:08 +00002131addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00002132 // C++ [basic.lookup.koenig]p2:
2133 //
2134 // For each argument type T in the function call, there is a set
2135 // of zero or more associated namespaces and a set of zero or more
2136 // associated classes to be considered. The sets of namespaces and
2137 // classes is determined entirely by the types of the function
2138 // arguments (and the namespace of any template template
2139 // argument). Typedef names and using-declarations used to specify
2140 // the types do not contribute to this set. The sets of namespaces
2141 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00002142
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002143 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00002144 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2145
Douglas Gregore254f902009-02-04 00:32:51 +00002146 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00002147 switch (T->getTypeClass()) {
2148
2149#define TYPE(Class, Base)
2150#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2151#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2152#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2153#define ABSTRACT_TYPE(Class, Base)
2154#include "clang/AST/TypeNodes.def"
2155 // T is canonical. We can also ignore dependent types because
2156 // we don't need to do ADL at the definition point, but if we
2157 // wanted to implement template export (or if we find some other
2158 // use for associated classes and namespaces...) this would be
2159 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00002160 break;
Douglas Gregore254f902009-02-04 00:32:51 +00002161
John McCall0af3d3b2010-05-28 06:08:54 +00002162 // -- If T is a pointer to U or an array of U, its associated
2163 // namespaces and classes are those associated with U.
2164 case Type::Pointer:
2165 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2166 continue;
2167 case Type::ConstantArray:
2168 case Type::IncompleteArray:
2169 case Type::VariableArray:
2170 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2171 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002172
John McCall0af3d3b2010-05-28 06:08:54 +00002173 // -- If T is a fundamental type, its associated sets of
2174 // namespaces and classes are both empty.
2175 case Type::Builtin:
2176 break;
2177
2178 // -- If T is a class type (including unions), its associated
2179 // classes are: the class itself; the class of which it is a
2180 // member, if any; and its direct and indirect base
2181 // classes. Its associated namespaces are the namespaces in
2182 // which its associated classes are defined.
2183 case Type::Record: {
Richard Smith594461f2014-03-14 22:07:27 +00002184 Result.S.RequireCompleteType(Result.InstantiationLoc, QualType(T, 0),
2185 /*no diagnostic*/ 0);
John McCall0af3d3b2010-05-28 06:08:54 +00002186 CXXRecordDecl *Class
2187 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002188 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00002189 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00002190 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00002191
John McCall0af3d3b2010-05-28 06:08:54 +00002192 // -- If T is an enumeration type, its associated namespace is
2193 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002194 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00002195 // it has no associated class.
2196 case Type::Enum: {
2197 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002198
John McCall0af3d3b2010-05-28 06:08:54 +00002199 DeclContext *Ctx = Enum->getDeclContext();
2200 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002201 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002202
John McCall0af3d3b2010-05-28 06:08:54 +00002203 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002204 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00002205
John McCall0af3d3b2010-05-28 06:08:54 +00002206 break;
2207 }
2208
2209 // -- If T is a function type, its associated namespaces and
2210 // classes are those associated with the function parameter
2211 // types and those associated with the return type.
2212 case Type::FunctionProto: {
2213 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002214 for (const auto &Arg : Proto->param_types())
2215 Queue.push_back(Arg.getTypePtr());
John McCall0af3d3b2010-05-28 06:08:54 +00002216 // fallthrough
2217 }
2218 case Type::FunctionNoProto: {
2219 const FunctionType *FnType = cast<FunctionType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00002220 T = FnType->getReturnType().getTypePtr();
John McCall0af3d3b2010-05-28 06:08:54 +00002221 continue;
2222 }
2223
2224 // -- If T is a pointer to a member function of a class X, its
2225 // associated namespaces and classes are those associated
2226 // with the function parameter types and return type,
2227 // together with those associated with X.
2228 //
2229 // -- If T is a pointer to a data member of class X, its
2230 // associated namespaces and classes are those associated
2231 // with the member type together with those associated with
2232 // X.
2233 case Type::MemberPointer: {
2234 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2235
2236 // Queue up the class type into which this points.
2237 Queue.push_back(MemberPtr->getClass());
2238
2239 // And directly continue with the pointee type.
2240 T = MemberPtr->getPointeeType().getTypePtr();
2241 continue;
2242 }
2243
2244 // As an extension, treat this like a normal pointer.
2245 case Type::BlockPointer:
2246 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2247 continue;
2248
2249 // References aren't covered by the standard, but that's such an
2250 // obvious defect that we cover them anyway.
2251 case Type::LValueReference:
2252 case Type::RValueReference:
2253 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2254 continue;
2255
2256 // These are fundamental types.
2257 case Type::Vector:
2258 case Type::ExtVector:
2259 case Type::Complex:
2260 break;
2261
Richard Smith27d807c2013-04-30 13:56:41 +00002262 // Non-deduced auto types only get here for error cases.
2263 case Type::Auto:
2264 break;
2265
Douglas Gregor8e936662011-04-12 01:02:45 +00002266 // If T is an Objective-C object or interface type, or a pointer to an
2267 // object or interface type, the associated namespace is the global
2268 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002269 case Type::ObjCObject:
2270 case Type::ObjCInterface:
2271 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002272 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002273 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002274
2275 // Atomic types are just wrappers; use the associations of the
2276 // contained type.
2277 case Type::Atomic:
2278 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2279 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002280 }
2281
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002282 if (Queue.empty())
2283 break;
2284 T = Queue.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002285 }
Douglas Gregore254f902009-02-04 00:32:51 +00002286}
2287
2288/// \brief Find the associated classes and namespaces for
2289/// argument-dependent lookup for a call with the given set of
2290/// arguments.
2291///
2292/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002293/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002294/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00002295void Sema::FindAssociatedClassesAndNamespaces(
2296 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2297 AssociatedNamespaceSet &AssociatedNamespaces,
2298 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002299 AssociatedNamespaces.clear();
2300 AssociatedClasses.clear();
2301
John McCall7d8b0412012-08-24 20:38:34 +00002302 AssociatedLookup Result(*this, InstantiationLoc,
2303 AssociatedNamespaces, AssociatedClasses);
John McCallf24d7bb2010-05-28 18:45:08 +00002304
Douglas Gregore254f902009-02-04 00:32:51 +00002305 // C++ [basic.lookup.koenig]p2:
2306 // For each argument type T in the function call, there is a set
2307 // of zero or more associated namespaces and a set of zero or more
2308 // associated classes to be considered. The sets of namespaces and
2309 // classes is determined entirely by the types of the function
2310 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002311 // argument).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002312 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregore254f902009-02-04 00:32:51 +00002313 Expr *Arg = Args[ArgIdx];
2314
2315 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002316 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002317 continue;
2318 }
2319
2320 // [...] In addition, if the argument is the name or address of a
2321 // set of overloaded functions and/or function templates, its
2322 // associated classes and namespaces are the union of those
2323 // associated with each of the members of the set: the namespace
2324 // in which the function or function template is defined and the
2325 // classes and namespaces associated with its (non-dependent)
2326 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002327 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002328 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002329 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002330 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002331
John McCallf24d7bb2010-05-28 18:45:08 +00002332 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2333 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002334
Aaron Ballman1e606f42014-07-15 22:03:49 +00002335 for (const auto *D : ULE->decls()) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002336 // Look through any using declarations to find the underlying function.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002337 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
Douglas Gregore254f902009-02-04 00:32:51 +00002338
2339 // Add the classes and namespaces associated with the parameter
2340 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002341 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002342 }
2343 }
2344}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002345
John McCall5cebab12009-11-18 07:57:50 +00002346NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002347 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002348 LookupNameKind NameKind,
2349 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002350 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002351 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002352 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002353}
2354
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002355/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002356ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002357 SourceLocation IdLoc,
2358 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002359 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002360 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002361 return cast_or_null<ObjCProtocolDecl>(D);
2362}
2363
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002364void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002365 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002366 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002367 // C++ [over.match.oper]p3:
2368 // -- The set of non-member candidates is the result of the
2369 // unqualified lookup of operator@ in the context of the
2370 // expression according to the usual rules for name lookup in
2371 // unqualified function calls (3.4.2) except that all member
Richard Smith100b24a2014-04-17 01:52:14 +00002372 // functions are ignored.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002373 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002374 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2375 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002376
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002377 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
Richard Smith100b24a2014-04-17 01:52:14 +00002378 Functions.append(Operators.begin(), Operators.end());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002379}
2380
Alexis Hunt1da39282011-06-24 02:11:39 +00002381Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002382 CXXSpecialMember SM,
2383 bool ConstArg,
2384 bool VolatileArg,
2385 bool RValueThis,
2386 bool ConstThis,
2387 bool VolatileThis) {
Richard Smith7d125a12012-11-27 21:20:31 +00002388 assert(CanDeclareSpecialMemberFunction(RD) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002389 "doing special member lookup into record that isn't fully complete");
Richard Smith7d125a12012-11-27 21:20:31 +00002390 RD = RD->getDefinition();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002391 if (RValueThis || ConstThis || VolatileThis)
2392 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2393 "constructors and destructors always have unqualified lvalue this");
2394 if (ConstArg || VolatileArg)
2395 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2396 "parameter-less special members can't have qualified arguments");
2397
2398 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002399 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002400 ID.AddInteger(SM);
2401 ID.AddInteger(ConstArg);
2402 ID.AddInteger(VolatileArg);
2403 ID.AddInteger(RValueThis);
2404 ID.AddInteger(ConstThis);
2405 ID.AddInteger(VolatileThis);
2406
2407 void *InsertPoint;
2408 SpecialMemberOverloadResult *Result =
2409 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2410
2411 // This was already cached
2412 if (Result)
2413 return Result;
2414
Alexis Huntba8e18d2011-06-07 00:11:58 +00002415 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2416 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002417 SpecialMemberCache.InsertNode(Result, InsertPoint);
2418
2419 if (SM == CXXDestructor) {
Richard Smith2be35f52012-12-01 02:35:44 +00002420 if (RD->needsImplicitDestructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002421 DeclareImplicitDestructor(RD);
2422 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002423 assert(DD && "record without a destructor");
2424 Result->setMethod(DD);
Richard Smith852265f2012-03-30 20:53:28 +00002425 Result->setKind(DD->isDeleted() ?
2426 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith83c478d2012-04-20 18:46:14 +00002427 SpecialMemberOverloadResult::Success);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002428 return Result;
2429 }
2430
Alexis Hunteef8ee02011-06-10 03:50:41 +00002431 // Prepare for overload resolution. Here we construct a synthetic argument
2432 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002433 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002434 DeclarationName Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002435 Expr *Arg = nullptr;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002436 unsigned NumArgs;
2437
Richard Smith83c478d2012-04-20 18:46:14 +00002438 QualType ArgType = CanTy;
2439 ExprValueKind VK = VK_LValue;
2440
Alexis Hunteef8ee02011-06-10 03:50:41 +00002441 if (SM == CXXDefaultConstructor) {
2442 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2443 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002444 if (RD->needsImplicitDefaultConstructor())
2445 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002446 } else {
2447 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2448 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smith2be35f52012-12-01 02:35:44 +00002449 if (RD->needsImplicitCopyConstructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002450 DeclareImplicitCopyConstructor(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002451 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002452 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002453 } else {
2454 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smith2be35f52012-12-01 02:35:44 +00002455 if (RD->needsImplicitCopyAssignment())
Alexis Hunt1da39282011-06-24 02:11:39 +00002456 DeclareImplicitCopyAssignment(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002457 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002458 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002459 }
2460
Alexis Hunteef8ee02011-06-10 03:50:41 +00002461 if (ConstArg)
2462 ArgType.addConst();
2463 if (VolatileArg)
2464 ArgType.addVolatile();
2465
2466 // This isn't /really/ specified by the standard, but it's implied
2467 // we should be working from an RValue in the case of move to ensure
2468 // that we prefer to bind to rvalue references, and an LValue in the
2469 // case of copy to ensure we don't bind to rvalue references.
2470 // Possibly an XValue is actually correct in the case of move, but
2471 // there is no semantic difference for class types in this restricted
2472 // case.
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002473 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002474 VK = VK_LValue;
2475 else
2476 VK = VK_RValue;
Richard Smith83c478d2012-04-20 18:46:14 +00002477 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00002478
Richard Smith83c478d2012-04-20 18:46:14 +00002479 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2480
2481 if (SM != CXXDefaultConstructor) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002482 NumArgs = 1;
Richard Smith83c478d2012-04-20 18:46:14 +00002483 Arg = &FakeArg;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002484 }
2485
2486 // Create the object argument
2487 QualType ThisTy = CanTy;
2488 if (ConstThis)
2489 ThisTy.addConst();
2490 if (VolatileThis)
2491 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002492 Expr::Classification Classification =
Richard Smith83c478d2012-04-20 18:46:14 +00002493 OpaqueValueExpr(SourceLocation(), ThisTy,
2494 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002495
2496 // Now we perform lookup on the name we computed earlier and do overload
2497 // resolution. Lookup is only performed directly into the class since there
2498 // will always be a (possibly implicit) declaration to shadow any others.
Richard Smith100b24a2014-04-17 01:52:14 +00002499 OverloadCandidateSet OCS(RD->getLocation(), OverloadCandidateSet::CSK_Normal);
David Blaikieff7d47a2012-12-19 00:45:41 +00002500 DeclContext::lookup_result R = RD->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00002501 assert(!R.empty() &&
Alexis Hunteef8ee02011-06-10 03:50:41 +00002502 "lookup for a constructor or assignment operator was empty");
Chandler Carruth7deaae72013-08-18 07:20:52 +00002503
2504 // Copy the candidates as our processing of them may load new declarations
2505 // from an external source and invalidate lookup_result.
2506 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2507
Aaron Ballman1e606f42014-07-15 22:03:49 +00002508 for (auto *Cand : Candidates) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002509 if (Cand->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002510 continue;
2511
Alexis Hunt1da39282011-06-24 02:11:39 +00002512 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2513 // FIXME: [namespace.udecl]p15 says that we should only consider a
2514 // using declaration here if it does not match a declaration in the
2515 // derived class. We do not implement this correctly in other cases
2516 // either.
2517 Cand = U->getTargetDecl();
2518
2519 if (Cand->isInvalidDecl())
2520 continue;
2521 }
2522
2523 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002524 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Alexis Hunt1da39282011-06-24 02:11:39 +00002525 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002526 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2527 OCS, true);
Alexis Hunt080709f2011-06-23 00:26:20 +00002528 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002529 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2530 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt2949f022011-06-22 02:58:46 +00002531 } else if (FunctionTemplateDecl *Tmpl =
Alexis Hunt1da39282011-06-24 02:11:39 +00002532 dyn_cast<FunctionTemplateDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002533 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2534 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Craig Topperc3ec1492014-05-26 06:22:03 +00002535 RD, nullptr, ThisTy, Classification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002536 llvm::makeArrayRef(&Arg, NumArgs),
Alexis Hunt080709f2011-06-23 00:26:20 +00002537 OCS, true);
2538 else
2539 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Craig Topperc3ec1492014-05-26 06:22:03 +00002540 nullptr, llvm::makeArrayRef(&Arg, NumArgs),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002541 OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002542 } else {
2543 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002544 }
2545 }
2546
2547 OverloadCandidateSet::iterator Best;
2548 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2549 case OR_Success:
2550 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith83c478d2012-04-20 18:46:14 +00002551 Result->setKind(SpecialMemberOverloadResult::Success);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002552 break;
2553
2554 case OR_Deleted:
2555 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith852265f2012-03-30 20:53:28 +00002556 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002557 break;
2558
2559 case OR_Ambiguous:
Craig Topperc3ec1492014-05-26 06:22:03 +00002560 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00002561 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2562 break;
2563
Alexis Hunteef8ee02011-06-10 03:50:41 +00002564 case OR_No_Viable_Function:
Craig Topperc3ec1492014-05-26 06:22:03 +00002565 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00002566 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002567 break;
2568 }
2569
2570 return Result;
2571}
2572
2573/// \brief Look up the default constructor for the given class.
2574CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002575 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002576 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2577 false, false);
2578
2579 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002580}
2581
Alexis Hunt491ec602011-06-21 23:42:56 +00002582/// \brief Look up the copying constructor for the given class.
2583CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith83c478d2012-04-20 18:46:14 +00002584 unsigned Quals) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002585 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2586 "non-const, non-volatile qualifiers for copy ctor arg");
2587 SpecialMemberOverloadResult *Result =
2588 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2589 Quals & Qualifiers::Volatile, false, false, false);
2590
Alexis Hunt899bd442011-06-10 04:44:37 +00002591 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2592}
2593
Sebastian Redl22653ba2011-08-30 19:58:05 +00002594/// \brief Look up the moving constructor for the given class.
Richard Smith1c6461e2012-07-18 03:36:00 +00002595CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2596 unsigned Quals) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002597 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002598 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2599 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002600
2601 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2602}
2603
Douglas Gregor52b72822010-07-02 23:12:18 +00002604/// \brief Look up the constructors for the given class.
2605DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002606 // If the implicit constructors have not yet been declared, do so now.
Richard Smith7d125a12012-11-27 21:20:31 +00002607 if (CanDeclareSpecialMemberFunction(Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00002608 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002609 DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +00002610 if (Class->needsImplicitCopyConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002611 DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002612 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002613 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00002614 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002615
Douglas Gregor52b72822010-07-02 23:12:18 +00002616 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2617 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2618 return Class->lookup(Name);
2619}
2620
Alexis Hunt491ec602011-06-21 23:42:56 +00002621/// \brief Look up the copying assignment operator for the given class.
2622CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2623 unsigned Quals, bool RValueThis,
Richard Smith83c478d2012-04-20 18:46:14 +00002624 unsigned ThisQuals) {
Alexis Hunt491ec602011-06-21 23:42:56 +00002625 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2626 "non-const, non-volatile qualifiers for copy assignment arg");
2627 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2628 "non-const, non-volatile qualifiers for copy assignment this");
2629 SpecialMemberOverloadResult *Result =
2630 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2631 Quals & Qualifiers::Volatile, RValueThis,
2632 ThisQuals & Qualifiers::Const,
2633 ThisQuals & Qualifiers::Volatile);
2634
Alexis Hunt491ec602011-06-21 23:42:56 +00002635 return Result->getMethod();
2636}
2637
Sebastian Redl22653ba2011-08-30 19:58:05 +00002638/// \brief Look up the moving assignment operator for the given class.
2639CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith1c6461e2012-07-18 03:36:00 +00002640 unsigned Quals,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002641 bool RValueThis,
2642 unsigned ThisQuals) {
2643 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2644 "non-const, non-volatile qualifiers for copy assignment this");
2645 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002646 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2647 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002648 ThisQuals & Qualifiers::Const,
2649 ThisQuals & Qualifiers::Volatile);
2650
2651 return Result->getMethod();
2652}
2653
Douglas Gregore71edda2010-07-01 22:47:18 +00002654/// \brief Look for the destructor of the given class.
2655///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00002656/// During semantic analysis, this routine should be used in lieu of
2657/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00002658///
2659/// \returns The destructor for this class.
2660CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002661 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2662 false, false, false,
2663 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00002664}
2665
Richard Smithbcc22fc2012-03-09 08:00:36 +00002666/// LookupLiteralOperator - Determine which literal operator should be used for
2667/// a user-defined literal, per C++11 [lex.ext].
2668///
2669/// Normal overload resolution is not used to select which literal operator to
2670/// call for a user-defined literal. Look up the provided literal operator name,
2671/// and filter the results to the appropriate set for the given argument types.
2672Sema::LiteralOperatorLookupResult
2673Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2674 ArrayRef<QualType> ArgTys,
Richard Smithb8b41d32013-10-07 19:57:58 +00002675 bool AllowRaw, bool AllowTemplate,
2676 bool AllowStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002677 LookupName(R, S);
2678 assert(R.getResultKind() != LookupResult::Ambiguous &&
2679 "literal operator lookup can't be ambiguous");
2680
2681 // Filter the lookup results appropriately.
2682 LookupResult::Filter F = R.makeFilter();
2683
Richard Smithbcc22fc2012-03-09 08:00:36 +00002684 bool FoundRaw = false;
Richard Smithb8b41d32013-10-07 19:57:58 +00002685 bool FoundTemplate = false;
2686 bool FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002687 bool FoundExactMatch = false;
2688
2689 while (F.hasNext()) {
2690 Decl *D = F.next();
2691 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2692 D = USD->getTargetDecl();
2693
Douglas Gregorc1970572013-04-10 05:18:00 +00002694 // If the declaration we found is invalid, skip it.
2695 if (D->isInvalidDecl()) {
2696 F.erase();
2697 continue;
2698 }
2699
Richard Smithb8b41d32013-10-07 19:57:58 +00002700 bool IsRaw = false;
2701 bool IsTemplate = false;
2702 bool IsStringTemplate = false;
2703 bool IsExactMatch = false;
2704
Richard Smithbcc22fc2012-03-09 08:00:36 +00002705 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2706 if (FD->getNumParams() == 1 &&
2707 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2708 IsRaw = true;
Richard Smith550de452013-01-15 07:12:59 +00002709 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002710 IsExactMatch = true;
2711 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2712 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2713 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2714 IsExactMatch = false;
2715 break;
2716 }
2717 }
2718 }
2719 }
Richard Smithb8b41d32013-10-07 19:57:58 +00002720 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
2721 TemplateParameterList *Params = FD->getTemplateParameters();
2722 if (Params->size() == 1)
2723 IsTemplate = true;
2724 else
2725 IsStringTemplate = true;
2726 }
Richard Smithbcc22fc2012-03-09 08:00:36 +00002727
2728 if (IsExactMatch) {
2729 FoundExactMatch = true;
Richard Smithb8b41d32013-10-07 19:57:58 +00002730 AllowRaw = false;
2731 AllowTemplate = false;
2732 AllowStringTemplate = false;
2733 if (FoundRaw || FoundTemplate || FoundStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002734 // Go through again and remove the raw and template decls we've
2735 // already found.
2736 F.restart();
Richard Smithb8b41d32013-10-07 19:57:58 +00002737 FoundRaw = FoundTemplate = FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002738 }
Richard Smithb8b41d32013-10-07 19:57:58 +00002739 } else if (AllowRaw && IsRaw) {
2740 FoundRaw = true;
2741 } else if (AllowTemplate && IsTemplate) {
2742 FoundTemplate = true;
2743 } else if (AllowStringTemplate && IsStringTemplate) {
2744 FoundStringTemplate = true;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002745 } else {
2746 F.erase();
2747 }
2748 }
2749
2750 F.done();
2751
2752 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2753 // parameter type, that is used in preference to a raw literal operator
2754 // or literal operator template.
2755 if (FoundExactMatch)
2756 return LOLR_Cooked;
2757
2758 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2759 // operator template, but not both.
2760 if (FoundRaw && FoundTemplate) {
2761 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
Alp Tokera2794f92014-01-22 07:29:52 +00002762 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2763 NoteOverloadCandidate((*I)->getUnderlyingDecl()->getAsFunction());
Richard Smithbcc22fc2012-03-09 08:00:36 +00002764 return LOLR_Error;
2765 }
2766
2767 if (FoundRaw)
2768 return LOLR_Raw;
2769
2770 if (FoundTemplate)
2771 return LOLR_Template;
2772
Richard Smithb8b41d32013-10-07 19:57:58 +00002773 if (FoundStringTemplate)
2774 return LOLR_StringTemplate;
2775
Richard Smithbcc22fc2012-03-09 08:00:36 +00002776 // Didn't find anything we could use.
2777 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2778 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
Richard Smithb8b41d32013-10-07 19:57:58 +00002779 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
2780 << (AllowTemplate || AllowStringTemplate);
Richard Smithbcc22fc2012-03-09 08:00:36 +00002781 return LOLR_Error;
2782}
2783
John McCall8fe68082010-01-26 07:16:45 +00002784void ADLResult::insert(NamedDecl *New) {
2785 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2786
2787 // If we haven't yet seen a decl for this key, or the last decl
2788 // was exactly this one, we're done.
Craig Topperc3ec1492014-05-26 06:22:03 +00002789 if (Old == nullptr || Old == New) {
John McCall8fe68082010-01-26 07:16:45 +00002790 Old = New;
2791 return;
2792 }
2793
2794 // Otherwise, decide which is a more recent redeclaration.
Alp Tokera2794f92014-01-22 07:29:52 +00002795 FunctionDecl *OldFD = Old->getAsFunction();
2796 FunctionDecl *NewFD = New->getAsFunction();
John McCall8fe68082010-01-26 07:16:45 +00002797
2798 FunctionDecl *Cursor = NewFD;
2799 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002800 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00002801
2802 // If we got to the end without finding OldFD, OldFD is the newer
2803 // declaration; leave things as they are.
2804 if (!Cursor) return;
2805
2806 // If we do find OldFD, then NewFD is newer.
2807 if (Cursor == OldFD) break;
2808
2809 // Otherwise, keep looking.
2810 }
2811
2812 Old = New;
2813}
2814
Richard Smith100b24a2014-04-17 01:52:14 +00002815void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
2816 ArrayRef<Expr *> Args, ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002817 // Find all of the associated namespaces and classes based on the
2818 // arguments we have.
2819 AssociatedNamespaceSet AssociatedNamespaces;
2820 AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00002821 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCallc7e8e792009-08-07 22:18:02 +00002822 AssociatedNamespaces,
2823 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002824
2825 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002826 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2827 // and let Y be the lookup set produced by argument dependent
2828 // lookup (defined as follows). If X contains [...] then Y is
2829 // empty. Otherwise Y is the set of declarations found in the
2830 // namespaces associated with the argument types as described
2831 // below. The set of declarations found by the lookup of the name
2832 // is the union of X and Y.
2833 //
2834 // Here, we compute Y and add its members to the overloaded
2835 // candidate set.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002836 for (auto *NS : AssociatedNamespaces) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002837 // When considering an associated namespace, the lookup is the
2838 // same as the lookup performed when the associated namespace is
2839 // used as a qualifier (3.4.3.2) except that:
2840 //
2841 // -- Any using-directives in the associated namespace are
2842 // ignored.
2843 //
John McCallc7e8e792009-08-07 22:18:02 +00002844 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002845 // associated classes are visible within their respective
2846 // namespaces even if they are not visible during an ordinary
2847 // lookup (11.4).
Aaron Ballman1e606f42014-07-15 22:03:49 +00002848 DeclContext::lookup_result R = NS->lookup(Name);
2849 for (auto *D : R) {
John McCallaa74a0c2009-08-28 07:59:38 +00002850 // If the only declaration here is an ordinary friend, consider
2851 // it only if it was declared in an associated classes.
Richard Smith541b38b2013-09-20 01:15:31 +00002852 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) {
2853 // If it's neither ordinarily visible nor a friend, we can't find it.
2854 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0)
2855 continue;
2856
Richard Smith64017682013-07-17 23:53:16 +00002857 bool DeclaredInAssociatedClass = false;
2858 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
2859 DeclContext *LexDC = DI->getLexicalDeclContext();
2860 if (isa<CXXRecordDecl>(LexDC) &&
2861 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) {
2862 DeclaredInAssociatedClass = true;
2863 break;
2864 }
2865 }
2866 if (!DeclaredInAssociatedClass)
John McCalld1e9d832009-08-11 06:59:38 +00002867 continue;
2868 }
Mike Stump11289f42009-09-09 15:08:12 +00002869
John McCall91f61fc2010-01-26 06:04:06 +00002870 if (isa<UsingShadowDecl>(D))
2871 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002872
Richard Smith100b24a2014-04-17 01:52:14 +00002873 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D))
John McCall8fe68082010-01-26 07:16:45 +00002874 continue;
2875
2876 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002877 }
2878 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002879}
Douglas Gregor2d435302009-12-30 17:04:44 +00002880
2881//----------------------------------------------------------------------------
2882// Search for all visible declarations.
2883//----------------------------------------------------------------------------
2884VisibleDeclConsumer::~VisibleDeclConsumer() { }
2885
Richard Smithe156254d2013-08-20 20:35:18 +00002886bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
2887
Douglas Gregor2d435302009-12-30 17:04:44 +00002888namespace {
2889
2890class ShadowContextRAII;
2891
2892class VisibleDeclsRecord {
2893public:
2894 /// \brief An entry in the shadow map, which is optimized to store a
2895 /// single declaration (the common case) but can also store a list
2896 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002897 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00002898
2899private:
2900 /// \brief A mapping from declaration names to the declarations that have
2901 /// this name within a particular scope.
2902 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2903
2904 /// \brief A list of shadow maps, which is used to model name hiding.
2905 std::list<ShadowMap> ShadowMaps;
2906
2907 /// \brief The declaration contexts we have already visited.
2908 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2909
2910 friend class ShadowContextRAII;
2911
2912public:
2913 /// \brief Determine whether we have already visited this context
2914 /// (and, if not, note that we are going to visit that context now).
2915 bool visitedContext(DeclContext *Ctx) {
David Blaikie82e95a32014-11-19 07:49:47 +00002916 return !VisitedContexts.insert(Ctx).second;
Douglas Gregor2d435302009-12-30 17:04:44 +00002917 }
2918
Douglas Gregor39982192010-08-15 06:18:01 +00002919 bool alreadyVisitedContext(DeclContext *Ctx) {
2920 return VisitedContexts.count(Ctx);
2921 }
2922
Douglas Gregor2d435302009-12-30 17:04:44 +00002923 /// \brief Determine whether the given declaration is hidden in the
2924 /// current scope.
2925 ///
2926 /// \returns the declaration that hides the given declaration, or
2927 /// NULL if no such declaration exists.
2928 NamedDecl *checkHidden(NamedDecl *ND);
2929
2930 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002931 void add(NamedDecl *ND) {
2932 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2933 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002934};
2935
2936/// \brief RAII object that records when we've entered a shadow context.
2937class ShadowContextRAII {
2938 VisibleDeclsRecord &Visible;
2939
2940 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2941
2942public:
2943 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2944 Visible.ShadowMaps.push_back(ShadowMap());
2945 }
2946
2947 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00002948 Visible.ShadowMaps.pop_back();
2949 }
2950};
2951
2952} // end anonymous namespace
2953
Douglas Gregor2d435302009-12-30 17:04:44 +00002954NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002955 // Look through using declarations.
2956 ND = ND->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002957
Douglas Gregor2d435302009-12-30 17:04:44 +00002958 unsigned IDNS = ND->getIdentifierNamespace();
2959 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2960 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2961 SM != SMEnd; ++SM) {
2962 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2963 if (Pos == SM->end())
2964 continue;
2965
Aaron Ballman1e606f42014-07-15 22:03:49 +00002966 for (auto *D : Pos->second) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002967 // A tag declaration does not hide a non-tag declaration.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002968 if (D->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002969 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00002970 Decl::IDNS_ObjCProtocol)))
2971 continue;
2972
2973 // Protocols are in distinct namespaces from everything else.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002974 if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor2d435302009-12-30 17:04:44 +00002975 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Aaron Ballman1e606f42014-07-15 22:03:49 +00002976 D->getIdentifierNamespace() != IDNS)
Douglas Gregor2d435302009-12-30 17:04:44 +00002977 continue;
2978
Douglas Gregor09bbc652010-01-14 15:47:35 +00002979 // Functions and function templates in the same scope overload
2980 // rather than hide. FIXME: Look for hiding based on function
2981 // signatures!
Aaron Ballman1e606f42014-07-15 22:03:49 +00002982 if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Alp Tokera2794f92014-01-22 07:29:52 +00002983 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002984 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002985 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002986
Douglas Gregor2d435302009-12-30 17:04:44 +00002987 // We've found a declaration that hides this one.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002988 return D;
Douglas Gregor2d435302009-12-30 17:04:44 +00002989 }
2990 }
2991
Craig Topperc3ec1492014-05-26 06:22:03 +00002992 return nullptr;
Douglas Gregor2d435302009-12-30 17:04:44 +00002993}
2994
2995static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2996 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002997 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002998 VisibleDeclConsumer &Consumer,
2999 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00003000 if (!Ctx)
3001 return;
3002
Douglas Gregor2d435302009-12-30 17:04:44 +00003003 // Make sure we don't visit the same context twice.
3004 if (Visited.visitedContext(Ctx->getPrimaryContext()))
3005 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003006
Douglas Gregor7454c562010-07-02 20:37:36 +00003007 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3008 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3009
Douglas Gregor2d435302009-12-30 17:04:44 +00003010 // Enumerate all of the results in this context.
Aaron Ballman576114e2014-03-14 15:28:49 +00003011 for (const auto &R : Ctx->lookups()) {
3012 for (auto *I : R) {
3013 if (NamedDecl *ND = dyn_cast<NamedDecl>(I)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00003014 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003015 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00003016 Visited.add(ND);
3017 }
Douglas Gregora3b23b02010-12-09 21:44:02 +00003018 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003019 }
3020 }
3021
3022 // Traverse using directives for qualified name lookup.
3023 if (QualifiedNameLookup) {
3024 ShadowContextRAII Shadow(Visited);
Aaron Ballman804a7fb2014-03-17 17:14:12 +00003025 for (auto I : Ctx->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00003026 LookupVisibleDecls(I->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003027 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003028 }
3029 }
3030
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003031 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00003032 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00003033 if (!Record->hasDefinition())
3034 return;
3035
Aaron Ballman574705e2014-03-13 15:41:46 +00003036 for (const auto &B : Record->bases()) {
3037 QualType BaseType = B.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003038
Douglas Gregor2d435302009-12-30 17:04:44 +00003039 // Don't look into dependent bases, because name lookup can't look
3040 // there anyway.
3041 if (BaseType->isDependentType())
3042 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003043
Douglas Gregor2d435302009-12-30 17:04:44 +00003044 const RecordType *Record = BaseType->getAs<RecordType>();
3045 if (!Record)
3046 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003047
Douglas Gregor2d435302009-12-30 17:04:44 +00003048 // FIXME: It would be nice to be able to determine whether referencing
3049 // a particular member would be ambiguous. For example, given
3050 //
3051 // struct A { int member; };
3052 // struct B { int member; };
3053 // struct C : A, B { };
3054 //
3055 // void f(C *c) { c->### }
3056 //
3057 // accessing 'member' would result in an ambiguity. However, we
3058 // could be smart enough to qualify the member with the base
3059 // class, e.g.,
3060 //
3061 // c->B::member
3062 //
3063 // or
3064 //
3065 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003066
Douglas Gregor2d435302009-12-30 17:04:44 +00003067 // Find results in this base class (and its bases).
3068 ShadowContextRAII Shadow(Visited);
3069 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003070 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003071 }
3072 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003073
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003074 // Traverse the contexts of Objective-C classes.
3075 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3076 // Traverse categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003077 for (auto *Cat : IFace->visible_categories()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003078 ShadowContextRAII Shadow(Visited);
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003079 LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003080 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003081 }
3082
3083 // Traverse protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003084 for (auto *I : IFace->all_referenced_protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003085 ShadowContextRAII Shadow(Visited);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003086 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003087 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003088 }
3089
3090 // Traverse the superclass.
3091 if (IFace->getSuperClass()) {
3092 ShadowContextRAII Shadow(Visited);
3093 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003094 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003095 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003096
Douglas Gregor0b59e802010-04-19 18:02:19 +00003097 // If there is an implementation, traverse it. We do this to find
3098 // synthesized ivars.
3099 if (IFace->getImplementation()) {
3100 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003101 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky13668f22012-04-03 20:26:45 +00003102 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor0b59e802010-04-19 18:02:19 +00003103 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003104 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003105 for (auto *I : Protocol->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003106 ShadowContextRAII Shadow(Visited);
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003107 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003108 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003109 }
3110 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003111 for (auto *I : Category->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003112 ShadowContextRAII Shadow(Visited);
Aaron Ballman19a41762014-03-14 12:55:57 +00003113 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003114 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003115 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003116
Douglas Gregor0b59e802010-04-19 18:02:19 +00003117 // If there is an implementation, traverse it.
3118 if (Category->getImplementation()) {
3119 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003120 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00003121 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003122 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003123 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003124}
3125
3126static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3127 UnqualUsingDirectiveSet &UDirs,
3128 VisibleDeclConsumer &Consumer,
3129 VisibleDeclsRecord &Visited) {
3130 if (!S)
3131 return;
3132
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003133 if (!S->getEntity() ||
3134 (!S->getParent() &&
Ted Kremenekc37877d2013-10-08 17:08:03 +00003135 !Visited.alreadyVisitedContext(S->getEntity())) ||
3136 (S->getEntity())->isFunctionOrMethod()) {
Richard Smith541b38b2013-09-20 01:15:31 +00003137 FindLocalExternScope FindLocals(Result);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003138 // Walk through the declarations in this Scope.
Aaron Ballman35c54952014-03-17 16:55:25 +00003139 for (auto *D : S->decls()) {
3140 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Douglas Gregor4a814562011-12-14 16:03:29 +00003141 if ((ND = Result.getAcceptableDecl(ND))) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003142 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003143 Visited.add(ND);
3144 }
3145 }
3146 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003147
Douglas Gregor66230062010-03-15 14:33:29 +00003148 // FIXME: C++ [temp.local]p8
Craig Topperc3ec1492014-05-26 06:22:03 +00003149 DeclContext *Entity = nullptr;
Douglas Gregor4f248632010-01-01 17:44:25 +00003150 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003151 // Look into this scope's declaration context, along with any of its
3152 // parent lookup contexts (e.g., enclosing classes), up to the point
3153 // where we hit the context stored in the next outer scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00003154 Entity = S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00003155 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003156
Douglas Gregorea166062010-03-15 15:26:48 +00003157 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00003158 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003159 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3160 if (Method->isInstanceMethod()) {
3161 // For instance methods, look for ivars in the method's interface.
3162 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3163 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003164 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003165 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Richard Smithe156254d2013-08-20 20:35:18 +00003166 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003167 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003168 }
3169
3170 // We've already performed all of the name lookup that we need
3171 // to for Objective-C methods; the next context will be the
3172 // outer scope.
3173 break;
3174 }
3175
Douglas Gregor2d435302009-12-30 17:04:44 +00003176 if (Ctx->isFunctionOrMethod())
3177 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003178
3179 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003180 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003181 }
3182 } else if (!S->getParent()) {
3183 // Look into the translation unit scope. We walk through the translation
3184 // unit's declaration context, because the Scope itself won't have all of
3185 // the declarations if we loaded a precompiled header.
3186 // FIXME: We would like the translation unit's Scope object to point to the
3187 // translation unit, so we don't need this special "if" branch. However,
3188 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003189 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00003190 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003191 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00003192 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003193 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003194 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003195 }
3196
Douglas Gregor2d435302009-12-30 17:04:44 +00003197 if (Entity) {
3198 // Lookup visible declarations in any namespaces found by using
3199 // directives.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003200 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
3201 LookupVisibleDecls(const_cast<DeclContext *>(UUE.getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003202 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003203 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003204 }
3205
3206 // Lookup names in the parent scope.
3207 ShadowContextRAII Shadow(Visited);
3208 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3209}
3210
3211void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003212 VisibleDeclConsumer &Consumer,
3213 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003214 // Determine the set of using directives available during
3215 // unqualified name lookup.
3216 Scope *Initial = S;
3217 UnqualUsingDirectiveSet UDirs;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003218 if (getLangOpts().CPlusPlus) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003219 // Find the first namespace or translation-unit scope.
3220 while (S && !isNamespaceOrTranslationUnitScope(S))
3221 S = S->getParent();
3222
3223 UDirs.visitScopeChain(Initial, S);
3224 }
3225 UDirs.done();
3226
3227 // Look for visible declarations.
3228 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003229 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003230 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003231 if (!IncludeGlobalScope)
3232 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003233 ShadowContextRAII Shadow(Visited);
3234 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3235}
3236
3237void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003238 VisibleDeclConsumer &Consumer,
3239 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003240 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003241 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003242 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003243 if (!IncludeGlobalScope)
3244 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003245 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003246 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003247 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003248}
3249
Chris Lattner43e7f312011-02-18 02:08:43 +00003250/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003251/// If GnuLabelLoc is a valid source location, then this is a definition
3252/// of an __label__ label name, otherwise it is a normal label definition
3253/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003254LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003255 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003256 // Do a lookup to see if we have a label with this name already.
Craig Topperc3ec1492014-05-26 06:22:03 +00003257 NamedDecl *Res = nullptr;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003258
3259 if (GnuLabelLoc.isValid()) {
3260 // Local label definitions always shadow existing labels.
3261 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3262 Scope *S = CurScope;
3263 PushOnScopeChains(Res, S, true);
3264 return cast<LabelDecl>(Res);
3265 }
3266
3267 // Not a GNU local label.
3268 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3269 // If we found a label, check to see if it is in the same context as us.
3270 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003271 if (Res && Res->getDeclContext() != CurContext)
Craig Topperc3ec1492014-05-26 06:22:03 +00003272 Res = nullptr;
3273 if (!Res) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003274 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003275 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3276 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003277 assert(S && "Not in a function?");
3278 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003279 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003280 return cast<LabelDecl>(Res);
3281}
3282
3283//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003284// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003285//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003286
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003287static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3288 TypoCorrection &Candidate) {
3289 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3290 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3291}
3292
3293static void LookupPotentialTypoResult(Sema &SemaRef,
3294 LookupResult &Res,
3295 IdentifierInfo *Name,
3296 Scope *S, CXXScopeSpec *SS,
3297 DeclContext *MemberContext,
3298 bool EnteringContext,
3299 bool isObjCIvarLookup,
3300 bool FindHidden);
3301
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003302/// \brief Check whether the declarations found for a typo correction are
3303/// visible, and if none of them are, convert the correction to an 'import
3304/// a module' correction.
3305static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
3306 if (TC.begin() == TC.end())
3307 return;
3308
3309 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3310
3311 for (/**/; DI != DE; ++DI)
3312 if (!LookupResult::isVisible(SemaRef, *DI))
3313 break;
3314 // Nothing to do if all decls are visible.
3315 if (DI == DE)
3316 return;
3317
3318 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3319 bool AnyVisibleDecls = !NewDecls.empty();
3320
3321 for (/**/; DI != DE; ++DI) {
3322 NamedDecl *VisibleDecl = *DI;
3323 if (!LookupResult::isVisible(SemaRef, *DI))
3324 VisibleDecl = findAcceptableDecl(SemaRef, *DI);
3325
3326 if (VisibleDecl) {
3327 if (!AnyVisibleDecls) {
3328 // Found a visible decl, discard all hidden ones.
3329 AnyVisibleDecls = true;
3330 NewDecls.clear();
3331 }
3332 NewDecls.push_back(VisibleDecl);
3333 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
3334 NewDecls.push_back(*DI);
3335 }
3336
3337 if (NewDecls.empty())
3338 TC = TypoCorrection();
3339 else {
3340 TC.setCorrectionDecls(NewDecls);
3341 TC.setRequiresImport(!AnyVisibleDecls);
3342 }
3343}
3344
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003345// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3346// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3347// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3348static void getNestedNameSpecifierIdentifiers(
3349 NestedNameSpecifier *NNS,
3350 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3351 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3352 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3353 else
3354 Identifiers.clear();
3355
3356 const IdentifierInfo *II = nullptr;
3357
3358 switch (NNS->getKind()) {
3359 case NestedNameSpecifier::Identifier:
3360 II = NNS->getAsIdentifier();
3361 break;
3362
3363 case NestedNameSpecifier::Namespace:
3364 if (NNS->getAsNamespace()->isAnonymousNamespace())
3365 return;
3366 II = NNS->getAsNamespace()->getIdentifier();
3367 break;
3368
3369 case NestedNameSpecifier::NamespaceAlias:
3370 II = NNS->getAsNamespaceAlias()->getIdentifier();
3371 break;
3372
3373 case NestedNameSpecifier::TypeSpecWithTemplate:
3374 case NestedNameSpecifier::TypeSpec:
3375 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3376 break;
3377
3378 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00003379 case NestedNameSpecifier::Super:
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003380 return;
3381 }
3382
3383 if (II)
3384 Identifiers.push_back(II);
3385}
3386
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003387void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003388 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003389 // Don't consider hidden names for typo correction.
3390 if (Hiding)
3391 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003392
Douglas Gregor2d435302009-12-30 17:04:44 +00003393 // Only consider entities with identifiers for names, ignoring
3394 // special names (constructors, overloaded operators, selectors,
3395 // etc.).
3396 IdentifierInfo *Name = ND->getIdentifier();
3397 if (!Name)
3398 return;
3399
Richard Smithe156254d2013-08-20 20:35:18 +00003400 // Only consider visible declarations and declarations from modules with
3401 // names that exactly match.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003402 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo &&
Richard Smithe156254d2013-08-20 20:35:18 +00003403 !findAcceptableDecl(SemaRef, ND))
3404 return;
3405
Douglas Gregor57756ea2010-10-14 22:11:03 +00003406 FoundName(Name->getName());
3407}
3408
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003409void TypoCorrectionConsumer::FoundName(StringRef Name) {
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003410 // Compute the edit distance between the typo and the name of this
3411 // entity, and add the identifier to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003412 addName(Name, nullptr);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003413}
3414
3415void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3416 // Compute the edit distance between the typo and this keyword,
3417 // and add the keyword to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003418 addName(Keyword, nullptr, nullptr, true);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003419}
3420
3421void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
3422 NestedNameSpecifier *NNS, bool isKeyword) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003423 // Use a simple length-based heuristic to determine the minimum possible
3424 // edit distance. If the minimum isn't good enough, bail out early.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003425 StringRef TypoStr = Typo->getName();
3426 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
3427 if (MinED && TypoStr.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00003428 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003429
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003430 // Compute an upper bound on the allowable edit distance, so that the
3431 // edit-distance algorithm can short-circuit.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003432 unsigned UpperBound = (TypoStr.size() + 2) / 3 + 1;
3433 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003434 if (ED >= UpperBound) return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003435
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003436 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003437 if (isKeyword) TC.makeKeyword();
Kaelyn Takata0a313022014-11-20 22:06:26 +00003438 TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003439 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003440}
3441
Kaelyn Takatad2287c32014-10-27 18:07:13 +00003442static const unsigned MaxTypoDistanceResultSets = 5;
3443
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003444void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003445 StringRef TypoStr = Typo->getName();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003446 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003447
3448 // For very short typos, ignore potential corrections that have a different
3449 // base identifier from the typo or which have a normalized edit distance
3450 // longer than the typo itself.
3451 if (TypoStr.size() < 3 &&
3452 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
3453 return;
3454
3455 // If the correction is resolved but is not viable, ignore it.
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003456 if (Correction.isResolved()) {
3457 checkCorrectionVisibility(SemaRef, Correction);
3458 if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
3459 return;
3460 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003461
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003462 TypoResultList &CList =
3463 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003464
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003465 if (!CList.empty() && !CList.back().isResolved())
3466 CList.pop_back();
3467 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3468 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3469 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3470 RI != RIEnd; ++RI) {
3471 // If the Correction refers to a decl already in the result list,
3472 // replace the existing result if the string representation of Correction
3473 // comes before the current result alphabetically, then stop as there is
3474 // nothing more to be done to add Correction to the candidate set.
3475 if (RI->getCorrectionDecl() == NewND) {
3476 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3477 *RI = Correction;
3478 return;
3479 }
3480 }
3481 }
3482 if (CList.empty() || Correction.isResolved())
3483 CList.push_back(Correction);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003484
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003485 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003486 CorrectionResults.erase(std::prev(CorrectionResults.end()));
3487}
3488
3489void TypoCorrectionConsumer::addNamespaces(
3490 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
3491 SearchNamespaces = true;
3492
3493 for (auto KNPair : KnownNamespaces)
3494 Namespaces.addNameSpecifier(KNPair.first);
3495
3496 bool SSIsTemplate = false;
3497 if (NestedNameSpecifier *NNS =
3498 (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
3499 if (const Type *T = NNS->getAsType())
3500 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
3501 }
3502 for (const auto *TI : SemaRef.getASTContext().types()) {
3503 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
3504 CD = CD->getCanonicalDecl();
3505 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
3506 !CD->isUnion() && CD->getIdentifier() &&
3507 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
3508 (CD->isBeingDefined() || CD->isCompleteDefinition()))
3509 Namespaces.addNameSpecifier(CD);
3510 }
3511 }
3512}
3513
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003514const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
3515 if (++CurrentTCIndex < ValidatedCorrections.size())
3516 return ValidatedCorrections[CurrentTCIndex];
3517
3518 CurrentTCIndex = ValidatedCorrections.size();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003519 while (!CorrectionResults.empty()) {
3520 auto DI = CorrectionResults.begin();
3521 if (DI->second.empty()) {
3522 CorrectionResults.erase(DI);
3523 continue;
3524 }
3525
3526 auto RI = DI->second.begin();
3527 if (RI->second.empty()) {
3528 DI->second.erase(RI);
3529 performQualifiedLookups();
3530 continue;
3531 }
3532
3533 TypoCorrection TC = RI->second.pop_back_val();
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003534 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003535 ValidatedCorrections.push_back(TC);
3536 return ValidatedCorrections[CurrentTCIndex];
3537 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003538 }
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003539 return ValidatedCorrections[0]; // The empty correction.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003540}
3541
3542bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
3543 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
3544 DeclContext *TempMemberContext = MemberContext;
Kaelyn Takata6c759512014-10-27 18:07:37 +00003545 CXXScopeSpec *TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003546retry_lookup:
3547 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
3548 EnteringContext,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00003549 CorrectionValidator->IsObjCIvarLookup,
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003550 Name == Typo && !Candidate.WillReplaceSpecifier());
3551 switch (Result.getResultKind()) {
3552 case LookupResult::NotFound:
3553 case LookupResult::NotFoundInCurrentInstantiation:
3554 case LookupResult::FoundUnresolvedValue:
3555 if (TempSS) {
3556 // Immediately retry the lookup without the given CXXScopeSpec
3557 TempSS = nullptr;
3558 Candidate.WillReplaceSpecifier(true);
3559 goto retry_lookup;
3560 }
3561 if (TempMemberContext) {
3562 if (SS && !TempSS)
Kaelyn Takata6c759512014-10-27 18:07:37 +00003563 TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003564 TempMemberContext = nullptr;
3565 goto retry_lookup;
3566 }
3567 if (SearchNamespaces)
3568 QualifiedResults.push_back(Candidate);
3569 break;
3570
3571 case LookupResult::Ambiguous:
3572 // We don't deal with ambiguities.
3573 break;
3574
3575 case LookupResult::Found:
3576 case LookupResult::FoundOverloaded:
3577 // Store all of the Decls for overloaded symbols
3578 for (auto *TRD : Result)
3579 Candidate.addCorrectionDecl(TRD);
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003580 checkCorrectionVisibility(SemaRef, Candidate);
Kaelyn Takata89c881b2014-10-27 18:07:29 +00003581 if (!isCandidateViable(*CorrectionValidator, Candidate)) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003582 if (SearchNamespaces)
3583 QualifiedResults.push_back(Candidate);
3584 break;
3585 }
Kaelyn Takata20deb1d2015-01-28 00:46:09 +00003586 Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003587 return true;
3588 }
3589 return false;
3590}
3591
3592void TypoCorrectionConsumer::performQualifiedLookups() {
3593 unsigned TypoLen = Typo->getName().size();
3594 for (auto QR : QualifiedResults) {
3595 for (auto NSI : Namespaces) {
3596 DeclContext *Ctx = NSI.DeclCtx;
3597 const Type *NSType = NSI.NameSpecifier->getAsType();
3598
3599 // If the current NestedNameSpecifier refers to a class and the
3600 // current correction candidate is the name of that class, then skip
3601 // it as it is unlikely a qualified version of the class' constructor
3602 // is an appropriate correction.
3603 if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() : 0) {
3604 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
3605 continue;
3606 }
3607
3608 TypoCorrection TC(QR);
3609 TC.ClearCorrectionDecls();
3610 TC.setCorrectionSpecifier(NSI.NameSpecifier);
3611 TC.setQualifierDistance(NSI.EditDistance);
3612 TC.setCallbackDistance(0); // Reset the callback distance
3613
3614 // If the current correction candidate and namespace combination are
3615 // too far away from the original typo based on the normalized edit
3616 // distance, then skip performing a qualified name lookup.
3617 unsigned TmpED = TC.getEditDistance(true);
3618 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
3619 TypoLen / TmpED < 3)
3620 continue;
3621
3622 Result.clear();
3623 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
3624 if (!SemaRef.LookupQualifiedName(Result, Ctx))
3625 continue;
3626
3627 // Any corrections added below will be validated in subsequent
3628 // iterations of the main while() loop over the Consumer's contents.
3629 switch (Result.getResultKind()) {
3630 case LookupResult::Found:
3631 case LookupResult::FoundOverloaded: {
3632 if (SS && SS->isValid()) {
3633 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
3634 std::string OldQualified;
3635 llvm::raw_string_ostream OldOStream(OldQualified);
3636 SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
3637 OldOStream << Typo->getName();
3638 // If correction candidate would be an identical written qualified
3639 // identifer, then the existing CXXScopeSpec probably included a
3640 // typedef that didn't get accounted for properly.
3641 if (OldOStream.str() == NewQualified)
3642 break;
3643 }
3644 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
3645 TRD != TRDEnd; ++TRD) {
3646 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
3647 NSType ? NSType->getAsCXXRecordDecl()
3648 : nullptr,
3649 TRD.getPair()) == Sema::AR_accessible)
3650 TC.addCorrectionDecl(*TRD);
3651 }
Kaelyn Takata0a313022014-11-20 22:06:26 +00003652 if (TC.isResolved()) {
3653 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003654 addCorrection(TC);
Kaelyn Takata0a313022014-11-20 22:06:26 +00003655 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003656 break;
3657 }
3658 case LookupResult::NotFound:
3659 case LookupResult::NotFoundInCurrentInstantiation:
3660 case LookupResult::Ambiguous:
3661 case LookupResult::FoundUnresolvedValue:
3662 break;
3663 }
3664 }
3665 }
3666 QualifiedResults.clear();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003667}
3668
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00003669TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
3670 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
3671 : Context(Context), CurContextChain(buildContextChain(CurContext)),
3672 isSorted(false) {
3673 if (NestedNameSpecifier *NNS =
3674 CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
3675 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
3676 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3677
3678 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
3679 }
3680 // Build the list of identifiers that would be used for an absolute
3681 // (from the global context) NestedNameSpecifier referring to the current
3682 // context.
3683 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3684 CEnd = CurContextChain.rend();
3685 C != CEnd; ++C) {
3686 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3687 CurContextIdentifiers.push_back(ND->getIdentifier());
3688 }
3689
3690 // Add the global context as a NestedNameSpecifier
3691 Distances.insert(1);
Hans Wennborg66010132014-06-11 21:24:13 +00003692 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
3693 NestedNameSpecifier::GlobalSpecifier(Context), 1};
3694 DistanceMap[1].push_back(SI);
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00003695}
3696
Kaelyn Takata7dcc0e62014-06-11 18:07:08 +00003697auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
3698 DeclContext *Start) -> DeclContextList {
Nick Lewycky0d9b3192013-04-08 21:55:21 +00003699 assert(Start && "Building a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003700 DeclContextList Chain;
Craig Topperc3ec1492014-05-26 06:22:03 +00003701 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003702 DC = DC->getLookupParent()) {
3703 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3704 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3705 !(ND && ND->isAnonymousNamespace()))
3706 Chain.push_back(DC->getPrimaryContext());
3707 }
3708 return Chain;
3709}
3710
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003711void TypoCorrectionConsumer::NamespaceSpecifierSet::sortNamespaces() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003712 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003713 sortedDistances.append(Distances.begin(), Distances.end());
3714
3715 if (sortedDistances.size() > 1)
3716 std::sort(sortedDistances.begin(), sortedDistances.end());
3717
3718 Specifiers.clear();
Aaron Ballman1e606f42014-07-15 22:03:49 +00003719 for (auto D : sortedDistances) {
3720 SpecifierInfoList &SpecList = DistanceMap[D];
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003721 Specifiers.append(SpecList.begin(), SpecList.end());
3722 }
3723
3724 isSorted = true;
3725}
3726
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003727unsigned
3728TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
3729 DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003730 unsigned NumSpecifiers = 0;
3731 for (DeclContextList::reverse_iterator C = DeclChain.rbegin(),
3732 CEnd = DeclChain.rend();
3733 C != CEnd; ++C) {
3734 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) {
3735 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3736 ++NumSpecifiers;
3737 } else if (RecordDecl *RD = dyn_cast_or_null<RecordDecl>(*C)) {
3738 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
3739 RD->getTypeForDecl());
3740 ++NumSpecifiers;
3741 }
3742 }
3743 return NumSpecifiers;
3744}
3745
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003746void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
3747 DeclContext *Ctx) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003748 NestedNameSpecifier *NNS = nullptr;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003749 unsigned NumSpecifiers = 0;
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003750 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003751 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
3752
3753 // Eliminate common elements from the two DeclContext chains.
3754 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3755 CEnd = CurContextChain.rend();
3756 C != CEnd && !NamespaceDeclChain.empty() &&
3757 NamespaceDeclChain.back() == *C; ++C) {
3758 NamespaceDeclChain.pop_back();
3759 }
3760
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003761 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003762 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003763
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003764 // Add an explicit leading '::' specifier if needed.
3765 if (NamespaceDeclChain.empty()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003766 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003767 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003768 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003769 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003770 } else if (NamedDecl *ND =
3771 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003772 IdentifierInfo *Name = ND->getIdentifier();
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003773 bool SameNameSpecifier = false;
3774 if (std::find(CurNameSpecifierIdentifiers.begin(),
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003775 CurNameSpecifierIdentifiers.end(),
3776 Name) != CurNameSpecifierIdentifiers.end()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003777 std::string NewNameSpecifier;
3778 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
3779 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
3780 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3781 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3782 SpecifierOStream.flush();
3783 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003784 }
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003785 if (SameNameSpecifier ||
3786 std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3787 Name) != CurContextIdentifiers.end()) {
3788 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
3789 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3790 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003791 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003792 }
3793 }
3794
3795 // If the built NestedNameSpecifier would be replacing an existing
3796 // NestedNameSpecifier, use the number of component identifiers that
3797 // would need to be changed as the edit distance instead of the number
3798 // of components in the built NestedNameSpecifier.
3799 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3800 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3801 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3802 NumSpecifiers = llvm::ComputeEditDistance(
Craig Topper8c2a2a02014-08-30 16:55:39 +00003803 llvm::makeArrayRef(CurNameSpecifierIdentifiers),
3804 llvm::makeArrayRef(NewNameSpecifierIdentifiers));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003805 }
3806
3807 isSorted = false;
3808 Distances.insert(NumSpecifiers);
Hans Wennborg66010132014-06-11 21:24:13 +00003809 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
3810 DistanceMap[NumSpecifiers].push_back(SI);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003811}
3812
Douglas Gregord507d772010-10-20 03:06:34 +00003813/// \brief Perform name lookup for a possible result for typo correction.
3814static void LookupPotentialTypoResult(Sema &SemaRef,
3815 LookupResult &Res,
3816 IdentifierInfo *Name,
3817 Scope *S, CXXScopeSpec *SS,
3818 DeclContext *MemberContext,
3819 bool EnteringContext,
Richard Smithe156254d2013-08-20 20:35:18 +00003820 bool isObjCIvarLookup,
3821 bool FindHidden) {
Douglas Gregord507d772010-10-20 03:06:34 +00003822 Res.suppressDiagnostics();
3823 Res.clear();
3824 Res.setLookupName(Name);
Richard Smithe156254d2013-08-20 20:35:18 +00003825 Res.setAllowHidden(FindHidden);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003826 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00003827 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003828 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00003829 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3830 Res.addDecl(Ivar);
3831 Res.resolveKind();
3832 return;
3833 }
3834 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003835
Douglas Gregord507d772010-10-20 03:06:34 +00003836 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3837 Res.addDecl(Prop);
3838 Res.resolveKind();
3839 return;
3840 }
3841 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003842
Douglas Gregord507d772010-10-20 03:06:34 +00003843 SemaRef.LookupQualifiedName(Res, MemberContext);
3844 return;
3845 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003846
3847 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00003848 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003849
Douglas Gregord507d772010-10-20 03:06:34 +00003850 // Fake ivar lookup; this should really be part of
3851 // LookupParsedName.
3852 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3853 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003854 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00003855 (Res.isSingleResult() &&
3856 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003857 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00003858 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3859 Res.addDecl(IV);
3860 Res.resolveKind();
3861 }
3862 }
3863 }
3864}
3865
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003866/// \brief Add keywords to the consumer as possible typo corrections.
3867static void AddKeywordsToConsumer(Sema &SemaRef,
3868 TypoCorrectionConsumer &Consumer,
Richard Smithb3a1df02012-06-08 21:35:42 +00003869 Scope *S, CorrectionCandidateCallback &CCC,
3870 bool AfterNestedNameSpecifier) {
3871 if (AfterNestedNameSpecifier) {
3872 // For 'X::', we know exactly which keywords can appear next.
3873 Consumer.addKeywordResult("template");
3874 if (CCC.WantExpressionKeywords)
3875 Consumer.addKeywordResult("operator");
3876 return;
3877 }
3878
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003879 if (CCC.WantObjCSuper)
3880 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003881
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003882 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003883 // Add type-specifier keywords to the set of results.
Craig Topperd6d31ac2013-07-15 08:24:27 +00003884 static const char *const CTypeSpecs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003885 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00003886 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003887 "_Complex", "_Imaginary",
3888 // storage-specifiers as well
3889 "extern", "inline", "static", "typedef"
3890 };
3891
Craig Toppere5ce8312013-07-15 03:38:40 +00003892 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003893 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3894 Consumer.addKeywordResult(CTypeSpecs[I]);
3895
David Blaikiebbafb8a2012-03-11 07:00:24 +00003896 if (SemaRef.getLangOpts().C99)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003897 Consumer.addKeywordResult("restrict");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003898 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003899 Consumer.addKeywordResult("bool");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003900 else if (SemaRef.getLangOpts().C99)
Douglas Gregor3b22a882011-07-01 21:27:45 +00003901 Consumer.addKeywordResult("_Bool");
3902
David Blaikiebbafb8a2012-03-11 07:00:24 +00003903 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003904 Consumer.addKeywordResult("class");
3905 Consumer.addKeywordResult("typename");
3906 Consumer.addKeywordResult("wchar_t");
3907
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003908 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003909 Consumer.addKeywordResult("char16_t");
3910 Consumer.addKeywordResult("char32_t");
3911 Consumer.addKeywordResult("constexpr");
3912 Consumer.addKeywordResult("decltype");
3913 Consumer.addKeywordResult("thread_local");
3914 }
3915 }
3916
David Blaikiebbafb8a2012-03-11 07:00:24 +00003917 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003918 Consumer.addKeywordResult("typeof");
Kaelyn Takatab04846b2014-07-28 18:14:02 +00003919 } else if (CCC.WantFunctionLikeCasts) {
3920 static const char *const CastableTypeSpecs[] = {
3921 "char", "double", "float", "int", "long", "short",
3922 "signed", "unsigned", "void"
3923 };
3924 for (auto *kw : CastableTypeSpecs)
3925 Consumer.addKeywordResult(kw);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003926 }
3927
David Blaikiebbafb8a2012-03-11 07:00:24 +00003928 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003929 Consumer.addKeywordResult("const_cast");
3930 Consumer.addKeywordResult("dynamic_cast");
3931 Consumer.addKeywordResult("reinterpret_cast");
3932 Consumer.addKeywordResult("static_cast");
3933 }
3934
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003935 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003936 Consumer.addKeywordResult("sizeof");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003937 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003938 Consumer.addKeywordResult("false");
3939 Consumer.addKeywordResult("true");
3940 }
3941
David Blaikiebbafb8a2012-03-11 07:00:24 +00003942 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topperd6d31ac2013-07-15 08:24:27 +00003943 static const char *const CXXExprs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003944 "delete", "new", "operator", "throw", "typeid"
3945 };
Craig Toppere5ce8312013-07-15 03:38:40 +00003946 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003947 for (unsigned I = 0; I != NumCXXExprs; ++I)
3948 Consumer.addKeywordResult(CXXExprs[I]);
3949
3950 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3951 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3952 Consumer.addKeywordResult("this");
3953
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003954 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003955 Consumer.addKeywordResult("alignof");
3956 Consumer.addKeywordResult("nullptr");
3957 }
3958 }
Jordan Rose58d54722012-06-30 21:33:57 +00003959
3960 if (SemaRef.getLangOpts().C11) {
3961 // FIXME: We should not suggest _Alignof if the alignof macro
3962 // is present.
3963 Consumer.addKeywordResult("_Alignof");
3964 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003965 }
3966
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003967 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003968 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3969 // Statements.
Craig Topperd6d31ac2013-07-15 08:24:27 +00003970 static const char *const CStmts[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003971 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Toppere5ce8312013-07-15 03:38:40 +00003972 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003973 for (unsigned I = 0; I != NumCStmts; ++I)
3974 Consumer.addKeywordResult(CStmts[I]);
3975
David Blaikiebbafb8a2012-03-11 07:00:24 +00003976 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003977 Consumer.addKeywordResult("catch");
3978 Consumer.addKeywordResult("try");
3979 }
3980
3981 if (S && S->getBreakParent())
3982 Consumer.addKeywordResult("break");
3983
3984 if (S && S->getContinueParent())
3985 Consumer.addKeywordResult("continue");
3986
3987 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3988 Consumer.addKeywordResult("case");
3989 Consumer.addKeywordResult("default");
3990 }
3991 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003992 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003993 Consumer.addKeywordResult("namespace");
3994 Consumer.addKeywordResult("template");
3995 }
3996
3997 if (S && S->isClassScope()) {
3998 Consumer.addKeywordResult("explicit");
3999 Consumer.addKeywordResult("friend");
4000 Consumer.addKeywordResult("mutable");
4001 Consumer.addKeywordResult("private");
4002 Consumer.addKeywordResult("protected");
4003 Consumer.addKeywordResult("public");
4004 Consumer.addKeywordResult("virtual");
4005 }
4006 }
4007
David Blaikiebbafb8a2012-03-11 07:00:24 +00004008 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004009 Consumer.addKeywordResult("using");
4010
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004011 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004012 Consumer.addKeywordResult("static_assert");
4013 }
4014 }
4015}
4016
Kaelyn Takata6c759512014-10-27 18:07:37 +00004017std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
4018 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4019 Scope *S, CXXScopeSpec *SS,
4020 std::unique_ptr<CorrectionCandidateCallback> CCC,
4021 DeclContext *MemberContext, bool EnteringContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004022 const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00004023
4024 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4025 DisableTypoCorrection)
4026 return nullptr;
4027
4028 // In Microsoft mode, don't perform typo correction in a template member
4029 // function dependent context because it interferes with the "lookup into
4030 // dependent bases of class templates" feature.
4031 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
4032 isa<CXXMethodDecl>(CurContext))
4033 return nullptr;
4034
4035 // We only attempt to correct typos for identifiers.
4036 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4037 if (!Typo)
4038 return nullptr;
4039
4040 // If the scope specifier itself was invalid, don't try to correct
4041 // typos.
4042 if (SS && SS->isInvalid())
4043 return nullptr;
4044
4045 // Never try to correct typos during template deduction or
4046 // instantiation.
4047 if (!ActiveTemplateInstantiations.empty())
4048 return nullptr;
4049
4050 // Don't try to correct 'super'.
4051 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4052 return nullptr;
4053
4054 // Abort if typo correction already failed for this specific typo.
4055 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4056 if (locs != TypoCorrectionFailures.end() &&
4057 locs->second.count(TypoName.getLoc()))
4058 return nullptr;
4059
4060 // Don't try to correct the identifier "vector" when in AltiVec mode.
4061 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4062 // remove this workaround.
4063 if (getLangOpts().AltiVec && Typo->isStr("vector"))
4064 return nullptr;
4065
Nick Lewycky24653262014-12-16 21:39:02 +00004066 // Provide a stop gap for files that are just seriously broken. Trying
4067 // to correct all typos can turn into a HUGE performance penalty, causing
4068 // some files to take minutes to get rejected by the parser.
4069 unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
4070 if (Limit && TyposCorrected >= Limit)
4071 return nullptr;
4072 ++TyposCorrected;
4073
Kaelyn Takata6c759512014-10-27 18:07:37 +00004074 // If we're handling a missing symbol error, using modules, and the
4075 // special search all modules option is used, look for a missing import.
4076 if (ErrorRecovery && getLangOpts().Modules &&
4077 getLangOpts().ModulesSearchAll) {
4078 // The following has the side effect of loading the missing module.
4079 getModuleLoader().lookupMissingImports(Typo->getName(),
4080 TypoName.getLocStart());
4081 }
4082
4083 CorrectionCandidateCallback &CCCRef = *CCC;
4084 auto Consumer = llvm::make_unique<TypoCorrectionConsumer>(
4085 *this, TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
4086 EnteringContext);
4087
Kaelyn Takata6c759512014-10-27 18:07:37 +00004088 // Perform name lookup to find visible, similarly-named entities.
Nick Lewycky24653262014-12-16 21:39:02 +00004089 bool IsUnqualifiedLookup = false;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004090 DeclContext *QualifiedDC = MemberContext;
4091 if (MemberContext) {
4092 LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
4093
4094 // Look in qualified interfaces.
4095 if (OPT) {
4096 for (auto *I : OPT->quals())
4097 LookupVisibleDecls(I, LookupKind, *Consumer);
4098 }
4099 } else if (SS && SS->isSet()) {
4100 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4101 if (!QualifiedDC)
4102 return nullptr;
4103
Kaelyn Takata6c759512014-10-27 18:07:37 +00004104 LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
4105 } else {
4106 IsUnqualifiedLookup = true;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004107 }
4108
4109 // Determine whether we are going to search in the various namespaces for
4110 // corrections.
4111 bool SearchNamespaces
4112 = getLangOpts().CPlusPlus &&
4113 (IsUnqualifiedLookup || (SS && SS->isSet()));
4114
4115 if (IsUnqualifiedLookup || SearchNamespaces) {
4116 // For unqualified lookup, look through all of the names that we have
4117 // seen in this translation unit.
4118 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4119 for (const auto &I : Context.Idents)
4120 Consumer->FoundName(I.getKey());
4121
4122 // Walk through identifiers in external identifier sources.
4123 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4124 if (IdentifierInfoLookup *External
4125 = Context.Idents.getExternalIdentifierLookup()) {
4126 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4127 do {
4128 StringRef Name = Iter->Next();
4129 if (Name.empty())
4130 break;
4131
4132 Consumer->FoundName(Name);
4133 } while (true);
4134 }
4135 }
4136
4137 AddKeywordsToConsumer(*this, *Consumer, S, CCCRef, SS && SS->isNotEmpty());
4138
4139 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4140 // to search those namespaces.
4141 if (SearchNamespaces) {
4142 // Load any externally-known namespaces.
4143 if (ExternalSource && !LoadedExternalKnownNamespaces) {
4144 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
4145 LoadedExternalKnownNamespaces = true;
4146 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4147 for (auto *N : ExternalKnownNamespaces)
4148 KnownNamespaces[N] = true;
4149 }
4150
4151 Consumer->addNamespaces(KnownNamespaces);
4152 }
4153
4154 return Consumer;
4155}
4156
Douglas Gregor2d435302009-12-30 17:04:44 +00004157/// \brief Try to "correct" a typo in the source code by finding
4158/// visible declarations whose names are similar to the name that was
4159/// present in the source code.
4160///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004161/// \param TypoName the \c DeclarationNameInfo structure that contains
4162/// the name that was present in the source code along with its location.
4163///
4164/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00004165///
4166/// \param S the scope in which name lookup occurs.
4167///
4168/// \param SS the nested-name-specifier that precedes the name we're
4169/// looking for, if present.
4170///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004171/// \param CCC A CorrectionCandidateCallback object that provides further
4172/// validation of typo correction candidates. It also provides flags for
4173/// determining the set of keywords permitted.
4174///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00004175/// \param MemberContext if non-NULL, the context in which to look for
4176/// a member access expression.
4177///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004178/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00004179/// the nested-name-specifier SS.
4180///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004181/// \param OPT when non-NULL, the search for visible declarations will
4182/// also walk the protocols in the qualified interfaces of \p OPT.
4183///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004184/// \returns a \c TypoCorrection containing the corrected name if the typo
4185/// along with information such as the \c NamedDecl where the corrected name
4186/// was declared, and any additional \c NestedNameSpecifier needed to access
4187/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
4188TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
4189 Sema::LookupNameKind LookupKind,
4190 Scope *S, CXXScopeSpec *SS,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004191 std::unique_ptr<CorrectionCandidateCallback> CCC,
John Thompson2255f2c2014-04-23 12:57:01 +00004192 CorrectTypoKind Mode,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004193 DeclContext *MemberContext,
4194 bool EnteringContext,
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004195 const ObjCObjectPointerType *OPT,
4196 bool RecordFailure) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004197 assert(CCC && "CorrectTypo requires a CorrectionCandidateCallback");
4198
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004199 // Always let the ExternalSource have the first chance at correction, even
4200 // if we would otherwise have given up.
4201 if (ExternalSource) {
4202 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004203 TypoName, LookupKind, S, SS, *CCC, MemberContext, EnteringContext, OPT))
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004204 return Correction;
4205 }
4206
Kaelyn Takata6c759512014-10-27 18:07:37 +00004207 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4208 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4209 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4210 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
4211 bool ObjCMessageReceiver = CCC->WantObjCSuper && !CCC->WantRemainingKeywords;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004212
Kaelyn Takata6c759512014-10-27 18:07:37 +00004213 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Kaelyn Takata6c759512014-10-27 18:07:37 +00004214 auto Consumer = makeTypoCorrectionConsumer(
4215 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004216 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004217
Kaelyn Takata6c759512014-10-27 18:07:37 +00004218 if (!Consumer)
4219 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004220
Douglas Gregor280e1ee2010-04-14 20:04:41 +00004221 // If we haven't found anything, we're done.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004222 if (Consumer->empty())
Nick Lewycky24653262014-12-16 21:39:02 +00004223 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregor2d435302009-12-30 17:04:44 +00004224
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004225 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4226 // is not more that about a third of the length of the typo's identifier.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004227 unsigned ED = Consumer->getBestEditDistance(true);
4228 unsigned TypoLen = Typo->getName().size();
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004229 if (ED > 0 && TypoLen / ED < 3)
Nick Lewycky24653262014-12-16 21:39:02 +00004230 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004231
Kaelyn Takata6c759512014-10-27 18:07:37 +00004232 TypoCorrection BestTC = Consumer->getNextCorrection();
4233 TypoCorrection SecondBestTC = Consumer->getNextCorrection();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004234 if (!BestTC)
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004235 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004236
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004237 ED = BestTC.getEditDistance();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004238
Kaelyn Takata6c759512014-10-27 18:07:37 +00004239 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004240 // If this was an unqualified lookup and we believe the callback
4241 // object wouldn't have filtered out possible corrections, note
4242 // that no correction was found.
Nick Lewycky24653262014-12-16 21:39:02 +00004243 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004244 }
4245
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004246 // If only a single name remains, return that result.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004247 if (!SecondBestTC ||
4248 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
4249 const TypoCorrection &Result = BestTC;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004250
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00004251 // Don't correct to a keyword that's the same as the typo; the keyword
4252 // wasn't actually in scope.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004253 if (ED == 0 && Result.isKeyword())
4254 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004255
David Blaikie04ea41c2012-10-12 20:00:44 +00004256 TypoCorrection TC = Result;
4257 TC.setCorrectionRange(SS, TypoName);
Kaelyn Takataa95ebc62014-06-17 23:47:29 +00004258 checkCorrectionVisibility(*this, TC);
David Blaikie04ea41c2012-10-12 20:00:44 +00004259 return TC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004260 } else if (SecondBestTC && ObjCMessageReceiver) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004261 // Prefer 'super' when we're completing in a message-receiver
4262 // context.
4263
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004264 if (BestTC.getCorrection().getAsString() != "super") {
4265 if (SecondBestTC.getCorrection().getAsString() == "super")
4266 BestTC = SecondBestTC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004267 else if ((*Consumer)["super"].front().isKeyword())
4268 BestTC = (*Consumer)["super"].front();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004269 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004270 // Don't correct to a keyword that's the same as the typo; the keyword
4271 // wasn't actually in scope.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004272 if (BestTC.getEditDistance() == 0 ||
4273 BestTC.getCorrection().getAsString() != "super")
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004274 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004275
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004276 BestTC.setCorrectionRange(SS, TypoName);
4277 return BestTC;
Douglas Gregoraf9eb592010-10-15 13:35:25 +00004278 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004279
Kaelyn Takata73429fd2014-06-10 21:03:49 +00004280 // Record the failure's location if needed and return an empty correction. If
4281 // this was an unqualified lookup and we believe the callback object did not
4282 // filter out possible corrections, also cache the failure for the typo.
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004283 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004284}
4285
Kaelyn Takata6c759512014-10-27 18:07:37 +00004286/// \brief Try to "correct" a typo in the source code by finding
4287/// visible declarations whose names are similar to the name that was
4288/// present in the source code.
4289///
4290/// \param TypoName the \c DeclarationNameInfo structure that contains
4291/// the name that was present in the source code along with its location.
4292///
4293/// \param LookupKind the name-lookup criteria used to search for the name.
4294///
4295/// \param S the scope in which name lookup occurs.
4296///
4297/// \param SS the nested-name-specifier that precedes the name we're
4298/// looking for, if present.
4299///
4300/// \param CCC A CorrectionCandidateCallback object that provides further
4301/// validation of typo correction candidates. It also provides flags for
4302/// determining the set of keywords permitted.
4303///
4304/// \param TDG A TypoDiagnosticGenerator functor that will be used to print
4305/// diagnostics when the actual typo correction is attempted.
4306///
Kaelyn Takata8363f042014-10-27 18:07:42 +00004307/// \param TRC A TypoRecoveryCallback functor that will be used to build an
4308/// Expr from a typo correction candidate.
4309///
Kaelyn Takata6c759512014-10-27 18:07:37 +00004310/// \param MemberContext if non-NULL, the context in which to look for
4311/// a member access expression.
4312///
4313/// \param EnteringContext whether we're entering the context described by
4314/// the nested-name-specifier SS.
4315///
4316/// \param OPT when non-NULL, the search for visible declarations will
4317/// also walk the protocols in the qualified interfaces of \p OPT.
4318///
4319/// \returns a new \c TypoExpr that will later be replaced in the AST with an
4320/// Expr representing the result of performing typo correction, or nullptr if
4321/// typo correction is not possible. If nullptr is returned, no diagnostics will
4322/// be emitted and it is the responsibility of the caller to emit any that are
4323/// needed.
4324TypoExpr *Sema::CorrectTypoDelayed(
4325 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4326 Scope *S, CXXScopeSpec *SS,
4327 std::unique_ptr<CorrectionCandidateCallback> CCC,
Kaelyn Takata8363f042014-10-27 18:07:42 +00004328 TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,
Kaelyn Takata6c759512014-10-27 18:07:37 +00004329 DeclContext *MemberContext, bool EnteringContext,
4330 const ObjCObjectPointerType *OPT) {
4331 assert(CCC && "CorrectTypoDelayed requires a CorrectionCandidateCallback");
4332
4333 TypoCorrection Empty;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004334 auto Consumer = makeTypoCorrectionConsumer(
4335 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004336 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Kaelyn Takata6c759512014-10-27 18:07:37 +00004337
4338 if (!Consumer || Consumer->empty())
4339 return nullptr;
4340
4341 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4342 // is not more that about a third of the length of the typo's identifier.
4343 unsigned ED = Consumer->getBestEditDistance(true);
4344 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4345 if (ED > 0 && Typo->getName().size() / ED < 3)
4346 return nullptr;
4347
4348 ExprEvalContexts.back().NumTypos++;
Kaelyn Takata8363f042014-10-27 18:07:42 +00004349 return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC));
Kaelyn Takata6c759512014-10-27 18:07:37 +00004350}
4351
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004352void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4353 if (!CDecl) return;
4354
4355 if (isKeyword())
4356 CorrectionDecls.clear();
4357
Kaelyn Uhrainf60b55a2012-11-19 18:49:53 +00004358 CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004359
4360 if (!CorrectionName)
4361 CorrectionName = CDecl->getDeclName();
4362}
4363
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004364std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4365 if (CorrectionNameSpec) {
4366 std::string tmpBuffer;
4367 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4368 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikied4da8722013-05-14 21:04:00 +00004369 PrefixOStream << CorrectionName;
Benjamin Kramer73faad62012-04-14 08:26:28 +00004370 return PrefixOStream.str();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004371 }
4372
4373 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00004374}
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004375
Nico Weberb58e51c2014-11-19 05:21:39 +00004376bool CorrectionCandidateCallback::ValidateCandidate(
4377 const TypoCorrection &candidate) {
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004378 if (!candidate.isResolved())
4379 return true;
4380
4381 if (candidate.isKeyword())
4382 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4383 WantRemainingKeywords || WantObjCSuper;
4384
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004385 bool HasNonType = false;
4386 bool HasStaticMethod = false;
4387 bool HasNonStaticMethod = false;
4388 for (Decl *D : candidate) {
4389 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
4390 D = FTD->getTemplatedDecl();
4391 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4392 if (Method->isStatic())
4393 HasStaticMethod = true;
4394 else
4395 HasNonStaticMethod = true;
4396 }
4397 if (!isa<TypeDecl>(D))
4398 HasNonType = true;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004399 }
4400
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004401 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
4402 !candidate.getCorrectionSpecifier())
4403 return false;
4404
4405 return WantTypeSpecifiers || HasNonType;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004406}
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004407
4408FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004409 bool HasExplicitTemplateArgs,
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004410 MemberExpr *ME)
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004411 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004412 CurContext(SemaRef.CurContext), MemberFn(ME) {
Kaelyn Takatab04846b2014-07-28 18:14:02 +00004413 WantTypeSpecifiers = false;
4414 WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus && NumArgs == 1;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004415 WantRemainingKeywords = false;
4416}
4417
4418bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4419 if (!candidate.getCorrectionDecl())
4420 return candidate.isKeyword();
4421
Aaron Ballman1e606f42014-07-15 22:03:49 +00004422 for (auto *C : candidate) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004423 FunctionDecl *FD = nullptr;
Aaron Ballman1e606f42014-07-15 22:03:49 +00004424 NamedDecl *ND = C->getUnderlyingDecl();
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004425 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4426 FD = FTD->getTemplatedDecl();
4427 if (!HasExplicitTemplateArgs && !FD) {
4428 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4429 // If the Decl is neither a function nor a template function,
4430 // determine if it is a pointer or reference to a function. If so,
4431 // check against the number of arguments expected for the pointee.
4432 QualType ValType = cast<ValueDecl>(ND)->getType();
4433 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4434 ValType = ValType->getPointeeType();
4435 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
Alp Toker9cacbab2014-01-20 20:26:09 +00004436 if (FPT->getNumParams() == NumArgs)
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004437 return true;
4438 }
4439 }
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004440
4441 // Skip the current candidate if it is not a FunctionDecl or does not accept
4442 // the current number of arguments.
4443 if (!FD || !(FD->getNumParams() >= NumArgs &&
4444 FD->getMinRequiredArguments() <= NumArgs))
4445 continue;
4446
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004447 // If the current candidate is a non-static C++ method, skip the candidate
4448 // unless the method being corrected--or the current DeclContext, if the
4449 // function being corrected is not a method--is a method in the same class
4450 // or a descendent class of the candidate's parent class.
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004451 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004452 if (MemberFn || !MD->isStatic()) {
4453 CXXMethodDecl *CurMD =
4454 MemberFn
4455 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
4456 : dyn_cast_or_null<CXXMethodDecl>(CurContext);
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004457 CXXRecordDecl *CurRD =
Craig Topperc3ec1492014-05-26 06:22:03 +00004458 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004459 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
4460 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
4461 continue;
4462 }
4463 }
4464 return true;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004465 }
4466 return false;
4467}
Richard Smithf9b15102013-08-17 00:46:16 +00004468
4469void Sema::diagnoseTypo(const TypoCorrection &Correction,
4470 const PartialDiagnostic &TypoDiag,
4471 bool ErrorRecovery) {
4472 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
4473 ErrorRecovery);
4474}
4475
Richard Smithe156254d2013-08-20 20:35:18 +00004476/// Find which declaration we should import to provide the definition of
4477/// the given declaration.
4478static const NamedDecl *getDefinitionToImport(const NamedDecl *D) {
4479 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4480 return VD->getDefinition();
4481 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +00004482 return FD->isDefined(FD) ? FD : nullptr;
Richard Smithe156254d2013-08-20 20:35:18 +00004483 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
4484 return TD->getDefinition();
4485 if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
4486 return ID->getDefinition();
4487 if (const ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
4488 return PD->getDefinition();
4489 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
4490 return getDefinitionToImport(TD->getTemplatedDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004491 return nullptr;
Richard Smithe156254d2013-08-20 20:35:18 +00004492}
4493
Richard Smithf9b15102013-08-17 00:46:16 +00004494/// \brief Diagnose a successfully-corrected typo. Separated from the correction
4495/// itself to allow external validation of the result, etc.
4496///
4497/// \param Correction The result of performing typo correction.
4498/// \param TypoDiag The diagnostic to produce. This will have the corrected
4499/// string added to it (and usually also a fixit).
4500/// \param PrevNote A note to use when indicating the location of the entity to
4501/// which we are correcting. Will have the correction string added to it.
4502/// \param ErrorRecovery If \c true (the default), the caller is going to
4503/// recover from the typo as if the corrected string had been typed.
4504/// In this case, \c PDiag must be an error, and we will attach a fixit
4505/// to it.
4506void Sema::diagnoseTypo(const TypoCorrection &Correction,
4507 const PartialDiagnostic &TypoDiag,
4508 const PartialDiagnostic &PrevNote,
4509 bool ErrorRecovery) {
4510 std::string CorrectedStr = Correction.getAsString(getLangOpts());
4511 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
4512 FixItHint FixTypo = FixItHint::CreateReplacement(
4513 Correction.getCorrectionRange(), CorrectedStr);
4514
Richard Smithe156254d2013-08-20 20:35:18 +00004515 // Maybe we're just missing a module import.
4516 if (Correction.requiresImport()) {
4517 NamedDecl *Decl = Correction.getCorrectionDecl();
4518 assert(Decl && "import required but no declaration to import");
4519
4520 // Suggest importing a module providing the definition of this entity, if
4521 // possible.
4522 const NamedDecl *Def = getDefinitionToImport(Decl);
4523 if (!Def)
4524 Def = Decl;
4525 Module *Owner = Def->getOwningModule();
4526 assert(Owner && "definition of hidden declaration is not in a module");
4527
4528 Diag(Correction.getCorrectionRange().getBegin(),
4529 diag::err_module_private_declaration)
4530 << Def << Owner->getFullModuleName();
4531 Diag(Def->getLocation(), diag::note_previous_declaration);
4532
4533 // Recover by implicitly importing this module.
Richard Smith3d23c422014-05-07 02:25:43 +00004534 if (ErrorRecovery)
4535 createImplicitModuleImportForErrorRecovery(
4536 Correction.getCorrectionRange().getBegin(), Owner);
Richard Smithe156254d2013-08-20 20:35:18 +00004537 return;
4538 }
4539
Richard Smithf9b15102013-08-17 00:46:16 +00004540 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
4541 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
4542
4543 NamedDecl *ChosenDecl =
Craig Topperc3ec1492014-05-26 06:22:03 +00004544 Correction.isKeyword() ? nullptr : Correction.getCorrectionDecl();
Richard Smithf9b15102013-08-17 00:46:16 +00004545 if (PrevNote.getDiagID() && ChosenDecl)
4546 Diag(ChosenDecl->getLocation(), PrevNote)
4547 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
4548}
Kaelyn Takata6c759512014-10-27 18:07:37 +00004549
Kaelyn Takata8363f042014-10-27 18:07:42 +00004550TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
4551 TypoDiagnosticGenerator TDG,
4552 TypoRecoveryCallback TRC) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00004553 assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
4554 auto TE = new (Context) TypoExpr(Context.DependentTy);
4555 auto &State = DelayedTypos[TE];
4556 State.Consumer = std::move(TCC);
4557 State.DiagHandler = std::move(TDG);
Kaelyn Takata8363f042014-10-27 18:07:42 +00004558 State.RecoveryHandler = std::move(TRC);
Kaelyn Takata6c759512014-10-27 18:07:37 +00004559 return TE;
4560}
4561
4562const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
4563 auto Entry = DelayedTypos.find(TE);
4564 assert(Entry != DelayedTypos.end() &&
4565 "Failed to get the state for a TypoExpr!");
4566 return Entry->second;
4567}
4568
4569void Sema::clearDelayedTypo(TypoExpr *TE) {
4570 DelayedTypos.erase(TE);
4571}