blob: 4baf6053359cac6df575e5986f22eb2f86e7352c [file] [log] [blame]
Nick Lewycky4b81fc872015-10-18 20:32:12 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
Douglas Gregor34074322009-01-14 22:20:51 +00002//
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//===----------------------------------------------------------------------===//
Hans Wennborgdcfba332015-10-06 23:40:43 +000014
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
Douglas Gregor960b5bc2009-01-15 00:26:24 +000016#include "clang/AST/ASTContext.h"
Richard Smithd9ba2242015-05-07 03:54:19 +000017#include "clang/AST/ASTMutationListener.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000019#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
Nick Lewyckyc3921482012-04-03 21:44:08 +000021#include "clang/AST/DeclLookups.h"
Douglas Gregor34074322009-01-14 22:20:51 +000022#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000023#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000024#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000025#include "clang/AST/ExprCXX.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Douglas Gregor34074322009-01-14 22:20:51 +000027#include "clang/Basic/LangOptions.h"
Richard Smith42413142015-05-15 20:05:43 +000028#include "clang/Lex/HeaderSearch.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000029#include "clang/Lex/ModuleLoader.h"
Richard Smith4caa4492015-05-15 02:34:32 +000030#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/ExternalSemaSource.h"
33#include "clang/Sema/Overload.h"
34#include "clang/Sema/Scope.h"
35#include "clang/Sema/ScopeInfo.h"
36#include "clang/Sema/Sema.h"
37#include "clang/Sema/SemaInternal.h"
38#include "clang/Sema/TemplateDeduction.h"
39#include "clang/Sema/TypoCorrection.h"
Douglas Gregor34074322009-01-14 22:20:51 +000040#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "llvm/ADT/SetVector.h"
Douglas Gregore254f902009-02-04 00:32:51 +000042#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0afa7f62010-10-14 20:34:08 +000043#include "llvm/ADT/StringMap.h"
Chris Lattner83cfc7c2011-07-18 01:54:02 +000044#include "llvm/ADT/TinyPtrVector.h"
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +000045#include "llvm/ADT/edit_distance.h"
John McCall6538c932009-10-10 05:48:19 +000046#include "llvm/Support/ErrorHandling.h"
Nick Lewycky13668f22012-04-03 20:26:45 +000047#include <algorithm>
48#include <iterator>
Douglas Gregor0afa7f62010-10-14 20:34:08 +000049#include <limits>
Douglas Gregor2d435302009-12-30 17:04:44 +000050#include <list>
Douglas Gregorc2fa1692011-06-28 16:20:02 +000051#include <map>
Nick Lewycky13668f22012-04-03 20:26:45 +000052#include <set>
53#include <utility>
54#include <vector>
Douglas Gregor34074322009-01-14 22:20:51 +000055
56using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000057using namespace sema;
Douglas Gregor34074322009-01-14 22:20:51 +000058
John McCallf6c8a4e2009-11-10 07:01:13 +000059namespace {
60 class UnqualUsingEntry {
61 const DeclContext *Nominated;
62 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000063
John McCallf6c8a4e2009-11-10 07:01:13 +000064 public:
65 UnqualUsingEntry(const DeclContext *Nominated,
66 const DeclContext *CommonAncestor)
67 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
68 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000069
John McCallf6c8a4e2009-11-10 07:01:13 +000070 const DeclContext *getCommonAncestor() const {
71 return CommonAncestor;
72 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000073
John McCallf6c8a4e2009-11-10 07:01:13 +000074 const DeclContext *getNominatedNamespace() const {
75 return Nominated;
76 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000077
John McCallf6c8a4e2009-11-10 07:01:13 +000078 // Sort by the pointer value of the common ancestor.
79 struct Comparator {
80 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
81 return L.getCommonAncestor() < R.getCommonAncestor();
82 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000083
John McCallf6c8a4e2009-11-10 07:01:13 +000084 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
85 return E.getCommonAncestor() < DC;
86 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000087
John McCallf6c8a4e2009-11-10 07:01:13 +000088 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
89 return DC < E.getCommonAncestor();
90 }
91 };
92 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000093
John McCallf6c8a4e2009-11-10 07:01:13 +000094 /// A collection of using directives, as used by C++ unqualified
95 /// lookup.
96 class UnqualUsingDirectiveSet {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000097 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000098
John McCallf6c8a4e2009-11-10 07:01:13 +000099 ListTy list;
100 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000101
John McCallf6c8a4e2009-11-10 07:01:13 +0000102 public:
103 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +0000104
John McCallf6c8a4e2009-11-10 07:01:13 +0000105 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000106 // C++ [namespace.udir]p1:
John McCallf6c8a4e2009-11-10 07:01:13 +0000107 // During unqualified name lookup, the names appear as if they
108 // were declared in the nearest enclosing namespace which contains
109 // both the using-directive and the nominated namespace.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000110 DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
John McCallf6c8a4e2009-11-10 07:01:13 +0000111 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +0000112
John McCallf6c8a4e2009-11-10 07:01:13 +0000113 for (; S; S = S->getParent()) {
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000114 // C++ [namespace.udir]p1:
115 // A using-directive shall not appear in class scope, but may
116 // appear in namespace scope or in block scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000117 DeclContext *Ctx = S->getEntity();
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000118 if (Ctx && Ctx->isFileContext()) {
119 visit(Ctx, Ctx);
120 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
Aaron Ballman5df6aa42014-03-17 17:03:37 +0000121 for (auto *I : S->using_directives())
122 visit(I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000123 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000124 }
125 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000126
127 // Visits a context and collect all of its using directives
128 // recursively. Treats all using directives as if they were
129 // declared in the context.
130 //
131 // A given context is only every visited once, so it is important
132 // that contexts be visited from the inside out in order to get
133 // the effective DCs right.
134 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
David Blaikie82e95a32014-11-19 07:49:47 +0000135 if (!visited.insert(DC).second)
John McCallf6c8a4e2009-11-10 07:01:13 +0000136 return;
137
138 addUsingDirectives(DC, EffectiveDC);
139 }
140
141 // Visits a using directive and collects all of its using
142 // directives recursively. Treats all using directives as if they
143 // were declared in the effective DC.
144 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
145 DeclContext *NS = UD->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +0000146 if (!visited.insert(NS).second)
John McCallf6c8a4e2009-11-10 07:01:13 +0000147 return;
148
149 addUsingDirective(UD, EffectiveDC);
150 addUsingDirectives(NS, EffectiveDC);
151 }
152
153 // Adds all the using directives in a context (and those nominated
154 // by its using directives, transitively) as if they appeared in
155 // the given effective context.
156 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Nick Lewycky4b81fc872015-10-18 20:32:12 +0000157 SmallVector<DeclContext*, 4> queue;
John McCallf6c8a4e2009-11-10 07:01:13 +0000158 while (true) {
Aaron Ballman804a7fb2014-03-17 17:14:12 +0000159 for (auto UD : DC->using_directives()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000160 DeclContext *NS = UD->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +0000161 if (visited.insert(NS).second) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000162 addUsingDirective(UD, EffectiveDC);
163 queue.push_back(NS);
164 }
165 }
166
167 if (queue.empty())
168 return;
169
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000170 DC = queue.pop_back_val();
John McCallf6c8a4e2009-11-10 07:01:13 +0000171 }
172 }
173
174 // Add a using directive as if it had been declared in the given
175 // context. This helps implement C++ [namespace.udir]p3:
176 // The using-directive is transitive: if a scope contains a
177 // using-directive that nominates a second namespace that itself
178 // contains using-directives, the effect is as if the
179 // using-directives from the second namespace also appeared in
180 // the first.
181 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
182 // Find the common ancestor between the effective context and
183 // the nominated namespace.
184 DeclContext *Common = UD->getNominatedNamespace();
185 while (!Common->Encloses(EffectiveDC))
186 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000187 Common = Common->getPrimaryContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000188
John McCallf6c8a4e2009-11-10 07:01:13 +0000189 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
190 }
191
192 void done() {
193 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
194 }
195
John McCallf6c8a4e2009-11-10 07:01:13 +0000196 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000197
John McCallf6c8a4e2009-11-10 07:01:13 +0000198 const_iterator begin() const { return list.begin(); }
199 const_iterator end() const { return list.end(); }
200
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000201 llvm::iterator_range<const_iterator>
John McCallf6c8a4e2009-11-10 07:01:13 +0000202 getNamespacesFor(DeclContext *DC) const {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000203 return llvm::make_range(std::equal_range(begin(), end(),
204 DC->getPrimaryContext(),
205 UnqualUsingEntry::Comparator()));
John McCallf6c8a4e2009-11-10 07:01:13 +0000206 }
207 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000208} // end anonymous namespace
Douglas Gregor889ceb72009-02-03 19:21:40 +0000209
Douglas Gregor889ceb72009-02-03 19:21:40 +0000210// Retrieve the set of identifier namespaces that correspond to a
211// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000212static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
213 bool CPlusPlus,
214 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000215 unsigned IDNS = 0;
216 switch (NameKind) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +0000217 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000218 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000219 case Sema::LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +0000220 case Sema::LookupLocalFriendName:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000221 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000222 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000223 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000224 if (Redeclaration)
225 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCallea305ed2009-12-18 10:40:03 +0000226 }
Richard Smith541b38b2013-09-20 01:15:31 +0000227 if (Redeclaration)
228 IDNS |= Decl::IDNS_LocalExtern;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000229 break;
230
John McCallb9467b62010-04-24 01:30:58 +0000231 case Sema::LookupOperatorName:
232 // Operator lookup is its own crazy thing; it is not the same
233 // as (e.g.) looking up an operator name for redeclaration.
234 assert(!Redeclaration && "cannot do redeclaration operator lookup");
235 IDNS = Decl::IDNS_NonMemberOperator;
236 break;
237
Douglas Gregor889ceb72009-02-03 19:21:40 +0000238 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000239 if (CPlusPlus) {
240 IDNS = Decl::IDNS_Type;
241
242 // When looking for a redeclaration of a tag name, we add:
243 // 1) TagFriend to find undeclared friend decls
244 // 2) Namespace because they can't "overload" with tag decls.
245 // 3) Tag because it includes class templates, which can't
246 // "overload" with tag decls.
247 if (Redeclaration)
248 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
249 } else {
250 IDNS = Decl::IDNS_Tag;
251 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000252 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000253
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000254 case Sema::LookupLabel:
255 IDNS = Decl::IDNS_Label;
256 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000257
Douglas Gregor889ceb72009-02-03 19:21:40 +0000258 case Sema::LookupMemberName:
259 IDNS = Decl::IDNS_Member;
260 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000261 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000262 break;
263
264 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000265 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
266 break;
267
Douglas Gregor889ceb72009-02-03 19:21:40 +0000268 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000269 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000270 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000271
John McCall84d87672009-12-10 09:41:52 +0000272 case Sema::LookupUsingDeclName:
Richard Smith83e78f52014-04-11 01:03:38 +0000273 assert(Redeclaration && "should only be used for redecl lookup");
274 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |
275 Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend |
276 Decl::IDNS_LocalExtern;
John McCall84d87672009-12-10 09:41:52 +0000277 break;
278
Douglas Gregor79947a22009-04-24 00:11:27 +0000279 case Sema::LookupObjCProtocolName:
280 IDNS = Decl::IDNS_ObjCProtocol;
281 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000282
Douglas Gregor39982192010-08-15 06:18:01 +0000283 case Sema::LookupAnyName:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000284 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor39982192010-08-15 06:18:01 +0000285 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
286 | Decl::IDNS_Type;
287 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000288 }
289 return IDNS;
290}
291
John McCallea305ed2009-12-18 10:40:03 +0000292void LookupResult::configure() {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000293 IDNS = getIDNS(LookupKind, getSema().getLangOpts().CPlusPlus,
John McCallea305ed2009-12-18 10:40:03 +0000294 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000295
Richard Smithbdd14642014-02-04 01:14:30 +0000296 // If we're looking for one of the allocation or deallocation
297 // operators, make sure that the implicitly-declared new and delete
298 // operators can be found.
299 switch (NameInfo.getName().getCXXOverloadedOperator()) {
300 case OO_New:
301 case OO_Delete:
302 case OO_Array_New:
303 case OO_Array_Delete:
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000304 getSema().DeclareGlobalNewDelete();
Richard Smithbdd14642014-02-04 01:14:30 +0000305 break;
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000306
Richard Smithbdd14642014-02-04 01:14:30 +0000307 default:
308 break;
309 }
Douglas Gregor15197662013-04-03 23:06:26 +0000310
Richard Smithbdd14642014-02-04 01:14:30 +0000311 // Compiler builtins are always visible, regardless of where they end
312 // up being declared.
313 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
314 if (unsigned BuiltinID = Id->getBuiltinID()) {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000315 if (!getSema().Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
Richard Smithbdd14642014-02-04 01:14:30 +0000316 AllowHidden = true;
Douglas Gregor15197662013-04-03 23:06:26 +0000317 }
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000318 }
John McCallea305ed2009-12-18 10:40:03 +0000319}
320
Alp Tokerc1086762013-12-07 13:51:35 +0000321bool LookupResult::sanity() const {
Richard Smithf97ad222014-04-01 18:33:50 +0000322 // This function is never called by NDEBUG builds.
John McCall19c1bfd2010-08-25 05:32:35 +0000323 assert(ResultKind != NotFound || Decls.size() == 0);
324 assert(ResultKind != Found || Decls.size() == 1);
325 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
326 (Decls.size() == 1 &&
327 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
328 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
329 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000330 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
331 Ambiguity == AmbiguousBaseSubobjectTypes)));
Craig Topperc3ec1492014-05-26 06:22:03 +0000332 assert((Paths != nullptr) == (ResultKind == Ambiguous &&
333 (Ambiguity == AmbiguousBaseSubobjectTypes ||
334 Ambiguity == AmbiguousBaseSubobjects)));
Alp Tokerc1086762013-12-07 13:51:35 +0000335 return true;
John McCall19c1bfd2010-08-25 05:32:35 +0000336}
John McCall19c1bfd2010-08-25 05:32:35 +0000337
John McCall9f3059a2009-10-09 21:13:30 +0000338// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000339void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000340 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000341}
342
Richard Smith3876cc82013-10-30 01:02:04 +0000343/// Get a representative context for a declaration such that two declarations
344/// will have the same context if they were found within the same scope.
Benjamin Kramerfc58b042013-11-01 11:50:55 +0000345static DeclContext *getContextForScopeMatching(Decl *D) {
Richard Smith3876cc82013-10-30 01:02:04 +0000346 // For function-local declarations, use that function as the context. This
347 // doesn't account for scopes within the function; the caller must deal with
348 // those.
349 DeclContext *DC = D->getLexicalDeclContext();
350 if (DC->isFunctionOrMethod())
351 return DC;
352
353 // Otherwise, look at the semantic context of the declaration. The
354 // declaration must have been found there.
355 return D->getDeclContext()->getRedeclContext();
356}
357
Richard Smith826711d2015-07-29 23:38:25 +0000358/// \brief Determine whether \p D is a better lookup result than \p Existing,
359/// given that they declare the same entity.
Richard Smithcd31b852015-08-22 21:37:34 +0000360static bool isPreferredLookupResult(Sema &S, Sema::LookupNameKind Kind,
Richard Smith826711d2015-07-29 23:38:25 +0000361 NamedDecl *D, NamedDecl *Existing) {
362 // When looking up redeclarations of a using declaration, prefer a using
363 // shadow declaration over any other declaration of the same entity.
364 if (Kind == Sema::LookupUsingDeclName && isa<UsingShadowDecl>(D) &&
365 !isa<UsingShadowDecl>(Existing))
366 return true;
367
368 auto *DUnderlying = D->getUnderlyingDecl();
369 auto *EUnderlying = Existing->getUnderlyingDecl();
370
Richard Smith990668b2015-11-12 22:04:34 +0000371 // If they have different underlying declarations, prefer a typedef over the
372 // original type (this happens when two type declarations denote the same
373 // type), per a generous reading of C++ [dcl.typedef]p3 and p4. The typedef
374 // might carry additional semantic information, such as an alignment override.
375 // However, per C++ [dcl.typedef]p5, when looking up a tag name, prefer a tag
376 // declaration over a typedef.
Richard Smith826711d2015-07-29 23:38:25 +0000377 if (DUnderlying->getCanonicalDecl() != EUnderlying->getCanonicalDecl()) {
378 assert(isa<TypeDecl>(DUnderlying) && isa<TypeDecl>(EUnderlying));
Richard Smith990668b2015-11-12 22:04:34 +0000379 bool HaveTag = isa<TagDecl>(EUnderlying);
380 bool WantTag = Kind == Sema::LookupTagName;
381 return HaveTag != WantTag;
Richard Smith826711d2015-07-29 23:38:25 +0000382 }
383
Richard Smithcd31b852015-08-22 21:37:34 +0000384 // Pick the function with more default arguments.
385 // FIXME: In the presence of ambiguous default arguments, we should keep both,
386 // so we can diagnose the ambiguity if the default argument is needed.
387 // See C++ [over.match.best]p3.
388 if (auto *DFD = dyn_cast<FunctionDecl>(DUnderlying)) {
389 auto *EFD = cast<FunctionDecl>(EUnderlying);
390 unsigned DMin = DFD->getMinRequiredArguments();
391 unsigned EMin = EFD->getMinRequiredArguments();
392 // If D has more default arguments, it is preferred.
393 if (DMin != EMin)
394 return DMin < EMin;
Richard Smith535ff802015-09-11 22:39:35 +0000395 // FIXME: When we track visibility for default function arguments, check
396 // that we pick the declaration with more visible default arguments.
Richard Smithcd31b852015-08-22 21:37:34 +0000397 }
398
399 // Pick the template with more default template arguments.
400 if (auto *DTD = dyn_cast<TemplateDecl>(DUnderlying)) {
401 auto *ETD = cast<TemplateDecl>(EUnderlying);
402 unsigned DMin = DTD->getTemplateParameters()->getMinRequiredArguments();
403 unsigned EMin = ETD->getTemplateParameters()->getMinRequiredArguments();
Richard Smith535ff802015-09-11 22:39:35 +0000404 // If D has more default arguments, it is preferred. Note that default
405 // arguments (and their visibility) is monotonically increasing across the
406 // redeclaration chain, so this is a quick proxy for "is more recent".
Richard Smithcd31b852015-08-22 21:37:34 +0000407 if (DMin != EMin)
408 return DMin < EMin;
Richard Smith535ff802015-09-11 22:39:35 +0000409 // If D has more *visible* default arguments, it is preferred. Note, an
410 // earlier default argument being visible does not imply that a later
411 // default argument is visible, so we can't just check the first one.
412 for (unsigned I = DMin, N = DTD->getTemplateParameters()->size();
413 I != N; ++I) {
414 if (!S.hasVisibleDefaultArgument(
415 ETD->getTemplateParameters()->getParam(I)) &&
416 S.hasVisibleDefaultArgument(
417 DTD->getTemplateParameters()->getParam(I)))
418 return true;
419 }
Richard Smithcd31b852015-08-22 21:37:34 +0000420 }
421
Vassil Vassilev4d75e8d2016-02-28 19:08:24 +0000422 // VarDecl can have incomplete array types, prefer the one with more complete
423 // array type.
424 if (VarDecl *DVD = dyn_cast<VarDecl>(DUnderlying)) {
425 VarDecl *EVD = cast<VarDecl>(EUnderlying);
426 if (EVD->getType()->isIncompleteType() &&
427 !DVD->getType()->isIncompleteType()) {
428 // Prefer the decl with a more complete type if visible.
429 return S.isVisible(DVD);
430 }
431 return false; // Avoid picking up a newer decl, just because it was newer.
432 }
433
Richard Smithcd31b852015-08-22 21:37:34 +0000434 // For most kinds of declaration, it doesn't really matter which one we pick.
435 if (!isa<FunctionDecl>(DUnderlying) && !isa<VarDecl>(DUnderlying)) {
436 // If the existing declaration is hidden, prefer the new one. Otherwise,
437 // keep what we've got.
438 return !S.isVisible(Existing);
439 }
440
441 // Pick the newer declaration; it might have a more precise type.
Richard Smith826711d2015-07-29 23:38:25 +0000442 for (Decl *Prev = DUnderlying->getPreviousDecl(); Prev;
443 Prev = Prev->getPreviousDecl())
444 if (Prev == EUnderlying)
445 return true;
Richard Smith826711d2015-07-29 23:38:25 +0000446 return false;
447}
448
Richard Smith990668b2015-11-12 22:04:34 +0000449/// Determine whether \p D can hide a tag declaration.
450static bool canHideTag(NamedDecl *D) {
451 // C++ [basic.scope.declarative]p4:
452 // Given a set of declarations in a single declarative region [...]
453 // exactly one declaration shall declare a class name or enumeration name
454 // that is not a typedef name and the other declarations shall all refer to
455 // the same variable or enumerator, or all refer to functions and function
456 // templates; in this case the class name or enumeration name is hidden.
457 // C++ [basic.scope.hiding]p2:
458 // A class name or enumeration name can be hidden by the name of a
459 // variable, data member, function, or enumerator declared in the same
460 // scope.
461 D = D->getUnderlyingDecl();
462 return isa<VarDecl>(D) || isa<EnumConstantDecl>(D) || isa<FunctionDecl>(D) ||
463 isa<FunctionTemplateDecl>(D) || isa<FieldDecl>(D);
464}
465
John McCall283b9012009-11-22 00:44:51 +0000466/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000467void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000468 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000469
John McCall9f3059a2009-10-09 21:13:30 +0000470 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000471 if (N == 0) {
Richard Smith826711d2015-07-29 23:38:25 +0000472 assert(ResultKind == NotFound ||
473 ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000474 return;
475 }
476
John McCall283b9012009-11-22 00:44:51 +0000477 // If there's a single decl, we need to examine it to decide what
478 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000479 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000480 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
481 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000482 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000483 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000484 ResultKind = FoundUnresolvedValue;
485 return;
486 }
John McCall9f3059a2009-10-09 21:13:30 +0000487
John McCall6538c932009-10-10 05:48:19 +0000488 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000489 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000490
Richard Smitha534a312015-07-21 23:54:07 +0000491 llvm::SmallDenseMap<NamedDecl*, unsigned, 16> Unique;
Richard Smith826711d2015-07-29 23:38:25 +0000492 llvm::SmallDenseMap<QualType, unsigned, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000493
John McCall9f3059a2009-10-09 21:13:30 +0000494 bool Ambiguous = false;
Richard Smith2dbe4042015-11-04 19:26:32 +0000495 bool HasTag = false, HasFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000496 bool HasFunctionTemplate = false, HasUnresolved = false;
Richard Smith2dbe4042015-11-04 19:26:32 +0000497 NamedDecl *HasNonFunction = nullptr;
498
499 llvm::SmallVector<NamedDecl*, 4> EquivalentNonFunctions;
John McCall9f3059a2009-10-09 21:13:30 +0000500
501 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000502
John McCall9f3059a2009-10-09 21:13:30 +0000503 unsigned I = 0;
504 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000505 NamedDecl *D = Decls[I]->getUnderlyingDecl();
506 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000507
Argyrios Kyrtzidis1fcd7fd2013-02-22 06:58:37 +0000508 // Ignore an invalid declaration unless it's the only one left.
Richard Smith5cd86f82015-11-03 03:13:11 +0000509 if (D->isInvalidDecl() && !(I == 0 && N == 1)) {
Argyrios Kyrtzidis1fcd7fd2013-02-22 06:58:37 +0000510 Decls[I] = Decls[--N];
511 continue;
512 }
513
Richard Smith826711d2015-07-29 23:38:25 +0000514 llvm::Optional<unsigned> ExistingI;
515
Douglas Gregor13e65872010-08-11 14:45:53 +0000516 // Redeclarations of types via typedef can occur both within a scope
517 // and, through using declarations and directives, across scopes. There is
518 // no ambiguity if they all refer to the same type, so unique based on the
519 // canonical type.
520 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
Richard Smith990668b2015-11-12 22:04:34 +0000521 QualType T = getSema().Context.getTypeDeclType(TD);
522 auto UniqueResult = UniqueTypes.insert(
523 std::make_pair(getSema().Context.getCanonicalType(T), I));
524 if (!UniqueResult.second) {
525 // The type is not unique.
526 ExistingI = UniqueResult.first->second;
Douglas Gregor13e65872010-08-11 14:45:53 +0000527 }
528 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000529
Richard Smith826711d2015-07-29 23:38:25 +0000530 // For non-type declarations, check for a prior lookup result naming this
531 // canonical declaration.
532 if (!ExistingI) {
533 auto UniqueResult = Unique.insert(std::make_pair(D, I));
534 if (!UniqueResult.second) {
535 // We've seen this entity before.
536 ExistingI = UniqueResult.first->second;
Richard Smitha534a312015-07-21 23:54:07 +0000537 }
Richard Smith826711d2015-07-29 23:38:25 +0000538 }
539
540 if (ExistingI) {
541 // This is not a unique lookup result. Pick one of the results and
542 // discard the other.
Richard Smithcd31b852015-08-22 21:37:34 +0000543 if (isPreferredLookupResult(getSema(), getLookupKind(), Decls[I],
Richard Smith826711d2015-07-29 23:38:25 +0000544 Decls[*ExistingI]))
545 Decls[*ExistingI] = Decls[I];
546 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000547 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000548 }
549
Douglas Gregor13e65872010-08-11 14:45:53 +0000550 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000551
Douglas Gregor13e65872010-08-11 14:45:53 +0000552 if (isa<UnresolvedUsingValueDecl>(D)) {
553 HasUnresolved = true;
554 } else if (isa<TagDecl>(D)) {
555 if (HasTag)
556 Ambiguous = true;
557 UniqueTagIndex = I;
558 HasTag = true;
559 } else if (isa<FunctionTemplateDecl>(D)) {
560 HasFunction = true;
561 HasFunctionTemplate = true;
562 } else if (isa<FunctionDecl>(D)) {
563 HasFunction = true;
564 } else {
Richard Smith2dbe4042015-11-04 19:26:32 +0000565 if (HasNonFunction) {
566 // If we're about to create an ambiguity between two declarations that
567 // are equivalent, but one is an internal linkage declaration from one
568 // module and the other is an internal linkage declaration from another
569 // module, just skip it.
570 if (getSema().isEquivalentInternalLinkageDeclaration(HasNonFunction,
571 D)) {
572 EquivalentNonFunctions.push_back(D);
573 Decls[I] = Decls[--N];
574 continue;
575 }
576
Douglas Gregor13e65872010-08-11 14:45:53 +0000577 Ambiguous = true;
Richard Smith2dbe4042015-11-04 19:26:32 +0000578 }
579 HasNonFunction = D;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000580 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000581 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000582 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000583
John McCall9f3059a2009-10-09 21:13:30 +0000584 // C++ [basic.scope.hiding]p2:
585 // A class name or enumeration name can be hidden by the name of
586 // an object, function, or enumerator declared in the same
587 // scope. If a class or enumeration name and an object, function,
588 // or enumerator are declared in the same scope (in any order)
589 // with the same name, the class or enumeration name is hidden
590 // wherever the object, function, or enumerator name is visible.
591 // But it's still an error if there are distinct tag types found,
592 // even if they're not visible. (ref?)
Richard Smith990668b2015-11-12 22:04:34 +0000593 if (N > 1 && HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000594 (HasFunction || HasNonFunction || HasUnresolved)) {
Richard Smith990668b2015-11-12 22:04:34 +0000595 NamedDecl *OtherDecl = Decls[UniqueTagIndex ? 0 : N - 1];
596 if (isa<TagDecl>(Decls[UniqueTagIndex]->getUnderlyingDecl()) &&
597 getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
598 getContextForScopeMatching(OtherDecl)) &&
599 canHideTag(OtherDecl))
Douglas Gregore63d0872010-10-23 16:06:17 +0000600 Decls[UniqueTagIndex] = Decls[--N];
601 else
602 Ambiguous = true;
603 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000604
Richard Smith2dbe4042015-11-04 19:26:32 +0000605 // FIXME: This diagnostic should really be delayed until we're done with
606 // the lookup result, in case the ambiguity is resolved by the caller.
607 if (!EquivalentNonFunctions.empty() && !Ambiguous)
608 getSema().diagnoseEquivalentInternalLinkageDeclarations(
609 getNameLoc(), HasNonFunction, EquivalentNonFunctions);
610
John McCall9f3059a2009-10-09 21:13:30 +0000611 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000612
John McCall80053822009-12-03 00:58:24 +0000613 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000614 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000615
John McCall9f3059a2009-10-09 21:13:30 +0000616 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000617 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000618 else if (HasUnresolved)
619 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000620 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000621 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000622 else
John McCall27b18f82009-11-17 02:14:36 +0000623 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000624}
625
John McCall5cebab12009-11-18 07:57:50 +0000626void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000627 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000628 for (I = P.begin(), E = P.end(); I != E; ++I)
David Blaikieff7d47a2012-12-19 00:45:41 +0000629 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
630 DE = I->Decls.end(); DI != DE; ++DI)
John McCall9f3059a2009-10-09 21:13:30 +0000631 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000632}
633
John McCall5cebab12009-11-18 07:57:50 +0000634void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000635 Paths = new CXXBasePaths;
636 Paths->swap(P);
637 addDeclsFromBasePaths(*Paths);
638 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000639 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000640}
641
John McCall5cebab12009-11-18 07:57:50 +0000642void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000643 Paths = new CXXBasePaths;
644 Paths->swap(P);
645 addDeclsFromBasePaths(*Paths);
646 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000647 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000648}
649
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000650void LookupResult::print(raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000651 Out << Decls.size() << " result(s)";
652 if (isAmbiguous()) Out << ", ambiguous";
653 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000654
John McCall9f3059a2009-10-09 21:13:30 +0000655 for (iterator I = begin(), E = end(); I != E; ++I) {
656 Out << "\n";
657 (*I)->print(Out, 2);
658 }
659}
660
Richard Smithba3a4f92016-01-12 21:59:26 +0000661LLVM_DUMP_METHOD void LookupResult::dump() {
662 llvm::errs() << "lookup results for " << getLookupName().getAsString()
663 << ":\n";
664 for (NamedDecl *D : *this)
665 D->dump();
666}
667
Douglas Gregord3a59182010-02-12 05:48:04 +0000668/// \brief Lookup a builtin function, when name lookup would otherwise
669/// fail.
670static bool LookupBuiltin(Sema &S, LookupResult &R) {
671 Sema::LookupNameKind NameKind = R.getLookupKind();
672
673 // If we didn't find a use of this identifier, and if the identifier
674 // corresponds to a compiler builtin, create the decl object for the builtin
675 // now, injecting it into translation unit scope, and return it.
676 if (NameKind == Sema::LookupOrdinaryName ||
677 NameKind == Sema::LookupRedeclarationWithLinkage) {
678 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
679 if (II) {
Nico Webere1687c52013-06-20 21:44:55 +0000680 if (S.getLangOpts().CPlusPlus11 && S.getLangOpts().GNUMode &&
681 II == S.getFloat128Identifier()) {
682 // libstdc++4.7's type_traits expects type __float128 to exist, so
683 // insert a dummy type to make that header build in gnu++11 mode.
684 R.addDecl(S.getASTContext().getFloat128StubType());
685 return true;
686 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000687 if (S.getLangOpts().CPlusPlus && NameKind == Sema::LookupOrdinaryName &&
688 II == S.getASTContext().getMakeIntegerSeqName()) {
689 R.addDecl(S.getASTContext().getMakeIntegerSeqDecl());
690 return true;
691 }
Nico Webere1687c52013-06-20 21:44:55 +0000692
Douglas Gregord3a59182010-02-12 05:48:04 +0000693 // If this is a builtin on this (or all) targets, create the decl.
694 if (unsigned BuiltinID = II->getBuiltinID()) {
Anastasia Stulovab607e0f2016-02-02 11:29:43 +0000695 // In C++ and OpenCL (spec v1.2 s6.9.f), we don't have any predefined
696 // library functions like 'malloc'. Instead, we'll just error.
697 if ((S.getLangOpts().CPlusPlus || S.getLangOpts().OpenCL) &&
Douglas Gregord3a59182010-02-12 05:48:04 +0000698 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
699 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000700
701 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
702 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000703 R.isForRedeclaration(),
704 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000705 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000706 return true;
707 }
Douglas Gregord3a59182010-02-12 05:48:04 +0000708 }
709 }
710 }
711
712 return false;
713}
714
Douglas Gregor7454c562010-07-02 20:37:36 +0000715/// \brief Determine whether we can declare a special member function within
716/// the class at this point.
Richard Smith7d125a12012-11-27 21:20:31 +0000717static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +0000718 // We need to have a definition for the class.
719 if (!Class->getDefinition() || Class->isDependentContext())
720 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000721
Douglas Gregor7454c562010-07-02 20:37:36 +0000722 // We can't be in the middle of defining the class.
Richard Smith7d125a12012-11-27 21:20:31 +0000723 return !Class->isBeingDefined();
Douglas Gregor7454c562010-07-02 20:37:36 +0000724}
725
726void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smith7d125a12012-11-27 21:20:31 +0000727 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregora6d69502010-07-02 23:41:54 +0000728 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000729
730 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000731 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000732 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000733
Douglas Gregora6d69502010-07-02 23:41:54 +0000734 // If the copy constructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000735 if (Class->needsImplicitCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +0000736 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000737
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000738 // If the copy assignment operator has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000739 if (Class->needsImplicitCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000740 DeclareImplicitCopyAssignment(Class);
741
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000742 if (getLangOpts().CPlusPlus11) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000743 // If the move constructor has not yet been declared, do so now.
744 if (Class->needsImplicitMoveConstructor())
745 DeclareImplicitMoveConstructor(Class); // might not actually do it
746
747 // If the move assignment operator has not yet been declared, do so now.
748 if (Class->needsImplicitMoveAssignment())
749 DeclareImplicitMoveAssignment(Class); // might not actually do it
750 }
751
Douglas Gregor7454c562010-07-02 20:37:36 +0000752 // If the destructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000753 if (Class->needsImplicitDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000754 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000755}
756
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000757/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000758/// special member function.
759static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
760 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000761 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000762 case DeclarationName::CXXDestructorName:
763 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000764
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000765 case DeclarationName::CXXOperatorName:
766 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000767
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000768 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000769 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000770 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000771
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000772 return false;
773}
774
775/// \brief If there are any implicit member functions with the given name
776/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000777static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000778 DeclarationName Name,
779 const DeclContext *DC) {
780 if (!DC)
781 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000782
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000783 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000784 case DeclarationName::CXXConstructorName:
785 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith7d125a12012-11-27 21:20:31 +0000786 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000787 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000788 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000789 S.DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +0000790 if (Record->needsImplicitCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000791 S.DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000792 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000793 Record->needsImplicitMoveConstructor())
794 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000795 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000796 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000797
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000798 case DeclarationName::CXXDestructorName:
799 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith2be35f52012-12-01 02:35:44 +0000800 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smith7d125a12012-11-27 21:20:31 +0000801 CanDeclareSpecialMemberFunction(Record))
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000802 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000803 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000804
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000805 case DeclarationName::CXXOperatorName:
806 if (Name.getCXXOverloadedOperator() != OO_Equal)
807 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000808
Sebastian Redl22653ba2011-08-30 19:58:05 +0000809 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smith7d125a12012-11-27 21:20:31 +0000810 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000811 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smith2be35f52012-12-01 02:35:44 +0000812 if (Record->needsImplicitCopyAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000813 S.DeclareImplicitCopyAssignment(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000814 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000815 Record->needsImplicitMoveAssignment())
816 S.DeclareImplicitMoveAssignment(Class);
817 }
818 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000819 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000820
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000821 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000822 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000823 }
824}
Douglas Gregor7454c562010-07-02 20:37:36 +0000825
John McCall9f3059a2009-10-09 21:13:30 +0000826// Adds all qualifying matches for a name within a decl context to the
827// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000828static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000829 bool Found = false;
830
Douglas Gregor7454c562010-07-02 20:37:36 +0000831 // Lazily declare C++ special member functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000832 if (S.getLangOpts().CPlusPlus)
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000833 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000834
Douglas Gregor7454c562010-07-02 20:37:36 +0000835 // Perform lookup into this declaration context.
Richard Smithcf4bdde2015-02-21 02:45:19 +0000836 DeclContext::lookup_result DR = DC->lookup(R.getLookupName());
837 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E;
David Blaikieff7d47a2012-12-19 00:45:41 +0000838 ++I) {
John McCall401982f2010-01-20 21:53:11 +0000839 NamedDecl *D = *I;
Douglas Gregor4a814562011-12-14 16:03:29 +0000840 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000841 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000842 Found = true;
843 }
844 }
John McCall9f3059a2009-10-09 21:13:30 +0000845
Douglas Gregord3a59182010-02-12 05:48:04 +0000846 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
847 return true;
848
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000849 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000850 != DeclarationName::CXXConversionFunctionName ||
851 R.getLookupName().getCXXNameType()->isDependentType() ||
852 !isa<CXXRecordDecl>(DC))
853 return Found;
854
855 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000856 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000857 // name lookup. Instead, any conversion function templates visible in the
858 // context of the use are considered. [...]
859 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000860 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000861 return Found;
862
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +0000863 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
864 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruth3a693b72010-01-31 11:44:02 +0000865 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
866 if (!ConvTemplate)
867 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000868
Chandler Carruth3a693b72010-01-31 11:44:02 +0000869 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000870 // add the conversion function template. When we deduce template
871 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000872 // type of the new declaration with the type of the function template.
873 if (R.isForRedeclaration()) {
874 R.addDecl(ConvTemplate);
875 Found = true;
876 continue;
877 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000878
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000879 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000880 // [...] For each such operator, if argument deduction succeeds
881 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000882 // name lookup.
883 //
884 // When referencing a conversion function for any purpose other than
885 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000886 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000887 // specialization into the result set. We do this to avoid forcing all
888 // callers to perform special deduction for conversion functions.
Craig Toppere6706e42012-09-19 02:26:47 +0000889 TemplateDeductionInfo Info(R.getNameLoc());
Craig Topperc3ec1492014-05-26 06:22:03 +0000890 FunctionDecl *Specialization = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000891
892 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000893 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
894 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000895
Chandler Carruth3a693b72010-01-31 11:44:02 +0000896 // Compute the type of the function that we would expect the conversion
897 // function to have, if it were to match the name given.
898 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000899 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
Reid Kleckner78af0702013-08-27 23:08:25 +0000900 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
Richard Smith8acb4282014-07-31 21:57:55 +0000901 EPI.ExceptionSpec = EST_None;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000902 QualType ExpectedType
903 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000904 None, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000905
Chandler Carruth3a693b72010-01-31 11:44:02 +0000906 // Perform template argument deduction against the type that we would
907 // expect the function to have.
Craig Topperc3ec1492014-05-26 06:22:03 +0000908 if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
Chandler Carruth3a693b72010-01-31 11:44:02 +0000909 Specialization, Info)
910 == Sema::TDK_Success) {
911 R.addDecl(Specialization);
912 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000913 }
914 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000915
John McCall9f3059a2009-10-09 21:13:30 +0000916 return Found;
917}
918
John McCallf6c8a4e2009-11-10 07:01:13 +0000919// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000920static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000921CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000922 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000923
924 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
925
John McCallf6c8a4e2009-11-10 07:01:13 +0000926 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000927 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000928
John McCallf6c8a4e2009-11-10 07:01:13 +0000929 // Perform direct name lookup into the namespaces nominated by the
930 // using directives whose common ancestor is this namespace.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000931 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
932 if (LookupDirect(S, R, UUE.getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000933 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000934
935 R.resolveKind();
936
937 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000938}
939
940static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000941 if (DeclContext *Ctx = S->getEntity())
Douglas Gregor700792c2009-02-05 19:25:20 +0000942 return Ctx->isFileContext();
943 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000944}
Douglas Gregored8f2882009-01-30 01:04:22 +0000945
Douglas Gregor66230062010-03-15 14:33:29 +0000946// Find the next outer declaration context from this scope. This
947// routine actually returns the semantic outer context, which may
948// differ from the lexical context (encoded directly in the Scope
949// stack) when we are parsing a member of a class template. In this
950// case, the second element of the pair will be true, to indicate that
951// name lookup should continue searching in this semantic context when
952// it leaves the current template parameter scope.
953static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000954 DeclContext *DC = S->getEntity();
Craig Topperc3ec1492014-05-26 06:22:03 +0000955 DeclContext *Lexical = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000956 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000957 OuterS = OuterS->getParent()) {
958 if (OuterS->getEntity()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000959 Lexical = OuterS->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +0000960 break;
961 }
962 }
963
964 // C++ [temp.local]p8:
965 // In the definition of a member of a class template that appears
966 // outside of the namespace containing the class template
967 // definition, the name of a template-parameter hides the name of
968 // a member of this namespace.
969 //
970 // Example:
971 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000972 // namespace N {
973 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000974 //
975 // template<class T> class B {
976 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000977 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000978 // }
979 //
980 // template<class C> void N::B<C>::f(C) {
981 // C b; // C is the template parameter, not N::C
982 // }
983 //
984 // In this example, the lexical context we return is the
985 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000986 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000987 !S->getParent()->isTemplateParamScope())
988 return std::make_pair(Lexical, false);
989
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000990 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000991 // For the example, this is the scope for the template parameters of
992 // template<class C>.
993 Scope *OutermostTemplateScope = S->getParent();
994 while (OutermostTemplateScope->getParent() &&
995 OutermostTemplateScope->getParent()->isTemplateParamScope())
996 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000997
Douglas Gregor66230062010-03-15 14:33:29 +0000998 // Find the namespace context in which the original scope occurs. In
999 // the example, this is namespace N.
1000 DeclContext *Semantic = DC;
1001 while (!Semantic->isFileContext())
1002 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001003
Douglas Gregor66230062010-03-15 14:33:29 +00001004 // Find the declaration context just outside of the template
1005 // parameter scope. This is the context in which the template is
1006 // being lexically declaration (a namespace context). In the
1007 // example, this is the global scope.
1008 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
1009 Lexical->Encloses(Semantic))
1010 return std::make_pair(Semantic, true);
1011
1012 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +00001013}
1014
Richard Smith541b38b2013-09-20 01:15:31 +00001015namespace {
1016/// An RAII object to specify that we want to find block scope extern
1017/// declarations.
1018struct FindLocalExternScope {
1019 FindLocalExternScope(LookupResult &R)
1020 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
1021 Decl::IDNS_LocalExtern) {
1022 R.setFindLocalExtern(R.getIdentifierNamespace() & Decl::IDNS_Ordinary);
1023 }
1024 void restore() {
1025 R.setFindLocalExtern(OldFindLocalExtern);
1026 }
1027 ~FindLocalExternScope() {
1028 restore();
1029 }
1030 LookupResult &R;
1031 bool OldFindLocalExtern;
1032};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001033} // end anonymous namespace
Richard Smith541b38b2013-09-20 01:15:31 +00001034
John McCall27b18f82009-11-17 02:14:36 +00001035bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001036 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +00001037
1038 DeclarationName Name = R.getLookupName();
Richard Smith1c34fb72013-08-13 18:18:50 +00001039 Sema::LookupNameKind NameKind = R.getLookupKind();
John McCall27b18f82009-11-17 02:14:36 +00001040
Douglas Gregor330b9cf2010-07-02 21:50:04 +00001041 // If this is the name of an implicitly-declared special member function,
1042 // go through the scope stack to implicitly declare
1043 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
1044 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +00001045 if (DeclContext *DC = PreS->getEntity())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00001046 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
1047 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001048
Douglas Gregor330b9cf2010-07-02 21:50:04 +00001049 // Implicitly declare member functions with the name we're looking for, if in
1050 // fact we are in a scope where it matters.
1051
Douglas Gregor889ceb72009-02-03 19:21:40 +00001052 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +00001053 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +00001054 I = IdResolver.begin(Name),
1055 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001056
Douglas Gregor889ceb72009-02-03 19:21:40 +00001057 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001058 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +00001059 // ...During unqualified name lookup (3.4.1), the names appear as if
1060 // they were declared in the nearest enclosing namespace which contains
1061 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +00001062 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +00001063 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +00001064 //
1065 // For example:
1066 // namespace A { int i; }
1067 // void foo() {
1068 // int i;
1069 // {
1070 // using namespace A;
1071 // ++i; // finds local 'i', A::i appears at global scope
1072 // }
1073 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +00001074 //
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001075 UnqualUsingDirectiveSet UDirs;
1076 bool VisitedUsingDirectives = false;
Richard Smith1c34fb72013-08-13 18:18:50 +00001077 bool LeftStartingScope = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00001078 DeclContext *OutsideOfTemplateParamDC = nullptr;
Richard Smith541b38b2013-09-20 01:15:31 +00001079
1080 // When performing a scope lookup, we want to find local extern decls.
1081 FindLocalExternScope FindLocals(R);
1082
Douglas Gregor700792c2009-02-05 19:25:20 +00001083 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00001084 DeclContext *Ctx = S->getEntity();
Douglas Gregor3e51e172010-05-20 20:58:56 +00001085
Douglas Gregor889ceb72009-02-03 19:21:40 +00001086 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +00001087 bool Found = false;
John McCall48871652010-08-21 09:40:31 +00001088 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001089 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Richard Smith1c34fb72013-08-13 18:18:50 +00001090 if (NameKind == LookupRedeclarationWithLinkage) {
1091 // Determine whether this (or a previous) declaration is
1092 // out-of-scope.
1093 if (!LeftStartingScope && !Initial->isDeclScope(*I))
1094 LeftStartingScope = true;
1095
1096 // If we found something outside of our starting scope that
Richard Smith9a00bbf2013-10-16 21:12:00 +00001097 // does not have linkage, skip it. If it's a template parameter,
1098 // we still find it, so we can diagnose the invalid redeclaration.
1099 if (LeftStartingScope && !((*I)->hasLinkage()) &&
1100 !(*I)->isTemplateParameter()) {
Richard Smith1c34fb72013-08-13 18:18:50 +00001101 R.setShadowed();
1102 continue;
1103 }
1104 }
1105
John McCall9f3059a2009-10-09 21:13:30 +00001106 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +00001107 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001108 }
1109 }
John McCall9f3059a2009-10-09 21:13:30 +00001110 if (Found) {
1111 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +00001112 if (S->isClassScope())
1113 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
1114 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +00001115 return true;
1116 }
1117
Richard Smith1c34fb72013-08-13 18:18:50 +00001118 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
Richard Smith114394f2013-08-09 04:35:01 +00001119 // C++11 [class.friend]p11:
1120 // If a friend declaration appears in a local class and the name
1121 // specified is an unqualified name, a prior declaration is
1122 // looked up without considering scopes that are outside the
1123 // innermost enclosing non-class scope.
1124 return false;
1125 }
1126
Douglas Gregor66230062010-03-15 14:33:29 +00001127 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1128 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1129 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001130 // found nothing, so look into the contexts between the
Douglas Gregor66230062010-03-15 14:33:29 +00001131 // lexical and semantic declaration contexts returned by
1132 // findOuterContext(). This implements the name lookup behavior
1133 // of C++ [temp.local]p8.
1134 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +00001135 OutsideOfTemplateParamDC = nullptr;
Douglas Gregor66230062010-03-15 14:33:29 +00001136 }
1137
1138 if (Ctx) {
1139 DeclContext *OuterCtx;
1140 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001141 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregor66230062010-03-15 14:33:29 +00001142 if (SearchAfterTemplateScope)
1143 OutsideOfTemplateParamDC = OuterCtx;
1144
Douglas Gregorea166062010-03-15 15:26:48 +00001145 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +00001146 // We do not directly look into transparent contexts, since
1147 // those entities will be found in the nearest enclosing
1148 // non-transparent context.
1149 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +00001150 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +00001151
1152 // We do not look directly into function or method contexts,
1153 // since all of the local variables and parameters of the
1154 // function/method are present within the Scope.
1155 if (Ctx->isFunctionOrMethod()) {
1156 // If we have an Objective-C instance method, look for ivars
1157 // in the corresponding interface.
1158 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
1159 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1160 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1161 ObjCInterfaceDecl *ClassDeclared;
1162 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001163 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +00001164 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001165 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1166 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +00001167 R.resolveKind();
1168 return true;
1169 }
1170 }
1171 }
1172 }
1173
1174 continue;
1175 }
1176
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001177 // If this is a file context, we need to perform unqualified name
1178 // lookup considering using directives.
1179 if (Ctx->isFileContext()) {
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001180 // If we haven't handled using directives yet, do so now.
1181 if (!VisitedUsingDirectives) {
1182 // Add using directives from this context up to the top level.
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001183 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1184 if (UCtx->isTransparentContext())
1185 continue;
1186
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001187 UDirs.visit(UCtx, UCtx);
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001188 }
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001189
1190 // Find the innermost file scope, so we can add using directives
1191 // from local scopes.
1192 Scope *InnermostFileScope = S;
1193 while (InnermostFileScope &&
1194 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1195 InnermostFileScope = InnermostFileScope->getParent();
1196 UDirs.visitScopeChain(Initial, InnermostFileScope);
1197
1198 UDirs.done();
1199
1200 VisitedUsingDirectives = true;
1201 }
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001202
1203 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1204 R.resolveKind();
1205 return true;
1206 }
1207
1208 continue;
1209 }
1210
Douglas Gregor7f737c02009-09-10 16:57:35 +00001211 // Perform qualified name lookup into this context.
1212 // FIXME: In some cases, we know that every name that could be found by
1213 // this qualified name lookup will also be on the identifier chain. For
1214 // example, inside a class without any base classes, we never need to
1215 // perform qualified lookup because all of the members are on top of the
1216 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001217 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +00001218 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +00001219 }
Douglas Gregor700792c2009-02-05 19:25:20 +00001220 }
Douglas Gregored8f2882009-01-30 01:04:22 +00001221 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001222
John McCallf6c8a4e2009-11-10 07:01:13 +00001223 // Stop if we ran out of scopes.
1224 // FIXME: This really, really shouldn't be happening.
1225 if (!S) return false;
1226
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001227 // If we are looking for members, no need to look into global/namespace scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00001228 if (NameKind == LookupMemberName)
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001229 return false;
1230
Douglas Gregor700792c2009-02-05 19:25:20 +00001231 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +00001232 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +00001233 //
Mike Stump87c57ac2009-05-16 07:39:55 +00001234 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1235 // don't build it for each lookup!
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001236 if (!VisitedUsingDirectives) {
1237 UDirs.visitScopeChain(Initial, S);
1238 UDirs.done();
1239 }
Richard Smith541b38b2013-09-20 01:15:31 +00001240
1241 // If we're not performing redeclaration lookup, do not look for local
1242 // extern declarations outside of a function scope.
1243 if (!R.isForRedeclaration())
1244 FindLocals.restore();
1245
Douglas Gregor700792c2009-02-05 19:25:20 +00001246 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +00001247 // Unqualified name lookup in C++ requires looking into scopes
1248 // that aren't strictly lexical, and therefore we walk through the
1249 // context as well as walking through the scopes.
1250 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001251 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +00001252 bool Found = false;
John McCall48871652010-08-21 09:40:31 +00001253 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001254 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001255 // We found something. Look for anything else in our scope
1256 // with this same name and in an acceptable identifier
1257 // namespace, so that we can construct an overload set if we
1258 // need to.
John McCall9f3059a2009-10-09 21:13:30 +00001259 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +00001260 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001261 }
1262 }
1263
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001264 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +00001265 R.resolveKind();
1266 return true;
1267 }
1268
Ted Kremenekc37877d2013-10-08 17:08:03 +00001269 DeclContext *Ctx = S->getEntity();
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001270 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1271 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1272 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001273 // found nothing, so look into the contexts between the
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001274 // lexical and semantic declaration contexts returned by
1275 // findOuterContext(). This implements the name lookup behavior
1276 // of C++ [temp.local]p8.
1277 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +00001278 OutsideOfTemplateParamDC = nullptr;
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001279 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001280
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001281 if (Ctx) {
1282 DeclContext *OuterCtx;
1283 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001284 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001285 if (SearchAfterTemplateScope)
1286 OutsideOfTemplateParamDC = OuterCtx;
1287
1288 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1289 // We do not directly look into transparent contexts, since
1290 // those entities will be found in the nearest enclosing
1291 // non-transparent context.
1292 if (Ctx->isTransparentContext())
1293 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001294
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001295 // If we have a context, and it's not a context stashed in the
1296 // template parameter scope for an out-of-line definition, also
1297 // look into that context.
1298 if (!(Found && S && S->isTemplateParamScope())) {
1299 assert(Ctx->isFileContext() &&
1300 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001301
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001302 // Look into context considering using-directives.
1303 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1304 Found = true;
1305 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001306
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001307 if (Found) {
1308 R.resolveKind();
1309 return true;
1310 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001311
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001312 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1313 return false;
1314 }
1315 }
1316
Douglas Gregor3ce74932010-02-05 07:07:10 +00001317 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001318 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001319 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001320
John McCall9f3059a2009-10-09 21:13:30 +00001321 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001322}
1323
Richard Smith0e5d7b82013-07-25 23:08:39 +00001324/// \brief Find the declaration that a class temploid member specialization was
1325/// instantiated from, or the member itself if it is an explicit specialization.
1326static Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) {
1327 return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom();
1328}
1329
Richard Smith42413142015-05-15 20:05:43 +00001330Module *Sema::getOwningModule(Decl *Entity) {
1331 // If it's imported, grab its owning module.
1332 Module *M = Entity->getImportedOwningModule();
1333 if (M || !isa<NamedDecl>(Entity) || !cast<NamedDecl>(Entity)->isHidden())
1334 return M;
1335 assert(!Entity->isFromASTFile() &&
1336 "hidden entity from AST file has no owning module");
1337
Richard Smith87bb5692015-06-09 00:35:49 +00001338 if (!getLangOpts().ModulesLocalVisibility) {
1339 // If we're not tracking visibility locally, the only way a declaration
1340 // can be hidden and local is if it's hidden because it's parent is (for
1341 // instance, maybe this is a lazily-declared special member of an imported
1342 // class).
1343 auto *Parent = cast<NamedDecl>(Entity->getDeclContext());
1344 assert(Parent->isHidden() && "unexpectedly hidden decl");
1345 return getOwningModule(Parent);
1346 }
1347
Richard Smith42413142015-05-15 20:05:43 +00001348 // It's local and hidden; grab or compute its owning module.
1349 M = Entity->getLocalOwningModule();
1350 if (M)
1351 return M;
1352
1353 if (auto *Containing =
1354 PP.getModuleContainingLocation(Entity->getLocation())) {
1355 M = Containing;
1356 } else if (Entity->isInvalidDecl() || Entity->getLocation().isInvalid()) {
1357 // Don't bother tracking visibility for invalid declarations with broken
1358 // locations.
1359 cast<NamedDecl>(Entity)->setHidden(false);
1360 } else {
1361 // We need to assign a module to an entity that exists outside of any
1362 // module, so that we can hide it from modules that we textually enter.
1363 // Invent a fake module for all such entities.
1364 if (!CachedFakeTopLevelModule) {
1365 CachedFakeTopLevelModule =
1366 PP.getHeaderSearchInfo().getModuleMap().findOrCreateModule(
1367 "<top-level>", nullptr, false, false).first;
1368
1369 auto &SrcMgr = PP.getSourceManager();
1370 SourceLocation StartLoc =
1371 SrcMgr.getLocForStartOfFile(SrcMgr.getMainFileID());
1372 auto &TopLevel =
1373 VisibleModulesStack.empty() ? VisibleModules : VisibleModulesStack[0];
1374 TopLevel.setVisible(CachedFakeTopLevelModule, StartLoc);
1375 }
1376
1377 M = CachedFakeTopLevelModule;
1378 }
1379
1380 if (M)
1381 Entity->setLocalOwningModule(M);
1382 return M;
1383}
1384
Richard Smithd9ba2242015-05-07 03:54:19 +00001385void Sema::makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc) {
Richard Smith87bb5692015-06-09 00:35:49 +00001386 if (auto *M = PP.getModuleContainingLocation(Loc))
1387 Context.mergeDefinitionIntoModule(ND, M);
1388 else
1389 // We're not building a module; just make the definition visible.
1390 ND->setHidden(false);
Richard Smith63e09bf2015-06-17 20:39:41 +00001391
1392 // If ND is a template declaration, make the template parameters
1393 // visible too. They're not (necessarily) within a mergeable DeclContext.
1394 if (auto *TD = dyn_cast<TemplateDecl>(ND))
1395 for (auto *Param : *TD->getTemplateParameters())
1396 makeMergedDefinitionVisible(Param, Loc);
Richard Smithd9ba2242015-05-07 03:54:19 +00001397}
1398
Richard Smith0e5d7b82013-07-25 23:08:39 +00001399/// \brief Find the module in which the given declaration was defined.
Richard Smith42413142015-05-15 20:05:43 +00001400static Module *getDefiningModule(Sema &S, Decl *Entity) {
Richard Smith0e5d7b82013-07-25 23:08:39 +00001401 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1402 // If this function was instantiated from a template, the defining module is
1403 // the module containing the pattern.
1404 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1405 Entity = Pattern;
1406 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
Reid Klecknere7367d62014-10-14 20:28:40 +00001407 if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
1408 Entity = Pattern;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001409 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1410 if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo())
1411 Entity = getInstantiatedFrom(ED, MSInfo);
1412 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1413 // FIXME: Map from variable template specializations back to the template.
1414 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo())
1415 Entity = getInstantiatedFrom(VD, MSInfo);
1416 }
1417
1418 // Walk up to the containing context. That might also have been instantiated
1419 // from a template.
1420 DeclContext *Context = Entity->getDeclContext();
1421 if (Context->isFileContext())
Richard Smith42413142015-05-15 20:05:43 +00001422 return S.getOwningModule(Entity);
1423 return getDefiningModule(S, cast<Decl>(Context));
Richard Smith0e5d7b82013-07-25 23:08:39 +00001424}
1425
1426llvm::DenseSet<Module*> &Sema::getLookupModules() {
1427 unsigned N = ActiveTemplateInstantiations.size();
1428 for (unsigned I = ActiveTemplateInstantiationLookupModules.size();
1429 I != N; ++I) {
Richard Smith42413142015-05-15 20:05:43 +00001430 Module *M =
1431 getDefiningModule(*this, ActiveTemplateInstantiations[I].Entity);
Richard Smith0e5d7b82013-07-25 23:08:39 +00001432 if (M && !LookupModulesCache.insert(M).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00001433 M = nullptr;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001434 ActiveTemplateInstantiationLookupModules.push_back(M);
1435 }
1436 return LookupModulesCache;
1437}
1438
Richard Smith42413142015-05-15 20:05:43 +00001439bool Sema::hasVisibleMergedDefinition(NamedDecl *Def) {
1440 for (Module *Merged : Context.getModulesWithMergedDefinition(Def))
1441 if (isModuleVisible(Merged))
1442 return true;
1443 return false;
1444}
1445
Richard Smithe7bd6de2015-06-10 20:30:23 +00001446template<typename ParmDecl>
Richard Smith35c1df52015-06-17 20:16:32 +00001447static bool
1448hasVisibleDefaultArgument(Sema &S, const ParmDecl *D,
1449 llvm::SmallVectorImpl<Module *> *Modules) {
Richard Smithe7bd6de2015-06-10 20:30:23 +00001450 if (!D->hasDefaultArgument())
1451 return false;
1452
1453 while (D) {
1454 auto &DefaultArg = D->getDefaultArgStorage();
1455 if (!DefaultArg.isInherited() && S.isVisible(D))
1456 return true;
1457
Richard Smith63e09bf2015-06-17 20:39:41 +00001458 if (!DefaultArg.isInherited() && Modules) {
1459 auto *NonConstD = const_cast<ParmDecl*>(D);
1460 Modules->push_back(S.getOwningModule(NonConstD));
1461 const auto &Merged = S.Context.getModulesWithMergedDefinition(NonConstD);
1462 Modules->insert(Modules->end(), Merged.begin(), Merged.end());
1463 }
Richard Smith35c1df52015-06-17 20:16:32 +00001464
Richard Smithe7bd6de2015-06-10 20:30:23 +00001465 // If there was a previous default argument, maybe its parameter is visible.
1466 D = DefaultArg.getInheritedFrom();
1467 }
1468 return false;
1469}
1470
Richard Smith35c1df52015-06-17 20:16:32 +00001471bool Sema::hasVisibleDefaultArgument(const NamedDecl *D,
1472 llvm::SmallVectorImpl<Module *> *Modules) {
Richard Smithe7bd6de2015-06-10 20:30:23 +00001473 if (auto *P = dyn_cast<TemplateTypeParmDecl>(D))
Richard Smith35c1df52015-06-17 20:16:32 +00001474 return ::hasVisibleDefaultArgument(*this, P, Modules);
Richard Smithe7bd6de2015-06-10 20:30:23 +00001475 if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))
Richard Smith35c1df52015-06-17 20:16:32 +00001476 return ::hasVisibleDefaultArgument(*this, P, Modules);
1477 return ::hasVisibleDefaultArgument(*this, cast<TemplateTemplateParmDecl>(D),
1478 Modules);
Richard Smithe7bd6de2015-06-10 20:30:23 +00001479}
1480
Richard Smith0e5d7b82013-07-25 23:08:39 +00001481/// \brief Determine whether a declaration is visible to name lookup.
1482///
1483/// This routine determines whether the declaration D is visible in the current
1484/// lookup context, taking into account the current template instantiation
1485/// stack. During template instantiation, a declaration is visible if it is
1486/// visible from a module containing any entity on the template instantiation
1487/// path (by instantiating a template, you allow it to see the declarations that
1488/// your module can see, including those later on in your module).
1489bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001490 assert(D->isHidden() && "should not call this: not in slow case");
Richard Smith5196a172015-08-24 03:38:11 +00001491 Module *DeclModule = nullptr;
1492
1493 if (SemaRef.getLangOpts().ModulesLocalVisibility) {
1494 DeclModule = SemaRef.getOwningModule(D);
1495 if (!DeclModule) {
1496 // getOwningModule() may have decided the declaration should not be hidden.
1497 assert(!D->isHidden() && "hidden decl not from a module");
Richard Smith42413142015-05-15 20:05:43 +00001498 return true;
Richard Smith5196a172015-08-24 03:38:11 +00001499 }
1500
1501 // If the owning module is visible, and the decl is not module private,
1502 // then the decl is visible too. (Module private is ignored within the same
1503 // top-level module.)
1504 if ((!D->isFromASTFile() || !D->isModulePrivate()) &&
1505 (SemaRef.isModuleVisible(DeclModule) ||
1506 SemaRef.hasVisibleMergedDefinition(D)))
Richard Smith42413142015-05-15 20:05:43 +00001507 return true;
1508 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001509
Richard Smithbe3980b2015-03-27 00:41:57 +00001510 // If this declaration is not at namespace scope nor module-private,
1511 // then it is visible if its lexical parent has a visible definition.
1512 DeclContext *DC = D->getLexicalDeclContext();
1513 if (!D->isModulePrivate() &&
1514 DC && !DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) {
Richard Smithc7d48d12015-05-20 17:50:35 +00001515 // For a parameter, check whether our current template declaration's
1516 // lexical context is visible, not whether there's some other visible
1517 // definition of it, because parameters aren't "within" the definition.
1518 if ((D->isTemplateParameter() || isa<ParmVarDecl>(D))
1519 ? isVisible(SemaRef, cast<NamedDecl>(DC))
1520 : SemaRef.hasVisibleDefinition(cast<NamedDecl>(DC))) {
Richard Smith42413142015-05-15 20:05:43 +00001521 if (SemaRef.ActiveTemplateInstantiations.empty() &&
1522 // FIXME: Do something better in this case.
1523 !SemaRef.getLangOpts().ModulesLocalVisibility) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001524 // Cache the fact that this declaration is implicitly visible because
1525 // its parent has a visible definition.
1526 D->setHidden(false);
1527 }
1528 return true;
1529 }
1530 return false;
1531 }
1532
Richard Smith0e5d7b82013-07-25 23:08:39 +00001533 // Find the extra places where we need to look.
1534 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
1535 if (LookupModules.empty())
1536 return false;
1537
Richard Smith5196a172015-08-24 03:38:11 +00001538 if (!DeclModule) {
1539 DeclModule = SemaRef.getOwningModule(D);
1540 assert(DeclModule && "hidden decl not from a module");
1541 }
1542
Richard Smith0e5d7b82013-07-25 23:08:39 +00001543 // If our lookup set contains the decl's module, it's visible.
1544 if (LookupModules.count(DeclModule))
1545 return true;
1546
1547 // If the declaration isn't exported, it's not visible in any other module.
1548 if (D->isModulePrivate())
1549 return false;
1550
1551 // Check whether DeclModule is transitively exported to an import of
1552 // the lookup set.
Yaron Keren941ad902015-11-23 19:28:42 +00001553 return std::any_of(LookupModules.begin(), LookupModules.end(),
Yaron Keren4c31fcf2015-11-24 20:18:24 +00001554 [&](Module *M) { return M->isModuleVisible(DeclModule); });
Richard Smith0e5d7b82013-07-25 23:08:39 +00001555}
1556
Richard Smith42413142015-05-15 20:05:43 +00001557bool Sema::isVisibleSlow(const NamedDecl *D) {
1558 return LookupResult::isVisible(*this, const_cast<NamedDecl*>(D));
1559}
1560
Richard Smith10568d82015-11-17 03:02:41 +00001561bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) {
1562 for (auto *D : R) {
1563 if (isVisible(D))
1564 return true;
1565 }
1566 return New->isExternallyVisible();
1567}
1568
Douglas Gregor4a814562011-12-14 16:03:29 +00001569/// \brief Retrieve the visible declaration corresponding to D, if any.
1570///
1571/// This routine determines whether the declaration D is visible in the current
1572/// module, with the current imports. If not, it checks whether any
1573/// redeclaration of D is visible, and if so, returns that declaration.
Richard Smith0e5d7b82013-07-25 23:08:39 +00001574///
Douglas Gregor4a814562011-12-14 16:03:29 +00001575/// \returns D, or a visible previous declaration of D, whichever is more recent
1576/// and visible. If no declaration of D is visible, returns null.
Richard Smithe156254d2013-08-20 20:35:18 +00001577static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
1578 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
Richard Smith0e5d7b82013-07-25 23:08:39 +00001579
Aaron Ballman86c93902014-03-06 23:45:36 +00001580 for (auto RD : D->redecls()) {
Richard Smith4083e032016-02-17 21:52:44 +00001581 // Don't bother with extra checks if we already know this one isn't visible.
1582 if (RD == D)
1583 continue;
1584
Aaron Ballman86c93902014-03-06 23:45:36 +00001585 if (auto ND = dyn_cast<NamedDecl>(RD)) {
Richard Smithe8292b12015-02-10 03:28:10 +00001586 // FIXME: This is wrong in the case where the previous declaration is not
1587 // visible in the same scope as D. This needs to be done much more
1588 // carefully.
Richard Smithe156254d2013-08-20 20:35:18 +00001589 if (LookupResult::isVisible(SemaRef, ND))
Douglas Gregor54079202012-01-06 22:05:37 +00001590 return ND;
1591 }
Douglas Gregor4a814562011-12-14 16:03:29 +00001592 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001593
Craig Topperc3ec1492014-05-26 06:22:03 +00001594 return nullptr;
Douglas Gregor4a814562011-12-14 16:03:29 +00001595}
1596
Richard Smithe156254d2013-08-20 20:35:18 +00001597NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
Richard Smith4083e032016-02-17 21:52:44 +00001598 if (auto *ND = dyn_cast<NamespaceDecl>(D)) {
1599 // Namespaces are a bit of a special case: we expect there to be a lot of
1600 // redeclarations of some namespaces, all declarations of a namespace are
1601 // essentially interchangeable, all declarations are found by name lookup
1602 // if any is, and namespaces are never looked up during template
1603 // instantiation. So we benefit from caching the check in this case, and
1604 // it is correct to do so.
1605 auto *Key = ND->getCanonicalDecl();
1606 if (auto *Acceptable = getSema().VisibleNamespaceCache.lookup(Key))
1607 return Acceptable;
1608 auto *Acceptable =
1609 isVisible(getSema(), Key) ? Key : findAcceptableDecl(getSema(), Key);
1610 if (Acceptable)
1611 getSema().VisibleNamespaceCache.insert(std::make_pair(Key, Acceptable));
1612 return Acceptable;
1613 }
1614
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +00001615 return findAcceptableDecl(getSema(), D);
Richard Smithe156254d2013-08-20 20:35:18 +00001616}
1617
Douglas Gregor34074322009-01-14 22:20:51 +00001618/// @brief Perform unqualified name lookup starting from a given
1619/// scope.
1620///
1621/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1622/// used to find names within the current scope. For example, 'x' in
1623/// @code
1624/// int x;
1625/// int f() {
1626/// return x; // unqualified name look finds 'x' in the global scope
1627/// }
1628/// @endcode
1629///
1630/// Different lookup criteria can find different names. For example, a
1631/// particular scope can have both a struct and a function of the same
1632/// name, and each can be found by certain lookup criteria. For more
1633/// information about lookup criteria, see the documentation for the
1634/// class LookupCriteria.
1635///
1636/// @param S The scope from which unqualified name lookup will
1637/// begin. If the lookup criteria permits, name lookup may also search
1638/// in the parent scopes.
1639///
James Dennett91738ff2012-06-22 10:32:46 +00001640/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1641/// look up and the lookup kind), and is updated with the results of lookup
1642/// including zero or more declarations and possibly additional information
1643/// used to diagnose ambiguities.
Douglas Gregor34074322009-01-14 22:20:51 +00001644///
James Dennett91738ff2012-06-22 10:32:46 +00001645/// @returns \c true if lookup succeeded and false otherwise.
John McCall27b18f82009-11-17 02:14:36 +00001646bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1647 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001648 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001649
John McCall27b18f82009-11-17 02:14:36 +00001650 LookupNameKind NameKind = R.getLookupKind();
1651
David Blaikiebbafb8a2012-03-11 07:00:24 +00001652 if (!getLangOpts().CPlusPlus) {
Douglas Gregor34074322009-01-14 22:20:51 +00001653 // Unqualified name lookup in C/Objective-C is purely lexical, so
1654 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001655 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001656 // Find the nearest non-transparent declaration scope.
1657 while (!(S->getFlags() & Scope::DeclScope) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001658 (S->getEntity() && S->getEntity()->isTransparentContext()))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001659 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001660 }
1661
Richard Smith541b38b2013-09-20 01:15:31 +00001662 // When performing a scope lookup, we want to find local extern decls.
1663 FindLocalExternScope FindLocals(R);
1664
Douglas Gregor34074322009-01-14 22:20:51 +00001665 // Scan up the scope chain looking for a decl that matches this
1666 // identifier that is in the appropriate namespace. This search
1667 // should not take long, as shadowing of names is uncommon, and
1668 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001669 bool LeftStartingScope = false;
1670
Douglas Gregored8f2882009-01-30 01:04:22 +00001671 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001672 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001673 I != IEnd; ++I)
Richard Smith0e5d7b82013-07-25 23:08:39 +00001674 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001675 if (NameKind == LookupRedeclarationWithLinkage) {
1676 // Determine whether this (or a previous) declaration is
1677 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001678 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001679 LeftStartingScope = true;
1680
1681 // If we found something outside of our starting scope that
1682 // does not have linkage, skip it.
Richard Smith1c34fb72013-08-13 18:18:50 +00001683 if (LeftStartingScope && !((*I)->hasLinkage())) {
1684 R.setShadowed();
Douglas Gregoreddf4332009-02-24 20:03:32 +00001685 continue;
Richard Smith1c34fb72013-08-13 18:18:50 +00001686 }
Douglas Gregoreddf4332009-02-24 20:03:32 +00001687 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001688 else if (NameKind == LookupObjCImplicitSelfParam &&
1689 !isa<ImplicitParamDecl>(*I))
1690 continue;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001691
Douglas Gregor4a814562011-12-14 16:03:29 +00001692 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001693
Douglas Gregorb59643b2012-01-03 23:26:26 +00001694 // Check whether there are any other declarations with the same name
1695 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001696 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001697 // Find the scope in which this declaration was declared (if it
1698 // actually exists in a Scope).
1699 while (S && !S->isDeclScope(D))
1700 S = S->getParent();
1701
1702 // If the scope containing the declaration is the translation unit,
1703 // then we'll need to perform our checks based on the matching
1704 // DeclContexts rather than matching scopes.
1705 if (S && isNamespaceOrTranslationUnitScope(S))
Craig Topperc3ec1492014-05-26 06:22:03 +00001706 S = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001707
1708 // Compute the DeclContext, if we need it.
Craig Topperc3ec1492014-05-26 06:22:03 +00001709 DeclContext *DC = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001710 if (!S)
1711 DC = (*I)->getDeclContext()->getRedeclContext();
1712
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001713 IdentifierResolver::iterator LastI = I;
1714 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001715 if (S) {
1716 // Match based on scope.
1717 if (!S->isDeclScope(*LastI))
1718 break;
1719 } else {
1720 // Match based on DeclContext.
1721 DeclContext *LastDC
1722 = (*LastI)->getDeclContext()->getRedeclContext();
1723 if (!LastDC->Equals(DC))
1724 break;
1725 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001726
1727 // If the declaration is in the right namespace and visible, add it.
1728 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1729 R.addDecl(LastD);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001730 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001731
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001732 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001733 }
Richard Smith541b38b2013-09-20 01:15:31 +00001734
John McCall9f3059a2009-10-09 21:13:30 +00001735 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001736 }
Douglas Gregor34074322009-01-14 22:20:51 +00001737 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001738 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001739 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001740 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001741 }
1742
1743 // If we didn't find a use of this identifier, and if the identifier
1744 // corresponds to a compiler builtin, create the decl object for the builtin
1745 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001746 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1747 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001748
Axel Naumann016538a2011-02-24 16:47:47 +00001749 // If we didn't find a use of this identifier, the ExternalSource
1750 // may be able to handle the situation.
1751 // Note: some lookup failures are expected!
1752 // See e.g. R.isForRedeclaration().
1753 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001754}
1755
John McCall6538c932009-10-10 05:48:19 +00001756/// @brief Perform qualified name lookup in the namespaces nominated by
1757/// using directives by the given context.
1758///
1759/// C++98 [namespace.qual]p2:
James Dennett51a8d8b2012-06-19 21:05:49 +00001760/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6538c932009-10-10 05:48:19 +00001761/// (where X is the global namespace), let S be the set of all
1762/// declarations of m in X and in the transitive closure of all
1763/// namespaces nominated by using-directives in X and its used
1764/// namespaces, except that using-directives are ignored in any
1765/// namespace, including X, directly containing one or more
1766/// declarations of m. No namespace is searched more than once in
1767/// the lookup of a name. If S is the empty set, the program is
1768/// ill-formed. Otherwise, if S has exactly one member, or if the
1769/// context of the reference is a using-declaration
1770/// (namespace.udecl), S is the required set of declarations of
1771/// m. Otherwise if the use of m is not one that allows a unique
1772/// declaration to be chosen from S, the program is ill-formed.
James Dennett51a8d8b2012-06-19 21:05:49 +00001773///
John McCall6538c932009-10-10 05:48:19 +00001774/// C++98 [namespace.qual]p5:
1775/// During the lookup of a qualified namespace member name, if the
1776/// lookup finds more than one declaration of the member, and if one
1777/// declaration introduces a class name or enumeration name and the
1778/// other declarations either introduce the same object, the same
1779/// enumerator or a set of functions, the non-type name hides the
1780/// class or enumeration name if and only if the declarations are
1781/// from the same namespace; otherwise (the declarations are from
1782/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001783static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001784 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001785 assert(StartDC->isFileContext() && "start context is not a file context");
1786
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001787 DeclContext::udir_range UsingDirectives = StartDC->using_directives();
1788 if (UsingDirectives.begin() == UsingDirectives.end()) return false;
John McCall6538c932009-10-10 05:48:19 +00001789
1790 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001791 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001792 Visited.insert(StartDC);
1793
1794 // We have not yet looked into these namespaces, much less added
1795 // their "using-children" to the queue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001796 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001797
1798 // We have already looked into the initial namespace; seed the queue
1799 // with its using-children.
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001800 for (auto *I : UsingDirectives) {
1801 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +00001802 if (Visited.insert(ND).second)
John McCall6538c932009-10-10 05:48:19 +00001803 Queue.push_back(ND);
1804 }
1805
1806 // The easiest way to implement the restriction in [namespace.qual]p5
1807 // is to check whether any of the individual results found a tag
1808 // and, if so, to declare an ambiguity if the final result is not
1809 // a tag.
1810 bool FoundTag = false;
1811 bool FoundNonTag = false;
1812
John McCall5cebab12009-11-18 07:57:50 +00001813 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001814
1815 bool Found = false;
1816 while (!Queue.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001817 NamespaceDecl *ND = Queue.pop_back_val();
John McCall6538c932009-10-10 05:48:19 +00001818
1819 // We go through some convolutions here to avoid copying results
1820 // between LookupResults.
1821 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001822 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001823 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001824
1825 if (FoundDirect) {
1826 // First do any local hiding.
1827 DirectR.resolveKind();
1828
1829 // If the local result is a tag, remember that.
1830 if (DirectR.isSingleTagDecl())
1831 FoundTag = true;
1832 else
1833 FoundNonTag = true;
1834
1835 // Append the local results to the total results if necessary.
1836 if (UseLocal) {
1837 R.addAllDecls(LocalR);
1838 LocalR.clear();
1839 }
1840 }
1841
1842 // If we find names in this namespace, ignore its using directives.
1843 if (FoundDirect) {
1844 Found = true;
1845 continue;
1846 }
1847
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001848 for (auto I : ND->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00001849 NamespaceDecl *Nom = I->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +00001850 if (Visited.insert(Nom).second)
John McCall6538c932009-10-10 05:48:19 +00001851 Queue.push_back(Nom);
1852 }
1853 }
1854
1855 if (Found) {
1856 if (FoundTag && FoundNonTag)
1857 R.setAmbiguousQualifiedTagHiding();
1858 else
1859 R.resolveKind();
1860 }
1861
1862 return Found;
1863}
1864
Douglas Gregor39982192010-08-15 06:18:01 +00001865/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001866static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00001867 CXXBasePath &Path, DeclarationName Name) {
Douglas Gregor39982192010-08-15 06:18:01 +00001868 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001869
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00001870 Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00001871 return !Path.Decls.empty();
Douglas Gregor39982192010-08-15 06:18:01 +00001872}
1873
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001874/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001875/// static members, nested types, and enumerators.
1876template<typename InputIterator>
1877static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1878 Decl *D = (*First)->getUnderlyingDecl();
1879 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1880 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001881
Douglas Gregorc0d24902010-10-22 22:08:47 +00001882 if (isa<CXXMethodDecl>(D)) {
1883 // Determine whether all of the methods are static.
1884 bool AllMethodsAreStatic = true;
1885 for(; First != Last; ++First) {
1886 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001887
Douglas Gregorc0d24902010-10-22 22:08:47 +00001888 if (!isa<CXXMethodDecl>(D)) {
1889 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1890 break;
1891 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001892
Douglas Gregorc0d24902010-10-22 22:08:47 +00001893 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1894 AllMethodsAreStatic = false;
1895 break;
1896 }
1897 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001898
Douglas Gregorc0d24902010-10-22 22:08:47 +00001899 if (AllMethodsAreStatic)
1900 return true;
1901 }
1902
1903 return false;
1904}
1905
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001906/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001907///
1908/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1909/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001910/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001911///
1912/// Different lookup criteria can find different names. For example, a
1913/// particular scope can have both a struct and a function of the same
1914/// name, and each can be found by certain lookup criteria. For more
1915/// information about lookup criteria, see the documentation for the
1916/// class LookupCriteria.
1917///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001918/// \param R captures both the lookup criteria and any lookup results found.
1919///
1920/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001921/// search. If the lookup criteria permits, name lookup may also search
1922/// in the parent contexts or (for C++ classes) base classes.
1923///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001924/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001925/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001926///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001927/// \returns true if lookup succeeded, false if it failed.
1928bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1929 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001930 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001931
John McCall27b18f82009-11-17 02:14:36 +00001932 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001933 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001934
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001935 // Make sure that the declaration context is complete.
1936 assert((!isa<TagDecl>(LookupCtx) ||
1937 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00001938 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith7d137e32012-03-23 03:33:32 +00001939 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001940 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001941
Eugene Leviant0d8103e2015-11-18 12:48:05 +00001942 struct QualifiedLookupInScope {
1943 bool oldVal;
1944 DeclContext *Context;
1945 // Set flag in DeclContext informing debugger that we're looking for qualified name
1946 QualifiedLookupInScope(DeclContext *ctx) : Context(ctx) {
1947 oldVal = ctx->setUseQualifiedLookup();
1948 }
1949 ~QualifiedLookupInScope() {
1950 Context->setUseQualifiedLookup(oldVal);
1951 }
1952 } QL(LookupCtx);
1953
Douglas Gregord3a59182010-02-12 05:48:04 +00001954 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001955 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001956 if (isa<CXXRecordDecl>(LookupCtx))
1957 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001958 return true;
1959 }
Douglas Gregor34074322009-01-14 22:20:51 +00001960
John McCall6538c932009-10-10 05:48:19 +00001961 // Don't descend into implied contexts for redeclarations.
1962 // C++98 [namespace.qual]p6:
1963 // In a declaration for a namespace member in which the
1964 // declarator-id is a qualified-id, given that the qualified-id
1965 // for the namespace member has the form
1966 // nested-name-specifier unqualified-id
1967 // the unqualified-id shall name a member of the namespace
1968 // designated by the nested-name-specifier.
1969 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001970 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001971 return false;
1972
John McCall27b18f82009-11-17 02:14:36 +00001973 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001974 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001975 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001976
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001977 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001978 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001979 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001980 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001981 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001982
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001983 // If we're performing qualified name lookup into a dependent class,
1984 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001985 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001986 // template instantiation time (at which point all bases will be available)
1987 // or we have to fail.
1988 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1989 LookupRec->hasAnyDependentBases()) {
1990 R.setNotFoundInCurrentInstantiation();
1991 return false;
1992 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001993
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001994 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001995 CXXBasePaths Paths;
1996 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001997
1998 // Look for this member in our base classes
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00001999 bool (*BaseCallback)(const CXXBaseSpecifier *Specifier, CXXBasePath &Path,
2000 DeclarationName Name) = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00002001 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00002002 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00002003 case LookupOrdinaryName:
2004 case LookupMemberName:
2005 case LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +00002006 case LookupLocalFriendName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00002007 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
2008 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002009
Douglas Gregor36d1b142009-10-06 17:59:45 +00002010 case LookupTagName:
2011 BaseCallback = &CXXRecordDecl::FindTagMember;
2012 break;
John McCall84d87672009-12-10 09:41:52 +00002013
Douglas Gregor39982192010-08-15 06:18:01 +00002014 case LookupAnyName:
2015 BaseCallback = &LookupAnyMember;
2016 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002017
John McCall84d87672009-12-10 09:41:52 +00002018 case LookupUsingDeclName:
2019 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002020
Douglas Gregor36d1b142009-10-06 17:59:45 +00002021 case LookupOperatorName:
2022 case LookupNamespaceName:
2023 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002024 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00002025 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00002026 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002027
Douglas Gregor36d1b142009-10-06 17:59:45 +00002028 case LookupNestedNameSpecifierName:
2029 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
2030 break;
2031 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002032
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00002033 DeclarationName Name = R.getLookupName();
2034 if (!LookupRec->lookupInBases(
2035 [=](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
2036 return BaseCallback(Specifier, Path, Name);
2037 },
2038 Paths))
John McCall9f3059a2009-10-09 21:13:30 +00002039 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002040
John McCall553c0792010-01-23 00:46:32 +00002041 R.setNamingClass(LookupRec);
2042
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002043 // C++ [class.member.lookup]p2:
2044 // [...] If the resulting set of declarations are not all from
2045 // sub-objects of the same type, or the set has a nonstatic member
2046 // and includes members from distinct sub-objects, there is an
2047 // ambiguity and the program is ill-formed. Otherwise that set is
2048 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002049 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00002050 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00002051 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002052
Douglas Gregor36d1b142009-10-06 17:59:45 +00002053 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002054 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00002055 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002056
John McCall401982f2010-01-20 21:53:11 +00002057 // Pick the best (i.e. most permissive i.e. numerically lowest) access
2058 // across all paths.
2059 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002060
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002061 // Determine whether we're looking at a distinct sub-object or not.
2062 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00002063 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002064 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
2065 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00002066 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002067 }
2068
Douglas Gregorc0d24902010-10-22 22:08:47 +00002069 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002070 != Context.getCanonicalType(PathElement.Base->getType())) {
2071 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00002072 // different types. If the declaration sets aren't the same, this
Nikola Smiljanic1c125682014-07-09 05:42:35 +00002073 // lookup is ambiguous.
David Blaikieff7d47a2012-12-19 00:45:41 +00002074 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00002075 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikieff7d47a2012-12-19 00:45:41 +00002076 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
2077 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002078
David Blaikieff7d47a2012-12-19 00:45:41 +00002079 while (FirstD != FirstPath->Decls.end() &&
2080 CurrentD != Path->Decls.end()) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00002081 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
2082 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
2083 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002084
Douglas Gregorc0d24902010-10-22 22:08:47 +00002085 ++FirstD;
2086 ++CurrentD;
2087 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002088
David Blaikieff7d47a2012-12-19 00:45:41 +00002089 if (FirstD == FirstPath->Decls.end() &&
2090 CurrentD == Path->Decls.end())
Douglas Gregorc0d24902010-10-22 22:08:47 +00002091 continue;
2092 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002093
John McCall9f3059a2009-10-09 21:13:30 +00002094 R.setAmbiguousBaseSubobjectTypes(Paths);
2095 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002096 }
2097
Douglas Gregorc0d24902010-10-22 22:08:47 +00002098 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002099 // We have a different subobject of the same type.
2100
2101 // C++ [class.member.lookup]p5:
2102 // A static member, a nested type or an enumerator defined in
2103 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00002104 // has more than one base class subobject of type T.
David Blaikieff7d47a2012-12-19 00:45:41 +00002105 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002106 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002107
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002108 // We have found a nonstatic member name in multiple, distinct
2109 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00002110 R.setAmbiguousBaseSubobjects(Paths);
2111 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002112 }
2113 }
2114
2115 // Lookup in a base class succeeded; return these results.
2116
Aaron Ballman1e606f42014-07-15 22:03:49 +00002117 for (auto *D : Paths.front().Decls) {
John McCall553c0792010-01-23 00:46:32 +00002118 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
2119 D->getAccess());
2120 R.addDecl(D, AS);
2121 }
John McCall9f3059a2009-10-09 21:13:30 +00002122 R.resolveKind();
2123 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00002124}
2125
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00002126/// \brief Performs qualified name lookup or special type of lookup for
2127/// "__super::" scope specifier.
2128///
2129/// This routine is a convenience overload meant to be called from contexts
2130/// that need to perform a qualified name lookup with an optional C++ scope
2131/// specifier that might require special kind of lookup.
2132///
2133/// \param R captures both the lookup criteria and any lookup results found.
2134///
2135/// \param LookupCtx The context in which qualified name lookup will
2136/// search.
2137///
2138/// \param SS An optional C++ scope-specifier.
2139///
2140/// \returns true if lookup succeeded, false if it failed.
2141bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2142 CXXScopeSpec &SS) {
2143 auto *NNS = SS.getScopeRep();
2144 if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
2145 return LookupInSuper(R, NNS->getAsRecordDecl());
2146 else
2147
2148 return LookupQualifiedName(R, LookupCtx);
2149}
2150
Douglas Gregor34074322009-01-14 22:20:51 +00002151/// @brief Performs name lookup for a name that was parsed in the
2152/// source code, and may contain a C++ scope specifier.
2153///
2154/// This routine is a convenience routine meant to be called from
2155/// contexts that receive a name and an optional C++ scope specifier
2156/// (e.g., "N::M::x"). It will then perform either qualified or
2157/// unqualified name lookup (with LookupQualifiedName or LookupName,
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002158/// respectively) on the given name and return those results. It will
2159/// perform a special type of lookup for "__super::" scope specifier.
Douglas Gregor34074322009-01-14 22:20:51 +00002160///
2161/// @param S The scope from which unqualified name lookup will
2162/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00002163///
Douglas Gregore861bac2009-08-25 22:51:20 +00002164/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00002165///
Douglas Gregore861bac2009-08-25 22:51:20 +00002166/// @param EnteringContext Indicates whether we are going to enter the
2167/// context of the scope-specifier SS (if present).
2168///
John McCall9f3059a2009-10-09 21:13:30 +00002169/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002170bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00002171 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00002172 if (SS && SS->isInvalid()) {
2173 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002174 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00002175 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00002176 }
Mike Stump11289f42009-09-09 15:08:12 +00002177
Douglas Gregore861bac2009-08-25 22:51:20 +00002178 if (SS && SS->isSet()) {
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002179 NestedNameSpecifier *NNS = SS->getScopeRep();
2180 if (NNS->getKind() == NestedNameSpecifier::Super)
2181 return LookupInSuper(R, NNS->getAsRecordDecl());
2182
Douglas Gregore861bac2009-08-25 22:51:20 +00002183 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00002184 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00002185 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00002186 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00002187 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002188
John McCall27b18f82009-11-17 02:14:36 +00002189 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00002190 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00002191 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002192
Douglas Gregore861bac2009-08-25 22:51:20 +00002193 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00002194 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00002195 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00002196 R.setNotFoundInCurrentInstantiation();
2197 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00002198 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00002199 }
2200
Mike Stump11289f42009-09-09 15:08:12 +00002201 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00002202 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00002203}
2204
Nikola Smiljanic67860242014-09-26 00:28:20 +00002205/// \brief Perform qualified name lookup into all base classes of the given
2206/// class.
2207///
2208/// \param R captures both the lookup criteria and any lookup results found.
2209///
2210/// \param Class The context in which qualified name lookup will
2211/// search. Name lookup will search in all base classes merging the results.
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002212///
2213/// @returns True if any decls were found (but possibly ambiguous)
2214bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
John McCallf4a1b772015-09-09 23:04:17 +00002215 // The access-control rules we use here are essentially the rules for
2216 // doing a lookup in Class that just magically skipped the direct
2217 // members of Class itself. That is, the naming class is Class, and the
2218 // access includes the access of the base.
Nikola Smiljanic67860242014-09-26 00:28:20 +00002219 for (const auto &BaseSpec : Class->bases()) {
2220 CXXRecordDecl *RD = cast<CXXRecordDecl>(
2221 BaseSpec.getType()->castAs<RecordType>()->getDecl());
2222 LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
2223 Result.setBaseObjectType(Context.getRecordType(Class));
2224 LookupQualifiedName(Result, RD);
John McCallf4a1b772015-09-09 23:04:17 +00002225
2226 // Copy the lookup results into the target, merging the base's access into
2227 // the path access.
2228 for (auto I = Result.begin(), E = Result.end(); I != E; ++I) {
2229 R.addDecl(I.getDecl(),
2230 CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(),
2231 I.getAccess()));
2232 }
2233
2234 Result.suppressDiagnostics();
Nikola Smiljanic67860242014-09-26 00:28:20 +00002235 }
2236
2237 R.resolveKind();
John McCallf4a1b772015-09-09 23:04:17 +00002238 R.setNamingClass(Class);
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002239
2240 return !R.empty();
Nikola Smiljanic67860242014-09-26 00:28:20 +00002241}
Douglas Gregor889ceb72009-02-03 19:21:40 +00002242
James Dennett41725122012-06-22 10:16:05 +00002243/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002244/// from name lookup.
2245///
James Dennett41725122012-06-22 10:16:05 +00002246/// \param Result The result of the ambiguous lookup to be diagnosed.
Serge Pavlov99292092013-08-29 07:23:24 +00002247void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002248 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
2249
John McCall27b18f82009-11-17 02:14:36 +00002250 DeclarationName Name = Result.getLookupName();
2251 SourceLocation NameLoc = Result.getNameLoc();
2252 SourceRange LookupRange = Result.getContextRange();
2253
John McCall6538c932009-10-10 05:48:19 +00002254 switch (Result.getAmbiguityKind()) {
2255 case LookupResult::AmbiguousBaseSubobjects: {
2256 CXXBasePaths *Paths = Result.getBasePaths();
2257 QualType SubobjectType = Paths->front().back().Base->getType();
2258 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
2259 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
2260 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002261
David Blaikieff7d47a2012-12-19 00:45:41 +00002262 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6538c932009-10-10 05:48:19 +00002263 while (isa<CXXMethodDecl>(*Found) &&
2264 cast<CXXMethodDecl>(*Found)->isStatic())
2265 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002266
John McCall6538c932009-10-10 05:48:19 +00002267 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
Serge Pavlov99292092013-08-29 07:23:24 +00002268 break;
John McCall6538c932009-10-10 05:48:19 +00002269 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00002270
John McCall6538c932009-10-10 05:48:19 +00002271 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00002272 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
2273 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002274
John McCall6538c932009-10-10 05:48:19 +00002275 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002276 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00002277 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
2278 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002279 Path != PathEnd; ++Path) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002280 Decl *D = Path->Decls.front();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002281 if (DeclsPrinted.insert(D).second)
2282 Diag(D->getLocation(), diag::note_ambiguous_member_found);
2283 }
Serge Pavlov99292092013-08-29 07:23:24 +00002284 break;
Douglas Gregor1c846b02009-01-16 00:38:09 +00002285 }
2286
John McCall6538c932009-10-10 05:48:19 +00002287 case LookupResult::AmbiguousTagHiding: {
2288 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00002289
Nick Lewycky4b81fc872015-10-18 20:32:12 +00002290 llvm::SmallPtrSet<NamedDecl*, 8> TagDecls;
John McCall6538c932009-10-10 05:48:19 +00002291
Aaron Ballman1e606f42014-07-15 22:03:49 +00002292 for (auto *D : Result)
2293 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
John McCall6538c932009-10-10 05:48:19 +00002294 TagDecls.insert(TD);
2295 Diag(TD->getLocation(), diag::note_hidden_tag);
2296 }
2297
Aaron Ballman1e606f42014-07-15 22:03:49 +00002298 for (auto *D : Result)
2299 if (!isa<TagDecl>(D))
2300 Diag(D->getLocation(), diag::note_hiding_object);
John McCall6538c932009-10-10 05:48:19 +00002301
2302 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00002303 LookupResult::Filter F = Result.makeFilter();
2304 while (F.hasNext()) {
2305 if (TagDecls.count(F.next()))
2306 F.erase();
2307 }
2308 F.done();
Serge Pavlov99292092013-08-29 07:23:24 +00002309 break;
John McCall6538c932009-10-10 05:48:19 +00002310 }
2311
2312 case LookupResult::AmbiguousReference: {
2313 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002314
Aaron Ballman1e606f42014-07-15 22:03:49 +00002315 for (auto *D : Result)
2316 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
Serge Pavlov99292092013-08-29 07:23:24 +00002317 break;
John McCall6538c932009-10-10 05:48:19 +00002318 }
Serge Pavlov99292092013-08-29 07:23:24 +00002319 }
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002320}
Douglas Gregore254f902009-02-04 00:32:51 +00002321
John McCallf24d7bb2010-05-28 18:45:08 +00002322namespace {
2323 struct AssociatedLookup {
John McCall7d8b0412012-08-24 20:38:34 +00002324 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallf24d7bb2010-05-28 18:45:08 +00002325 Sema::AssociatedNamespaceSet &Namespaces,
2326 Sema::AssociatedClassSet &Classes)
John McCall7d8b0412012-08-24 20:38:34 +00002327 : S(S), Namespaces(Namespaces), Classes(Classes),
2328 InstantiationLoc(InstantiationLoc) {
John McCallf24d7bb2010-05-28 18:45:08 +00002329 }
2330
2331 Sema &S;
2332 Sema::AssociatedNamespaceSet &Namespaces;
2333 Sema::AssociatedClassSet &Classes;
John McCall7d8b0412012-08-24 20:38:34 +00002334 SourceLocation InstantiationLoc;
John McCallf24d7bb2010-05-28 18:45:08 +00002335 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002336} // end anonymous namespace
John McCallf24d7bb2010-05-28 18:45:08 +00002337
Mike Stump11289f42009-09-09 15:08:12 +00002338static void
John McCallf24d7bb2010-05-28 18:45:08 +00002339addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00002340
Douglas Gregor8b895222010-04-30 07:08:38 +00002341static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
2342 DeclContext *Ctx) {
2343 // Add the associated namespace for this class.
2344
2345 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
2346 // be a locally scoped record.
2347
Sebastian Redlbd595762010-08-31 20:53:31 +00002348 // We skip out of inline namespaces. The innermost non-inline namespace
2349 // contains all names of all its nested inline namespaces anyway, so we can
2350 // replace the entire inline namespace tree with its root.
2351 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
2352 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00002353 Ctx = Ctx->getParent();
2354
John McCallc7e8e792009-08-07 22:18:02 +00002355 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00002356 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00002357}
Douglas Gregor197e5f72009-07-08 07:51:57 +00002358
Mike Stump11289f42009-09-09 15:08:12 +00002359// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00002360// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00002361static void
John McCallf24d7bb2010-05-28 18:45:08 +00002362addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2363 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002364 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00002365 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00002366 switch (Arg.getKind()) {
2367 case TemplateArgument::Null:
2368 break;
Mike Stump11289f42009-09-09 15:08:12 +00002369
Douglas Gregor197e5f72009-07-08 07:51:57 +00002370 case TemplateArgument::Type:
2371 // [...] the namespaces and classes associated with the types of the
2372 // template arguments provided for template type parameters (excluding
2373 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00002374 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00002375 break;
Mike Stump11289f42009-09-09 15:08:12 +00002376
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002377 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002378 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00002379 // [...] the namespaces in which any template template arguments are
2380 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00002381 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002382 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00002383 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002384 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002385 DeclContext *Ctx = ClassTemplate->getDeclContext();
2386 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002387 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002388 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002389 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002390 }
2391 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002392 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002393
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002394 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00002395 case TemplateArgument::Integral:
2396 case TemplateArgument::Expression:
Eli Friedmanb826a002012-09-26 02:36:12 +00002397 case TemplateArgument::NullPtr:
Mike Stump11289f42009-09-09 15:08:12 +00002398 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00002399 // associated namespaces. ]
2400 break;
Mike Stump11289f42009-09-09 15:08:12 +00002401
Douglas Gregor197e5f72009-07-08 07:51:57 +00002402 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00002403 for (const auto &P : Arg.pack_elements())
2404 addAssociatedClassesAndNamespaces(Result, P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002405 break;
2406 }
2407}
2408
Douglas Gregore254f902009-02-04 00:32:51 +00002409// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00002410// argument-dependent lookup with an argument of class type
2411// (C++ [basic.lookup.koenig]p2).
2412static void
John McCallf24d7bb2010-05-28 18:45:08 +00002413addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2414 CXXRecordDecl *Class) {
2415
2416 // Just silently ignore anything whose name is __va_list_tag.
2417 if (Class->getDeclName() == Result.S.VAListTagName)
2418 return;
2419
Douglas Gregore254f902009-02-04 00:32:51 +00002420 // C++ [basic.lookup.koenig]p2:
2421 // [...]
2422 // -- If T is a class type (including unions), its associated
2423 // classes are: the class itself; the class of which it is a
2424 // member, if any; and its direct and indirect base
2425 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00002426 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00002427
2428 // Add the class of which it is a member, if any.
2429 DeclContext *Ctx = Class->getDeclContext();
2430 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002431 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002432 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002433 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002434
Douglas Gregore254f902009-02-04 00:32:51 +00002435 // Add the class itself. If we've already seen this class, we don't
2436 // need to visit base classes.
Richard Smith594461f2014-03-14 22:07:27 +00002437 //
2438 // FIXME: That's not correct, we may have added this class only because it
2439 // was the enclosing class of another class, and in that case we won't have
2440 // added its base classes yet.
David Blaikie82e95a32014-11-19 07:49:47 +00002441 if (!Result.Classes.insert(Class).second)
Douglas Gregore254f902009-02-04 00:32:51 +00002442 return;
2443
Mike Stump11289f42009-09-09 15:08:12 +00002444 // -- If T is a template-id, its associated namespaces and classes are
2445 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002446 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00002447 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00002448 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00002449 // namespaces in which any template template arguments are defined; and
2450 // the classes in which any member templates used as template template
2451 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00002452 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00002453 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00002454 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2455 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2456 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002457 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002458 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002459 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002460
Douglas Gregor197e5f72009-07-08 07:51:57 +00002461 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2462 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00002463 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002464 }
Mike Stump11289f42009-09-09 15:08:12 +00002465
John McCall67da35c2010-02-04 22:26:26 +00002466 // Only recurse into base classes for complete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00002467 if (!Result.S.isCompleteType(Result.InstantiationLoc,
2468 Result.S.Context.getRecordType(Class)))
Richard Smith594461f2014-03-14 22:07:27 +00002469 return;
John McCall67da35c2010-02-04 22:26:26 +00002470
Douglas Gregore254f902009-02-04 00:32:51 +00002471 // Add direct and indirect base classes along with their associated
2472 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002473 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00002474 Bases.push_back(Class);
2475 while (!Bases.empty()) {
2476 // Pop this class off the stack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002477 Class = Bases.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002478
2479 // Visit the base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +00002480 for (const auto &Base : Class->bases()) {
2481 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00002482 // In dependent contexts, we do ADL twice, and the first time around,
2483 // the base type might be a dependent TemplateSpecializationType, or a
2484 // TemplateTypeParmType. If that happens, simply ignore it.
2485 // FIXME: If we want to support export, we probably need to add the
2486 // namespace of the template in a TemplateSpecializationType, or even
2487 // the classes and namespaces of known non-dependent arguments.
2488 if (!BaseType)
2489 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002490 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
David Blaikie82e95a32014-11-19 07:49:47 +00002491 if (Result.Classes.insert(BaseDecl).second) {
Douglas Gregore254f902009-02-04 00:32:51 +00002492 // Find the associated namespace for this base class.
2493 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00002494 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00002495
2496 // Make sure we visit the bases of this base class.
2497 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2498 Bases.push_back(BaseDecl);
2499 }
2500 }
2501 }
2502}
2503
2504// \brief Add the associated classes and namespaces for
2505// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00002506// (C++ [basic.lookup.koenig]p2).
2507static void
John McCallf24d7bb2010-05-28 18:45:08 +00002508addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00002509 // C++ [basic.lookup.koenig]p2:
2510 //
2511 // For each argument type T in the function call, there is a set
2512 // of zero or more associated namespaces and a set of zero or more
2513 // associated classes to be considered. The sets of namespaces and
2514 // classes is determined entirely by the types of the function
2515 // arguments (and the namespace of any template template
2516 // argument). Typedef names and using-declarations used to specify
2517 // the types do not contribute to this set. The sets of namespaces
2518 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00002519
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002520 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00002521 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2522
Douglas Gregore254f902009-02-04 00:32:51 +00002523 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00002524 switch (T->getTypeClass()) {
2525
2526#define TYPE(Class, Base)
2527#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2528#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2529#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2530#define ABSTRACT_TYPE(Class, Base)
2531#include "clang/AST/TypeNodes.def"
2532 // T is canonical. We can also ignore dependent types because
2533 // we don't need to do ADL at the definition point, but if we
2534 // wanted to implement template export (or if we find some other
2535 // use for associated classes and namespaces...) this would be
2536 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00002537 break;
Douglas Gregore254f902009-02-04 00:32:51 +00002538
John McCall0af3d3b2010-05-28 06:08:54 +00002539 // -- If T is a pointer to U or an array of U, its associated
2540 // namespaces and classes are those associated with U.
2541 case Type::Pointer:
2542 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2543 continue;
2544 case Type::ConstantArray:
2545 case Type::IncompleteArray:
2546 case Type::VariableArray:
2547 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2548 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002549
John McCall0af3d3b2010-05-28 06:08:54 +00002550 // -- If T is a fundamental type, its associated sets of
2551 // namespaces and classes are both empty.
2552 case Type::Builtin:
2553 break;
2554
2555 // -- If T is a class type (including unions), its associated
2556 // classes are: the class itself; the class of which it is a
2557 // member, if any; and its direct and indirect base
2558 // classes. Its associated namespaces are the namespaces in
2559 // which its associated classes are defined.
2560 case Type::Record: {
Richard Smith82b8d4e2015-12-18 22:19:11 +00002561 CXXRecordDecl *Class =
2562 cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002563 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00002564 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00002565 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00002566
John McCall0af3d3b2010-05-28 06:08:54 +00002567 // -- If T is an enumeration type, its associated namespace is
2568 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002569 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00002570 // it has no associated class.
2571 case Type::Enum: {
2572 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002573
John McCall0af3d3b2010-05-28 06:08:54 +00002574 DeclContext *Ctx = Enum->getDeclContext();
2575 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002576 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002577
John McCall0af3d3b2010-05-28 06:08:54 +00002578 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002579 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00002580
John McCall0af3d3b2010-05-28 06:08:54 +00002581 break;
2582 }
2583
2584 // -- If T is a function type, its associated namespaces and
2585 // classes are those associated with the function parameter
2586 // types and those associated with the return type.
2587 case Type::FunctionProto: {
2588 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002589 for (const auto &Arg : Proto->param_types())
2590 Queue.push_back(Arg.getTypePtr());
John McCall0af3d3b2010-05-28 06:08:54 +00002591 // fallthrough
2592 }
2593 case Type::FunctionNoProto: {
2594 const FunctionType *FnType = cast<FunctionType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00002595 T = FnType->getReturnType().getTypePtr();
John McCall0af3d3b2010-05-28 06:08:54 +00002596 continue;
2597 }
2598
2599 // -- If T is a pointer to a member function of a class X, its
2600 // associated namespaces and classes are those associated
2601 // with the function parameter types and return type,
2602 // together with those associated with X.
2603 //
2604 // -- If T is a pointer to a data member of class X, its
2605 // associated namespaces and classes are those associated
2606 // with the member type together with those associated with
2607 // X.
2608 case Type::MemberPointer: {
2609 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2610
2611 // Queue up the class type into which this points.
2612 Queue.push_back(MemberPtr->getClass());
2613
2614 // And directly continue with the pointee type.
2615 T = MemberPtr->getPointeeType().getTypePtr();
2616 continue;
2617 }
2618
2619 // As an extension, treat this like a normal pointer.
2620 case Type::BlockPointer:
2621 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2622 continue;
2623
2624 // References aren't covered by the standard, but that's such an
2625 // obvious defect that we cover them anyway.
2626 case Type::LValueReference:
2627 case Type::RValueReference:
2628 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2629 continue;
2630
2631 // These are fundamental types.
2632 case Type::Vector:
2633 case Type::ExtVector:
2634 case Type::Complex:
2635 break;
2636
Richard Smith27d807c2013-04-30 13:56:41 +00002637 // Non-deduced auto types only get here for error cases.
2638 case Type::Auto:
2639 break;
2640
Douglas Gregor8e936662011-04-12 01:02:45 +00002641 // If T is an Objective-C object or interface type, or a pointer to an
2642 // object or interface type, the associated namespace is the global
2643 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002644 case Type::ObjCObject:
2645 case Type::ObjCInterface:
2646 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002647 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002648 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002649
2650 // Atomic types are just wrappers; use the associations of the
2651 // contained type.
2652 case Type::Atomic:
2653 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2654 continue;
Xiuli Pan9c14e282016-01-09 12:53:17 +00002655 case Type::Pipe:
2656 T = cast<PipeType>(T)->getElementType().getTypePtr();
2657 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002658 }
2659
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002660 if (Queue.empty())
2661 break;
2662 T = Queue.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002663 }
Douglas Gregore254f902009-02-04 00:32:51 +00002664}
2665
2666/// \brief Find the associated classes and namespaces for
2667/// argument-dependent lookup for a call with the given set of
2668/// arguments.
2669///
2670/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002671/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002672/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00002673void Sema::FindAssociatedClassesAndNamespaces(
2674 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2675 AssociatedNamespaceSet &AssociatedNamespaces,
2676 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002677 AssociatedNamespaces.clear();
2678 AssociatedClasses.clear();
2679
John McCall7d8b0412012-08-24 20:38:34 +00002680 AssociatedLookup Result(*this, InstantiationLoc,
2681 AssociatedNamespaces, AssociatedClasses);
John McCallf24d7bb2010-05-28 18:45:08 +00002682
Douglas Gregore254f902009-02-04 00:32:51 +00002683 // C++ [basic.lookup.koenig]p2:
2684 // For each argument type T in the function call, there is a set
2685 // of zero or more associated namespaces and a set of zero or more
2686 // associated classes to be considered. The sets of namespaces and
2687 // classes is determined entirely by the types of the function
2688 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002689 // argument).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002690 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregore254f902009-02-04 00:32:51 +00002691 Expr *Arg = Args[ArgIdx];
2692
2693 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002694 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002695 continue;
2696 }
2697
2698 // [...] In addition, if the argument is the name or address of a
2699 // set of overloaded functions and/or function templates, its
2700 // associated classes and namespaces are the union of those
2701 // associated with each of the members of the set: the namespace
2702 // in which the function or function template is defined and the
2703 // classes and namespaces associated with its (non-dependent)
2704 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002705 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002706 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002707 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002708 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002709
John McCallf24d7bb2010-05-28 18:45:08 +00002710 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2711 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002712
Aaron Ballman1e606f42014-07-15 22:03:49 +00002713 for (const auto *D : ULE->decls()) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002714 // Look through any using declarations to find the underlying function.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002715 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
Douglas Gregore254f902009-02-04 00:32:51 +00002716
2717 // Add the classes and namespaces associated with the parameter
2718 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002719 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002720 }
2721 }
2722}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002723
John McCall5cebab12009-11-18 07:57:50 +00002724NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002725 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002726 LookupNameKind NameKind,
2727 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002728 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002729 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002730 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002731}
2732
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002733/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002734ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002735 SourceLocation IdLoc,
2736 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002737 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002738 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002739 return cast_or_null<ObjCProtocolDecl>(D);
2740}
2741
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002742void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002743 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002744 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002745 // C++ [over.match.oper]p3:
2746 // -- The set of non-member candidates is the result of the
2747 // unqualified lookup of operator@ in the context of the
2748 // expression according to the usual rules for name lookup in
2749 // unqualified function calls (3.4.2) except that all member
Richard Smith100b24a2014-04-17 01:52:14 +00002750 // functions are ignored.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002751 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002752 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2753 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002754
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002755 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
Richard Smith100b24a2014-04-17 01:52:14 +00002756 Functions.append(Operators.begin(), Operators.end());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002757}
2758
Alexis Hunt1da39282011-06-24 02:11:39 +00002759Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002760 CXXSpecialMember SM,
2761 bool ConstArg,
2762 bool VolatileArg,
2763 bool RValueThis,
2764 bool ConstThis,
2765 bool VolatileThis) {
Richard Smith7d125a12012-11-27 21:20:31 +00002766 assert(CanDeclareSpecialMemberFunction(RD) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002767 "doing special member lookup into record that isn't fully complete");
Richard Smith7d125a12012-11-27 21:20:31 +00002768 RD = RD->getDefinition();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002769 if (RValueThis || ConstThis || VolatileThis)
2770 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2771 "constructors and destructors always have unqualified lvalue this");
2772 if (ConstArg || VolatileArg)
2773 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2774 "parameter-less special members can't have qualified arguments");
2775
2776 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002777 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002778 ID.AddInteger(SM);
2779 ID.AddInteger(ConstArg);
2780 ID.AddInteger(VolatileArg);
2781 ID.AddInteger(RValueThis);
2782 ID.AddInteger(ConstThis);
2783 ID.AddInteger(VolatileThis);
2784
2785 void *InsertPoint;
2786 SpecialMemberOverloadResult *Result =
2787 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2788
2789 // This was already cached
2790 if (Result)
2791 return Result;
2792
Alexis Huntba8e18d2011-06-07 00:11:58 +00002793 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2794 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002795 SpecialMemberCache.InsertNode(Result, InsertPoint);
2796
2797 if (SM == CXXDestructor) {
Richard Smith2be35f52012-12-01 02:35:44 +00002798 if (RD->needsImplicitDestructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002799 DeclareImplicitDestructor(RD);
2800 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002801 assert(DD && "record without a destructor");
2802 Result->setMethod(DD);
Richard Smith852265f2012-03-30 20:53:28 +00002803 Result->setKind(DD->isDeleted() ?
2804 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith83c478d2012-04-20 18:46:14 +00002805 SpecialMemberOverloadResult::Success);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002806 return Result;
2807 }
2808
Alexis Hunteef8ee02011-06-10 03:50:41 +00002809 // Prepare for overload resolution. Here we construct a synthetic argument
2810 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002811 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002812 DeclarationName Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002813 Expr *Arg = nullptr;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002814 unsigned NumArgs;
2815
Richard Smith83c478d2012-04-20 18:46:14 +00002816 QualType ArgType = CanTy;
2817 ExprValueKind VK = VK_LValue;
2818
Alexis Hunteef8ee02011-06-10 03:50:41 +00002819 if (SM == CXXDefaultConstructor) {
2820 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2821 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002822 if (RD->needsImplicitDefaultConstructor())
2823 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002824 } else {
2825 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2826 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smith2be35f52012-12-01 02:35:44 +00002827 if (RD->needsImplicitCopyConstructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002828 DeclareImplicitCopyConstructor(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002829 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002830 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002831 } else {
2832 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smith2be35f52012-12-01 02:35:44 +00002833 if (RD->needsImplicitCopyAssignment())
Alexis Hunt1da39282011-06-24 02:11:39 +00002834 DeclareImplicitCopyAssignment(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002835 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002836 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002837 }
2838
Alexis Hunteef8ee02011-06-10 03:50:41 +00002839 if (ConstArg)
2840 ArgType.addConst();
2841 if (VolatileArg)
2842 ArgType.addVolatile();
2843
2844 // This isn't /really/ specified by the standard, but it's implied
2845 // we should be working from an RValue in the case of move to ensure
2846 // that we prefer to bind to rvalue references, and an LValue in the
2847 // case of copy to ensure we don't bind to rvalue references.
2848 // Possibly an XValue is actually correct in the case of move, but
2849 // there is no semantic difference for class types in this restricted
2850 // case.
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002851 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002852 VK = VK_LValue;
2853 else
2854 VK = VK_RValue;
Richard Smith83c478d2012-04-20 18:46:14 +00002855 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00002856
Richard Smith83c478d2012-04-20 18:46:14 +00002857 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2858
2859 if (SM != CXXDefaultConstructor) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002860 NumArgs = 1;
Richard Smith83c478d2012-04-20 18:46:14 +00002861 Arg = &FakeArg;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002862 }
2863
2864 // Create the object argument
2865 QualType ThisTy = CanTy;
2866 if (ConstThis)
2867 ThisTy.addConst();
2868 if (VolatileThis)
2869 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002870 Expr::Classification Classification =
Richard Smith83c478d2012-04-20 18:46:14 +00002871 OpaqueValueExpr(SourceLocation(), ThisTy,
2872 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002873
2874 // Now we perform lookup on the name we computed earlier and do overload
2875 // resolution. Lookup is only performed directly into the class since there
2876 // will always be a (possibly implicit) declaration to shadow any others.
Richard Smith100b24a2014-04-17 01:52:14 +00002877 OverloadCandidateSet OCS(RD->getLocation(), OverloadCandidateSet::CSK_Normal);
David Blaikieff7d47a2012-12-19 00:45:41 +00002878 DeclContext::lookup_result R = RD->lookup(Name);
Richard Smith8c37ab52015-02-11 01:48:47 +00002879
2880 if (R.empty()) {
2881 // We might have no default constructor because we have a lambda's closure
2882 // type, rather than because there's some other declared constructor.
2883 // Every class has a copy/move constructor, copy/move assignment, and
2884 // destructor.
2885 assert(SM == CXXDefaultConstructor &&
2886 "lookup for a constructor or assignment operator was empty");
2887 Result->setMethod(nullptr);
2888 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
2889 return Result;
2890 }
Chandler Carruth7deaae72013-08-18 07:20:52 +00002891
2892 // Copy the candidates as our processing of them may load new declarations
2893 // from an external source and invalidate lookup_result.
2894 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2895
Aaron Ballman1e606f42014-07-15 22:03:49 +00002896 for (auto *Cand : Candidates) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002897 if (Cand->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002898 continue;
2899
Alexis Hunt1da39282011-06-24 02:11:39 +00002900 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2901 // FIXME: [namespace.udecl]p15 says that we should only consider a
2902 // using declaration here if it does not match a declaration in the
2903 // derived class. We do not implement this correctly in other cases
2904 // either.
2905 Cand = U->getTargetDecl();
2906
2907 if (Cand->isInvalidDecl())
2908 continue;
2909 }
2910
2911 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002912 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Alexis Hunt1da39282011-06-24 02:11:39 +00002913 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002914 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2915 OCS, true);
Alexis Hunt080709f2011-06-23 00:26:20 +00002916 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002917 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2918 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt2949f022011-06-22 02:58:46 +00002919 } else if (FunctionTemplateDecl *Tmpl =
Alexis Hunt1da39282011-06-24 02:11:39 +00002920 dyn_cast<FunctionTemplateDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002921 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2922 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Craig Topperc3ec1492014-05-26 06:22:03 +00002923 RD, nullptr, ThisTy, Classification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002924 llvm::makeArrayRef(&Arg, NumArgs),
Alexis Hunt080709f2011-06-23 00:26:20 +00002925 OCS, true);
2926 else
2927 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Craig Topperc3ec1492014-05-26 06:22:03 +00002928 nullptr, llvm::makeArrayRef(&Arg, NumArgs),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002929 OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002930 } else {
2931 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002932 }
2933 }
2934
2935 OverloadCandidateSet::iterator Best;
2936 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2937 case OR_Success:
2938 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith83c478d2012-04-20 18:46:14 +00002939 Result->setKind(SpecialMemberOverloadResult::Success);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002940 break;
2941
2942 case OR_Deleted:
2943 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith852265f2012-03-30 20:53:28 +00002944 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002945 break;
2946
2947 case OR_Ambiguous:
Craig Topperc3ec1492014-05-26 06:22:03 +00002948 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00002949 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2950 break;
2951
Alexis Hunteef8ee02011-06-10 03:50:41 +00002952 case OR_No_Viable_Function:
Craig Topperc3ec1492014-05-26 06:22:03 +00002953 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00002954 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002955 break;
2956 }
2957
2958 return Result;
2959}
2960
2961/// \brief Look up the default constructor for the given class.
2962CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002963 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002964 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2965 false, false);
2966
2967 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002968}
2969
Alexis Hunt491ec602011-06-21 23:42:56 +00002970/// \brief Look up the copying constructor for the given class.
2971CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith83c478d2012-04-20 18:46:14 +00002972 unsigned Quals) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002973 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2974 "non-const, non-volatile qualifiers for copy ctor arg");
2975 SpecialMemberOverloadResult *Result =
2976 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2977 Quals & Qualifiers::Volatile, false, false, false);
2978
Alexis Hunt899bd442011-06-10 04:44:37 +00002979 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2980}
2981
Sebastian Redl22653ba2011-08-30 19:58:05 +00002982/// \brief Look up the moving constructor for the given class.
Richard Smith1c6461e2012-07-18 03:36:00 +00002983CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2984 unsigned Quals) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002985 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002986 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2987 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002988
2989 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2990}
2991
Douglas Gregor52b72822010-07-02 23:12:18 +00002992/// \brief Look up the constructors for the given class.
2993DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002994 // If the implicit constructors have not yet been declared, do so now.
Richard Smith7d125a12012-11-27 21:20:31 +00002995 if (CanDeclareSpecialMemberFunction(Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00002996 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002997 DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +00002998 if (Class->needsImplicitCopyConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002999 DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003000 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00003001 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00003002 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003003
Douglas Gregor52b72822010-07-02 23:12:18 +00003004 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
3005 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
3006 return Class->lookup(Name);
3007}
3008
Alexis Hunt491ec602011-06-21 23:42:56 +00003009/// \brief Look up the copying assignment operator for the given class.
3010CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
3011 unsigned Quals, bool RValueThis,
Richard Smith83c478d2012-04-20 18:46:14 +00003012 unsigned ThisQuals) {
Alexis Hunt491ec602011-06-21 23:42:56 +00003013 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3014 "non-const, non-volatile qualifiers for copy assignment arg");
3015 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3016 "non-const, non-volatile qualifiers for copy assignment this");
3017 SpecialMemberOverloadResult *Result =
3018 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
3019 Quals & Qualifiers::Volatile, RValueThis,
3020 ThisQuals & Qualifiers::Const,
3021 ThisQuals & Qualifiers::Volatile);
3022
Alexis Hunt491ec602011-06-21 23:42:56 +00003023 return Result->getMethod();
3024}
3025
Sebastian Redl22653ba2011-08-30 19:58:05 +00003026/// \brief Look up the moving assignment operator for the given class.
3027CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith1c6461e2012-07-18 03:36:00 +00003028 unsigned Quals,
Sebastian Redl22653ba2011-08-30 19:58:05 +00003029 bool RValueThis,
3030 unsigned ThisQuals) {
3031 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3032 "non-const, non-volatile qualifiers for copy assignment this");
3033 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00003034 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
3035 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl22653ba2011-08-30 19:58:05 +00003036 ThisQuals & Qualifiers::Const,
3037 ThisQuals & Qualifiers::Volatile);
3038
3039 return Result->getMethod();
3040}
3041
Douglas Gregore71edda2010-07-01 22:47:18 +00003042/// \brief Look for the destructor of the given class.
3043///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00003044/// During semantic analysis, this routine should be used in lieu of
3045/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00003046///
3047/// \returns The destructor for this class.
3048CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00003049 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
3050 false, false, false,
3051 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00003052}
3053
Richard Smithbcc22fc2012-03-09 08:00:36 +00003054/// LookupLiteralOperator - Determine which literal operator should be used for
3055/// a user-defined literal, per C++11 [lex.ext].
3056///
3057/// Normal overload resolution is not used to select which literal operator to
3058/// call for a user-defined literal. Look up the provided literal operator name,
3059/// and filter the results to the appropriate set for the given argument types.
3060Sema::LiteralOperatorLookupResult
3061Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
3062 ArrayRef<QualType> ArgTys,
Richard Smithb8b41d32013-10-07 19:57:58 +00003063 bool AllowRaw, bool AllowTemplate,
3064 bool AllowStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003065 LookupName(R, S);
3066 assert(R.getResultKind() != LookupResult::Ambiguous &&
3067 "literal operator lookup can't be ambiguous");
3068
3069 // Filter the lookup results appropriately.
3070 LookupResult::Filter F = R.makeFilter();
3071
Richard Smithbcc22fc2012-03-09 08:00:36 +00003072 bool FoundRaw = false;
Richard Smithb8b41d32013-10-07 19:57:58 +00003073 bool FoundTemplate = false;
3074 bool FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003075 bool FoundExactMatch = false;
3076
3077 while (F.hasNext()) {
3078 Decl *D = F.next();
3079 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
3080 D = USD->getTargetDecl();
3081
Douglas Gregorc1970572013-04-10 05:18:00 +00003082 // If the declaration we found is invalid, skip it.
3083 if (D->isInvalidDecl()) {
3084 F.erase();
3085 continue;
3086 }
3087
Richard Smithb8b41d32013-10-07 19:57:58 +00003088 bool IsRaw = false;
3089 bool IsTemplate = false;
3090 bool IsStringTemplate = false;
3091 bool IsExactMatch = false;
3092
Richard Smithbcc22fc2012-03-09 08:00:36 +00003093 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3094 if (FD->getNumParams() == 1 &&
3095 FD->getParamDecl(0)->getType()->getAs<PointerType>())
3096 IsRaw = true;
Richard Smith550de452013-01-15 07:12:59 +00003097 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003098 IsExactMatch = true;
3099 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
3100 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
3101 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
3102 IsExactMatch = false;
3103 break;
3104 }
3105 }
3106 }
3107 }
Richard Smithb8b41d32013-10-07 19:57:58 +00003108 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
3109 TemplateParameterList *Params = FD->getTemplateParameters();
3110 if (Params->size() == 1)
3111 IsTemplate = true;
3112 else
3113 IsStringTemplate = true;
3114 }
Richard Smithbcc22fc2012-03-09 08:00:36 +00003115
3116 if (IsExactMatch) {
3117 FoundExactMatch = true;
Richard Smithb8b41d32013-10-07 19:57:58 +00003118 AllowRaw = false;
3119 AllowTemplate = false;
3120 AllowStringTemplate = false;
3121 if (FoundRaw || FoundTemplate || FoundStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003122 // Go through again and remove the raw and template decls we've
3123 // already found.
3124 F.restart();
Richard Smithb8b41d32013-10-07 19:57:58 +00003125 FoundRaw = FoundTemplate = FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003126 }
Richard Smithb8b41d32013-10-07 19:57:58 +00003127 } else if (AllowRaw && IsRaw) {
3128 FoundRaw = true;
3129 } else if (AllowTemplate && IsTemplate) {
3130 FoundTemplate = true;
3131 } else if (AllowStringTemplate && IsStringTemplate) {
3132 FoundStringTemplate = true;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003133 } else {
3134 F.erase();
3135 }
3136 }
3137
3138 F.done();
3139
3140 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
3141 // parameter type, that is used in preference to a raw literal operator
3142 // or literal operator template.
3143 if (FoundExactMatch)
3144 return LOLR_Cooked;
3145
3146 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
3147 // operator template, but not both.
3148 if (FoundRaw && FoundTemplate) {
3149 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
Alp Tokera2794f92014-01-22 07:29:52 +00003150 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3151 NoteOverloadCandidate((*I)->getUnderlyingDecl()->getAsFunction());
Richard Smithbcc22fc2012-03-09 08:00:36 +00003152 return LOLR_Error;
3153 }
3154
3155 if (FoundRaw)
3156 return LOLR_Raw;
3157
3158 if (FoundTemplate)
3159 return LOLR_Template;
3160
Richard Smithb8b41d32013-10-07 19:57:58 +00003161 if (FoundStringTemplate)
3162 return LOLR_StringTemplate;
3163
Richard Smithbcc22fc2012-03-09 08:00:36 +00003164 // Didn't find anything we could use.
3165 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
3166 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
Richard Smithb8b41d32013-10-07 19:57:58 +00003167 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
3168 << (AllowTemplate || AllowStringTemplate);
Richard Smithbcc22fc2012-03-09 08:00:36 +00003169 return LOLR_Error;
3170}
3171
John McCall8fe68082010-01-26 07:16:45 +00003172void ADLResult::insert(NamedDecl *New) {
3173 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
3174
3175 // If we haven't yet seen a decl for this key, or the last decl
3176 // was exactly this one, we're done.
Craig Topperc3ec1492014-05-26 06:22:03 +00003177 if (Old == nullptr || Old == New) {
John McCall8fe68082010-01-26 07:16:45 +00003178 Old = New;
3179 return;
3180 }
3181
3182 // Otherwise, decide which is a more recent redeclaration.
Alp Tokera2794f92014-01-22 07:29:52 +00003183 FunctionDecl *OldFD = Old->getAsFunction();
3184 FunctionDecl *NewFD = New->getAsFunction();
John McCall8fe68082010-01-26 07:16:45 +00003185
3186 FunctionDecl *Cursor = NewFD;
3187 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00003188 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00003189
3190 // If we got to the end without finding OldFD, OldFD is the newer
3191 // declaration; leave things as they are.
3192 if (!Cursor) return;
3193
3194 // If we do find OldFD, then NewFD is newer.
3195 if (Cursor == OldFD) break;
3196
3197 // Otherwise, keep looking.
3198 }
3199
3200 Old = New;
3201}
3202
Richard Smith100b24a2014-04-17 01:52:14 +00003203void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3204 ArrayRef<Expr *> Args, ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003205 // Find all of the associated namespaces and classes based on the
3206 // arguments we have.
3207 AssociatedNamespaceSet AssociatedNamespaces;
3208 AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00003209 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCallc7e8e792009-08-07 22:18:02 +00003210 AssociatedNamespaces,
3211 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003212
3213 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003214 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3215 // and let Y be the lookup set produced by argument dependent
3216 // lookup (defined as follows). If X contains [...] then Y is
3217 // empty. Otherwise Y is the set of declarations found in the
3218 // namespaces associated with the argument types as described
3219 // below. The set of declarations found by the lookup of the name
3220 // is the union of X and Y.
3221 //
3222 // Here, we compute Y and add its members to the overloaded
3223 // candidate set.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003224 for (auto *NS : AssociatedNamespaces) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003225 // When considering an associated namespace, the lookup is the
3226 // same as the lookup performed when the associated namespace is
3227 // used as a qualifier (3.4.3.2) except that:
3228 //
3229 // -- Any using-directives in the associated namespace are
3230 // ignored.
3231 //
John McCallc7e8e792009-08-07 22:18:02 +00003232 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003233 // associated classes are visible within their respective
3234 // namespaces even if they are not visible during an ordinary
3235 // lookup (11.4).
Aaron Ballman1e606f42014-07-15 22:03:49 +00003236 DeclContext::lookup_result R = NS->lookup(Name);
3237 for (auto *D : R) {
John McCallaa74a0c2009-08-28 07:59:38 +00003238 // If the only declaration here is an ordinary friend, consider
3239 // it only if it was declared in an associated classes.
Richard Smith541b38b2013-09-20 01:15:31 +00003240 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) {
3241 // If it's neither ordinarily visible nor a friend, we can't find it.
3242 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0)
3243 continue;
3244
Richard Smith64017682013-07-17 23:53:16 +00003245 bool DeclaredInAssociatedClass = false;
3246 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
3247 DeclContext *LexDC = DI->getLexicalDeclContext();
3248 if (isa<CXXRecordDecl>(LexDC) &&
Richard Smith82b8d4e2015-12-18 22:19:11 +00003249 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)) &&
3250 isVisible(cast<NamedDecl>(DI))) {
Richard Smith64017682013-07-17 23:53:16 +00003251 DeclaredInAssociatedClass = true;
3252 break;
3253 }
3254 }
3255 if (!DeclaredInAssociatedClass)
John McCalld1e9d832009-08-11 06:59:38 +00003256 continue;
3257 }
Mike Stump11289f42009-09-09 15:08:12 +00003258
John McCall91f61fc2010-01-26 06:04:06 +00003259 if (isa<UsingShadowDecl>(D))
3260 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00003261
Richard Smith100b24a2014-04-17 01:52:14 +00003262 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D))
John McCall8fe68082010-01-26 07:16:45 +00003263 continue;
3264
Richard Smitha1431072015-06-12 01:32:13 +00003265 if (!isVisible(D) && !(D = findAcceptableDecl(*this, D)))
3266 continue;
3267
John McCall8fe68082010-01-26 07:16:45 +00003268 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00003269 }
3270 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003271}
Douglas Gregor2d435302009-12-30 17:04:44 +00003272
3273//----------------------------------------------------------------------------
3274// Search for all visible declarations.
3275//----------------------------------------------------------------------------
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00003276VisibleDeclConsumer::~VisibleDeclConsumer() { }
Douglas Gregor2d435302009-12-30 17:04:44 +00003277
Richard Smithe156254d2013-08-20 20:35:18 +00003278bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
3279
Douglas Gregor2d435302009-12-30 17:04:44 +00003280namespace {
3281
3282class ShadowContextRAII;
3283
3284class VisibleDeclsRecord {
3285public:
3286 /// \brief An entry in the shadow map, which is optimized to store a
3287 /// single declaration (the common case) but can also store a list
3288 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00003289 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00003290
3291private:
3292 /// \brief A mapping from declaration names to the declarations that have
3293 /// this name within a particular scope.
3294 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
3295
3296 /// \brief A list of shadow maps, which is used to model name hiding.
3297 std::list<ShadowMap> ShadowMaps;
3298
3299 /// \brief The declaration contexts we have already visited.
3300 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
3301
3302 friend class ShadowContextRAII;
3303
3304public:
3305 /// \brief Determine whether we have already visited this context
3306 /// (and, if not, note that we are going to visit that context now).
3307 bool visitedContext(DeclContext *Ctx) {
David Blaikie82e95a32014-11-19 07:49:47 +00003308 return !VisitedContexts.insert(Ctx).second;
Douglas Gregor2d435302009-12-30 17:04:44 +00003309 }
3310
Douglas Gregor39982192010-08-15 06:18:01 +00003311 bool alreadyVisitedContext(DeclContext *Ctx) {
3312 return VisitedContexts.count(Ctx);
3313 }
3314
Douglas Gregor2d435302009-12-30 17:04:44 +00003315 /// \brief Determine whether the given declaration is hidden in the
3316 /// current scope.
3317 ///
3318 /// \returns the declaration that hides the given declaration, or
3319 /// NULL if no such declaration exists.
3320 NamedDecl *checkHidden(NamedDecl *ND);
3321
3322 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00003323 void add(NamedDecl *ND) {
3324 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
3325 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003326};
3327
3328/// \brief RAII object that records when we've entered a shadow context.
3329class ShadowContextRAII {
3330 VisibleDeclsRecord &Visible;
3331
3332 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
3333
3334public:
3335 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
Benjamin Kramer3204b152015-05-29 19:42:19 +00003336 Visible.ShadowMaps.emplace_back();
Douglas Gregor2d435302009-12-30 17:04:44 +00003337 }
3338
3339 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00003340 Visible.ShadowMaps.pop_back();
3341 }
3342};
3343
3344} // end anonymous namespace
3345
Douglas Gregor2d435302009-12-30 17:04:44 +00003346NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
3347 unsigned IDNS = ND->getIdentifierNamespace();
3348 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
3349 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3350 SM != SMEnd; ++SM) {
3351 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
3352 if (Pos == SM->end())
3353 continue;
3354
Aaron Ballman1e606f42014-07-15 22:03:49 +00003355 for (auto *D : Pos->second) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003356 // A tag declaration does not hide a non-tag declaration.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003357 if (D->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003358 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00003359 Decl::IDNS_ObjCProtocol)))
3360 continue;
3361
3362 // Protocols are in distinct namespaces from everything else.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003363 if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor2d435302009-12-30 17:04:44 +00003364 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Aaron Ballman1e606f42014-07-15 22:03:49 +00003365 D->getIdentifierNamespace() != IDNS)
Douglas Gregor2d435302009-12-30 17:04:44 +00003366 continue;
3367
Douglas Gregor09bbc652010-01-14 15:47:35 +00003368 // Functions and function templates in the same scope overload
3369 // rather than hide. FIXME: Look for hiding based on function
3370 // signatures!
Aaron Ballman1e606f42014-07-15 22:03:49 +00003371 if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Alp Tokera2794f92014-01-22 07:29:52 +00003372 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00003373 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00003374 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003375
Douglas Gregor2d435302009-12-30 17:04:44 +00003376 // We've found a declaration that hides this one.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003377 return D;
Douglas Gregor2d435302009-12-30 17:04:44 +00003378 }
3379 }
3380
Craig Topperc3ec1492014-05-26 06:22:03 +00003381 return nullptr;
Douglas Gregor2d435302009-12-30 17:04:44 +00003382}
3383
3384static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
3385 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003386 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00003387 VisibleDeclConsumer &Consumer,
3388 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00003389 if (!Ctx)
3390 return;
3391
Douglas Gregor2d435302009-12-30 17:04:44 +00003392 // Make sure we don't visit the same context twice.
3393 if (Visited.visitedContext(Ctx->getPrimaryContext()))
3394 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003395
Richard Smith9e2341d2015-03-23 03:25:59 +00003396 // Outside C++, lookup results for the TU live on identifiers.
3397 if (isa<TranslationUnitDecl>(Ctx) &&
3398 !Result.getSema().getLangOpts().CPlusPlus) {
3399 auto &S = Result.getSema();
3400 auto &Idents = S.Context.Idents;
3401
3402 // Ensure all external identifiers are in the identifier table.
3403 if (IdentifierInfoLookup *External = Idents.getExternalIdentifierLookup()) {
3404 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
3405 for (StringRef Name = Iter->Next(); !Name.empty(); Name = Iter->Next())
3406 Idents.get(Name);
3407 }
3408
3409 // Walk all lookup results in the TU for each identifier.
3410 for (const auto &Ident : Idents) {
3411 for (auto I = S.IdResolver.begin(Ident.getValue()),
3412 E = S.IdResolver.end();
3413 I != E; ++I) {
3414 if (S.IdResolver.isDeclInScope(*I, Ctx)) {
3415 if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
3416 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3417 Visited.add(ND);
3418 }
3419 }
3420 }
3421 }
3422
3423 return;
3424 }
3425
Douglas Gregor7454c562010-07-02 20:37:36 +00003426 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3427 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3428
Douglas Gregor2d435302009-12-30 17:04:44 +00003429 // Enumerate all of the results in this context.
Richard Trieu20abd6b2015-04-15 03:48:48 +00003430 for (DeclContextLookupResult R : Ctx->lookups()) {
Richard Smith9e2341d2015-03-23 03:25:59 +00003431 for (auto *D : R) {
3432 if (auto *ND = Result.getAcceptableDecl(D)) {
3433 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3434 Visited.add(ND);
Douglas Gregora3b23b02010-12-09 21:44:02 +00003435 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003436 }
3437 }
3438
3439 // Traverse using directives for qualified name lookup.
3440 if (QualifiedNameLookup) {
3441 ShadowContextRAII Shadow(Visited);
Aaron Ballman804a7fb2014-03-17 17:14:12 +00003442 for (auto I : Ctx->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00003443 LookupVisibleDecls(I->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003444 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003445 }
3446 }
3447
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003448 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00003449 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00003450 if (!Record->hasDefinition())
3451 return;
3452
Aaron Ballman574705e2014-03-13 15:41:46 +00003453 for (const auto &B : Record->bases()) {
3454 QualType BaseType = B.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003455
Douglas Gregor2d435302009-12-30 17:04:44 +00003456 // Don't look into dependent bases, because name lookup can't look
3457 // there anyway.
3458 if (BaseType->isDependentType())
3459 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003460
Douglas Gregor2d435302009-12-30 17:04:44 +00003461 const RecordType *Record = BaseType->getAs<RecordType>();
3462 if (!Record)
3463 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003464
Douglas Gregor2d435302009-12-30 17:04:44 +00003465 // FIXME: It would be nice to be able to determine whether referencing
3466 // a particular member would be ambiguous. For example, given
3467 //
3468 // struct A { int member; };
3469 // struct B { int member; };
3470 // struct C : A, B { };
3471 //
3472 // void f(C *c) { c->### }
3473 //
3474 // accessing 'member' would result in an ambiguity. However, we
3475 // could be smart enough to qualify the member with the base
3476 // class, e.g.,
3477 //
3478 // c->B::member
3479 //
3480 // or
3481 //
3482 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003483
Douglas Gregor2d435302009-12-30 17:04:44 +00003484 // Find results in this base class (and its bases).
3485 ShadowContextRAII Shadow(Visited);
3486 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003487 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003488 }
3489 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003490
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003491 // Traverse the contexts of Objective-C classes.
3492 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3493 // Traverse categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003494 for (auto *Cat : IFace->visible_categories()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003495 ShadowContextRAII Shadow(Visited);
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003496 LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003497 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003498 }
3499
3500 // Traverse protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003501 for (auto *I : IFace->all_referenced_protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003502 ShadowContextRAII Shadow(Visited);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003503 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003504 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003505 }
3506
3507 // Traverse the superclass.
3508 if (IFace->getSuperClass()) {
3509 ShadowContextRAII Shadow(Visited);
3510 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003511 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003512 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003513
Douglas Gregor0b59e802010-04-19 18:02:19 +00003514 // If there is an implementation, traverse it. We do this to find
3515 // synthesized ivars.
3516 if (IFace->getImplementation()) {
3517 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003518 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky13668f22012-04-03 20:26:45 +00003519 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor0b59e802010-04-19 18:02:19 +00003520 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003521 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003522 for (auto *I : Protocol->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003523 ShadowContextRAII Shadow(Visited);
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003524 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003525 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003526 }
3527 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003528 for (auto *I : Category->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003529 ShadowContextRAII Shadow(Visited);
Aaron Ballman19a41762014-03-14 12:55:57 +00003530 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003531 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003532 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003533
Douglas Gregor0b59e802010-04-19 18:02:19 +00003534 // If there is an implementation, traverse it.
3535 if (Category->getImplementation()) {
3536 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003537 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00003538 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003539 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003540 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003541}
3542
3543static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3544 UnqualUsingDirectiveSet &UDirs,
3545 VisibleDeclConsumer &Consumer,
3546 VisibleDeclsRecord &Visited) {
3547 if (!S)
3548 return;
3549
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003550 if (!S->getEntity() ||
3551 (!S->getParent() &&
Ted Kremenekc37877d2013-10-08 17:08:03 +00003552 !Visited.alreadyVisitedContext(S->getEntity())) ||
3553 (S->getEntity())->isFunctionOrMethod()) {
Richard Smith541b38b2013-09-20 01:15:31 +00003554 FindLocalExternScope FindLocals(Result);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003555 // Walk through the declarations in this Scope.
Aaron Ballman35c54952014-03-17 16:55:25 +00003556 for (auto *D : S->decls()) {
3557 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Douglas Gregor4a814562011-12-14 16:03:29 +00003558 if ((ND = Result.getAcceptableDecl(ND))) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003559 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003560 Visited.add(ND);
3561 }
3562 }
3563 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003564
Douglas Gregor66230062010-03-15 14:33:29 +00003565 // FIXME: C++ [temp.local]p8
Craig Topperc3ec1492014-05-26 06:22:03 +00003566 DeclContext *Entity = nullptr;
Douglas Gregor4f248632010-01-01 17:44:25 +00003567 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003568 // Look into this scope's declaration context, along with any of its
3569 // parent lookup contexts (e.g., enclosing classes), up to the point
3570 // where we hit the context stored in the next outer scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00003571 Entity = S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00003572 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003573
Douglas Gregorea166062010-03-15 15:26:48 +00003574 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00003575 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003576 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3577 if (Method->isInstanceMethod()) {
3578 // For instance methods, look for ivars in the method's interface.
3579 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3580 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003581 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003582 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Richard Smithe156254d2013-08-20 20:35:18 +00003583 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003584 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003585 }
3586
3587 // We've already performed all of the name lookup that we need
3588 // to for Objective-C methods; the next context will be the
3589 // outer scope.
3590 break;
3591 }
3592
Douglas Gregor2d435302009-12-30 17:04:44 +00003593 if (Ctx->isFunctionOrMethod())
3594 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003595
3596 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003597 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003598 }
3599 } else if (!S->getParent()) {
3600 // Look into the translation unit scope. We walk through the translation
3601 // unit's declaration context, because the Scope itself won't have all of
3602 // the declarations if we loaded a precompiled header.
3603 // FIXME: We would like the translation unit's Scope object to point to the
3604 // translation unit, so we don't need this special "if" branch. However,
3605 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003606 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00003607 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003608 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00003609 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003610 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003611 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003612 }
3613
Douglas Gregor2d435302009-12-30 17:04:44 +00003614 if (Entity) {
3615 // Lookup visible declarations in any namespaces found by using
3616 // directives.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003617 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
3618 LookupVisibleDecls(const_cast<DeclContext *>(UUE.getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003619 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003620 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003621 }
3622
3623 // Lookup names in the parent scope.
3624 ShadowContextRAII Shadow(Visited);
3625 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3626}
3627
3628void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003629 VisibleDeclConsumer &Consumer,
3630 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003631 // Determine the set of using directives available during
3632 // unqualified name lookup.
3633 Scope *Initial = S;
3634 UnqualUsingDirectiveSet UDirs;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003635 if (getLangOpts().CPlusPlus) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003636 // Find the first namespace or translation-unit scope.
3637 while (S && !isNamespaceOrTranslationUnitScope(S))
3638 S = S->getParent();
3639
3640 UDirs.visitScopeChain(Initial, S);
3641 }
3642 UDirs.done();
3643
3644 // Look for visible declarations.
3645 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003646 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003647 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003648 if (!IncludeGlobalScope)
3649 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003650 ShadowContextRAII Shadow(Visited);
3651 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3652}
3653
3654void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003655 VisibleDeclConsumer &Consumer,
3656 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003657 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003658 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003659 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003660 if (!IncludeGlobalScope)
3661 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003662 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003663 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003664 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003665}
3666
Chris Lattner43e7f312011-02-18 02:08:43 +00003667/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003668/// If GnuLabelLoc is a valid source location, then this is a definition
3669/// of an __label__ label name, otherwise it is a normal label definition
3670/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003671LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003672 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003673 // Do a lookup to see if we have a label with this name already.
Craig Topperc3ec1492014-05-26 06:22:03 +00003674 NamedDecl *Res = nullptr;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003675
3676 if (GnuLabelLoc.isValid()) {
3677 // Local label definitions always shadow existing labels.
3678 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3679 Scope *S = CurScope;
3680 PushOnScopeChains(Res, S, true);
3681 return cast<LabelDecl>(Res);
3682 }
3683
3684 // Not a GNU local label.
3685 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3686 // If we found a label, check to see if it is in the same context as us.
3687 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003688 if (Res && Res->getDeclContext() != CurContext)
Craig Topperc3ec1492014-05-26 06:22:03 +00003689 Res = nullptr;
3690 if (!Res) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003691 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003692 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3693 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003694 assert(S && "Not in a function?");
3695 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003696 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003697 return cast<LabelDecl>(Res);
3698}
3699
3700//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003701// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003702//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003703
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003704static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3705 TypoCorrection &Candidate) {
3706 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3707 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3708}
3709
3710static void LookupPotentialTypoResult(Sema &SemaRef,
3711 LookupResult &Res,
3712 IdentifierInfo *Name,
3713 Scope *S, CXXScopeSpec *SS,
3714 DeclContext *MemberContext,
3715 bool EnteringContext,
3716 bool isObjCIvarLookup,
3717 bool FindHidden);
3718
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003719/// \brief Check whether the declarations found for a typo correction are
3720/// visible, and if none of them are, convert the correction to an 'import
3721/// a module' correction.
3722static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
3723 if (TC.begin() == TC.end())
3724 return;
3725
3726 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3727
3728 for (/**/; DI != DE; ++DI)
3729 if (!LookupResult::isVisible(SemaRef, *DI))
3730 break;
3731 // Nothing to do if all decls are visible.
3732 if (DI == DE)
3733 return;
3734
3735 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3736 bool AnyVisibleDecls = !NewDecls.empty();
3737
3738 for (/**/; DI != DE; ++DI) {
3739 NamedDecl *VisibleDecl = *DI;
3740 if (!LookupResult::isVisible(SemaRef, *DI))
3741 VisibleDecl = findAcceptableDecl(SemaRef, *DI);
3742
3743 if (VisibleDecl) {
3744 if (!AnyVisibleDecls) {
3745 // Found a visible decl, discard all hidden ones.
3746 AnyVisibleDecls = true;
3747 NewDecls.clear();
3748 }
3749 NewDecls.push_back(VisibleDecl);
3750 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
3751 NewDecls.push_back(*DI);
3752 }
3753
3754 if (NewDecls.empty())
3755 TC = TypoCorrection();
3756 else {
3757 TC.setCorrectionDecls(NewDecls);
3758 TC.setRequiresImport(!AnyVisibleDecls);
3759 }
3760}
3761
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003762// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3763// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3764// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3765static void getNestedNameSpecifierIdentifiers(
3766 NestedNameSpecifier *NNS,
3767 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3768 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3769 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3770 else
3771 Identifiers.clear();
3772
3773 const IdentifierInfo *II = nullptr;
3774
3775 switch (NNS->getKind()) {
3776 case NestedNameSpecifier::Identifier:
3777 II = NNS->getAsIdentifier();
3778 break;
3779
3780 case NestedNameSpecifier::Namespace:
3781 if (NNS->getAsNamespace()->isAnonymousNamespace())
3782 return;
3783 II = NNS->getAsNamespace()->getIdentifier();
3784 break;
3785
3786 case NestedNameSpecifier::NamespaceAlias:
3787 II = NNS->getAsNamespaceAlias()->getIdentifier();
3788 break;
3789
3790 case NestedNameSpecifier::TypeSpecWithTemplate:
3791 case NestedNameSpecifier::TypeSpec:
3792 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3793 break;
3794
3795 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00003796 case NestedNameSpecifier::Super:
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003797 return;
3798 }
3799
3800 if (II)
3801 Identifiers.push_back(II);
3802}
3803
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003804void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003805 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003806 // Don't consider hidden names for typo correction.
3807 if (Hiding)
3808 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003809
Douglas Gregor2d435302009-12-30 17:04:44 +00003810 // Only consider entities with identifiers for names, ignoring
3811 // special names (constructors, overloaded operators, selectors,
3812 // etc.).
3813 IdentifierInfo *Name = ND->getIdentifier();
3814 if (!Name)
3815 return;
3816
Richard Smithe156254d2013-08-20 20:35:18 +00003817 // Only consider visible declarations and declarations from modules with
3818 // names that exactly match.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003819 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo &&
Richard Smithe156254d2013-08-20 20:35:18 +00003820 !findAcceptableDecl(SemaRef, ND))
3821 return;
3822
Douglas Gregor57756ea2010-10-14 22:11:03 +00003823 FoundName(Name->getName());
3824}
3825
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003826void TypoCorrectionConsumer::FoundName(StringRef Name) {
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003827 // Compute the edit distance between the typo and the name of this
3828 // entity, and add the identifier to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003829 addName(Name, nullptr);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003830}
3831
3832void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3833 // Compute the edit distance between the typo and this keyword,
3834 // and add the keyword to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003835 addName(Keyword, nullptr, nullptr, true);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003836}
3837
3838void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
3839 NestedNameSpecifier *NNS, bool isKeyword) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003840 // Use a simple length-based heuristic to determine the minimum possible
3841 // edit distance. If the minimum isn't good enough, bail out early.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003842 StringRef TypoStr = Typo->getName();
3843 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
3844 if (MinED && TypoStr.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00003845 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003846
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003847 // Compute an upper bound on the allowable edit distance, so that the
3848 // edit-distance algorithm can short-circuit.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003849 unsigned UpperBound = (TypoStr.size() + 2) / 3 + 1;
3850 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003851 if (ED >= UpperBound) return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003852
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003853 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003854 if (isKeyword) TC.makeKeyword();
Kaelyn Takata0a313022014-11-20 22:06:26 +00003855 TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003856 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003857}
3858
Kaelyn Takatad2287c32014-10-27 18:07:13 +00003859static const unsigned MaxTypoDistanceResultSets = 5;
3860
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003861void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003862 StringRef TypoStr = Typo->getName();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003863 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003864
3865 // For very short typos, ignore potential corrections that have a different
3866 // base identifier from the typo or which have a normalized edit distance
3867 // longer than the typo itself.
3868 if (TypoStr.size() < 3 &&
3869 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
3870 return;
3871
3872 // If the correction is resolved but is not viable, ignore it.
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003873 if (Correction.isResolved()) {
3874 checkCorrectionVisibility(SemaRef, Correction);
3875 if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
3876 return;
3877 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003878
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003879 TypoResultList &CList =
3880 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003881
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003882 if (!CList.empty() && !CList.back().isResolved())
3883 CList.pop_back();
3884 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3885 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3886 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3887 RI != RIEnd; ++RI) {
3888 // If the Correction refers to a decl already in the result list,
3889 // replace the existing result if the string representation of Correction
3890 // comes before the current result alphabetically, then stop as there is
3891 // nothing more to be done to add Correction to the candidate set.
3892 if (RI->getCorrectionDecl() == NewND) {
3893 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3894 *RI = Correction;
3895 return;
3896 }
3897 }
3898 }
3899 if (CList.empty() || Correction.isResolved())
3900 CList.push_back(Correction);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003901
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003902 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003903 CorrectionResults.erase(std::prev(CorrectionResults.end()));
3904}
3905
3906void TypoCorrectionConsumer::addNamespaces(
3907 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
3908 SearchNamespaces = true;
3909
3910 for (auto KNPair : KnownNamespaces)
3911 Namespaces.addNameSpecifier(KNPair.first);
3912
3913 bool SSIsTemplate = false;
3914 if (NestedNameSpecifier *NNS =
3915 (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
3916 if (const Type *T = NNS->getAsType())
3917 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
3918 }
Richard Smith2a40fb72015-11-18 01:19:02 +00003919 // Do not transform this into an iterator-based loop. The loop body can
3920 // trigger the creation of further types (through lazy deserialization) and
3921 // invalide iterators into this list.
3922 auto &Types = SemaRef.getASTContext().getTypes();
3923 for (unsigned I = 0; I != Types.size(); ++I) {
3924 const auto *TI = Types[I];
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003925 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
3926 CD = CD->getCanonicalDecl();
3927 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
3928 !CD->isUnion() && CD->getIdentifier() &&
3929 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
3930 (CD->isBeingDefined() || CD->isCompleteDefinition()))
3931 Namespaces.addNameSpecifier(CD);
3932 }
3933 }
3934}
3935
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003936const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
3937 if (++CurrentTCIndex < ValidatedCorrections.size())
3938 return ValidatedCorrections[CurrentTCIndex];
3939
3940 CurrentTCIndex = ValidatedCorrections.size();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003941 while (!CorrectionResults.empty()) {
3942 auto DI = CorrectionResults.begin();
3943 if (DI->second.empty()) {
3944 CorrectionResults.erase(DI);
3945 continue;
3946 }
3947
3948 auto RI = DI->second.begin();
3949 if (RI->second.empty()) {
3950 DI->second.erase(RI);
3951 performQualifiedLookups();
3952 continue;
3953 }
3954
3955 TypoCorrection TC = RI->second.pop_back_val();
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003956 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003957 ValidatedCorrections.push_back(TC);
3958 return ValidatedCorrections[CurrentTCIndex];
3959 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003960 }
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003961 return ValidatedCorrections[0]; // The empty correction.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003962}
3963
3964bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
3965 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
3966 DeclContext *TempMemberContext = MemberContext;
Kaelyn Takata6c759512014-10-27 18:07:37 +00003967 CXXScopeSpec *TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003968retry_lookup:
3969 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
3970 EnteringContext,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00003971 CorrectionValidator->IsObjCIvarLookup,
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003972 Name == Typo && !Candidate.WillReplaceSpecifier());
3973 switch (Result.getResultKind()) {
3974 case LookupResult::NotFound:
3975 case LookupResult::NotFoundInCurrentInstantiation:
3976 case LookupResult::FoundUnresolvedValue:
3977 if (TempSS) {
3978 // Immediately retry the lookup without the given CXXScopeSpec
3979 TempSS = nullptr;
3980 Candidate.WillReplaceSpecifier(true);
3981 goto retry_lookup;
3982 }
3983 if (TempMemberContext) {
3984 if (SS && !TempSS)
Kaelyn Takata6c759512014-10-27 18:07:37 +00003985 TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003986 TempMemberContext = nullptr;
3987 goto retry_lookup;
3988 }
3989 if (SearchNamespaces)
3990 QualifiedResults.push_back(Candidate);
3991 break;
3992
3993 case LookupResult::Ambiguous:
3994 // We don't deal with ambiguities.
3995 break;
3996
3997 case LookupResult::Found:
3998 case LookupResult::FoundOverloaded:
3999 // Store all of the Decls for overloaded symbols
4000 for (auto *TRD : Result)
4001 Candidate.addCorrectionDecl(TRD);
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00004002 checkCorrectionVisibility(SemaRef, Candidate);
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004003 if (!isCandidateViable(*CorrectionValidator, Candidate)) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004004 if (SearchNamespaces)
4005 QualifiedResults.push_back(Candidate);
4006 break;
4007 }
Kaelyn Takata20deb1d2015-01-28 00:46:09 +00004008 Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004009 return true;
4010 }
4011 return false;
4012}
4013
4014void TypoCorrectionConsumer::performQualifiedLookups() {
4015 unsigned TypoLen = Typo->getName().size();
4016 for (auto QR : QualifiedResults) {
4017 for (auto NSI : Namespaces) {
4018 DeclContext *Ctx = NSI.DeclCtx;
4019 const Type *NSType = NSI.NameSpecifier->getAsType();
4020
4021 // If the current NestedNameSpecifier refers to a class and the
4022 // current correction candidate is the name of that class, then skip
4023 // it as it is unlikely a qualified version of the class' constructor
4024 // is an appropriate correction.
Hans Wennborgdcfba332015-10-06 23:40:43 +00004025 if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() :
4026 nullptr) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004027 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
4028 continue;
4029 }
4030
4031 TypoCorrection TC(QR);
4032 TC.ClearCorrectionDecls();
4033 TC.setCorrectionSpecifier(NSI.NameSpecifier);
4034 TC.setQualifierDistance(NSI.EditDistance);
4035 TC.setCallbackDistance(0); // Reset the callback distance
4036
4037 // If the current correction candidate and namespace combination are
4038 // too far away from the original typo based on the normalized edit
4039 // distance, then skip performing a qualified name lookup.
4040 unsigned TmpED = TC.getEditDistance(true);
4041 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
4042 TypoLen / TmpED < 3)
4043 continue;
4044
4045 Result.clear();
4046 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
4047 if (!SemaRef.LookupQualifiedName(Result, Ctx))
4048 continue;
4049
4050 // Any corrections added below will be validated in subsequent
4051 // iterations of the main while() loop over the Consumer's contents.
4052 switch (Result.getResultKind()) {
4053 case LookupResult::Found:
4054 case LookupResult::FoundOverloaded: {
4055 if (SS && SS->isValid()) {
4056 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
4057 std::string OldQualified;
4058 llvm::raw_string_ostream OldOStream(OldQualified);
4059 SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
4060 OldOStream << Typo->getName();
4061 // If correction candidate would be an identical written qualified
4062 // identifer, then the existing CXXScopeSpec probably included a
4063 // typedef that didn't get accounted for properly.
4064 if (OldOStream.str() == NewQualified)
4065 break;
4066 }
4067 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
4068 TRD != TRDEnd; ++TRD) {
4069 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4070 NSType ? NSType->getAsCXXRecordDecl()
4071 : nullptr,
4072 TRD.getPair()) == Sema::AR_accessible)
4073 TC.addCorrectionDecl(*TRD);
4074 }
Kaelyn Takata0a313022014-11-20 22:06:26 +00004075 if (TC.isResolved()) {
4076 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004077 addCorrection(TC);
Kaelyn Takata0a313022014-11-20 22:06:26 +00004078 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004079 break;
4080 }
4081 case LookupResult::NotFound:
4082 case LookupResult::NotFoundInCurrentInstantiation:
4083 case LookupResult::Ambiguous:
4084 case LookupResult::FoundUnresolvedValue:
4085 break;
4086 }
4087 }
4088 }
4089 QualifiedResults.clear();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004090}
4091
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004092TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
4093 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
Benjamin Kramer15537272015-03-13 16:10:42 +00004094 : Context(Context), CurContextChain(buildContextChain(CurContext)) {
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004095 if (NestedNameSpecifier *NNS =
4096 CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
4097 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
4098 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4099
4100 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
4101 }
4102 // Build the list of identifiers that would be used for an absolute
4103 // (from the global context) NestedNameSpecifier referring to the current
4104 // context.
4105 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
4106 CEnd = CurContextChain.rend();
4107 C != CEnd; ++C) {
4108 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
4109 CurContextIdentifiers.push_back(ND->getIdentifier());
4110 }
4111
4112 // Add the global context as a NestedNameSpecifier
Hans Wennborg66010132014-06-11 21:24:13 +00004113 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
4114 NestedNameSpecifier::GlobalSpecifier(Context), 1};
4115 DistanceMap[1].push_back(SI);
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004116}
4117
Kaelyn Takata7dcc0e62014-06-11 18:07:08 +00004118auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
4119 DeclContext *Start) -> DeclContextList {
Nick Lewycky0d9b3192013-04-08 21:55:21 +00004120 assert(Start && "Building a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004121 DeclContextList Chain;
Craig Topperc3ec1492014-05-26 06:22:03 +00004122 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004123 DC = DC->getLookupParent()) {
4124 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
4125 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
4126 !(ND && ND->isAnonymousNamespace()))
4127 Chain.push_back(DC->getPrimaryContext());
4128 }
4129 return Chain;
4130}
4131
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004132unsigned
4133TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
4134 DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004135 unsigned NumSpecifiers = 0;
4136 for (DeclContextList::reverse_iterator C = DeclChain.rbegin(),
4137 CEnd = DeclChain.rend();
4138 C != CEnd; ++C) {
4139 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) {
4140 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
4141 ++NumSpecifiers;
4142 } else if (RecordDecl *RD = dyn_cast_or_null<RecordDecl>(*C)) {
4143 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
4144 RD->getTypeForDecl());
4145 ++NumSpecifiers;
4146 }
4147 }
4148 return NumSpecifiers;
4149}
4150
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004151void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
4152 DeclContext *Ctx) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004153 NestedNameSpecifier *NNS = nullptr;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004154 unsigned NumSpecifiers = 0;
Kaelyn Takata0fc75192014-06-11 18:06:56 +00004155 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004156 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
4157
4158 // Eliminate common elements from the two DeclContext chains.
4159 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
4160 CEnd = CurContextChain.rend();
4161 C != CEnd && !NamespaceDeclChain.empty() &&
4162 NamespaceDeclChain.back() == *C; ++C) {
4163 NamespaceDeclChain.pop_back();
4164 }
4165
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004166 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004167 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004168
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004169 // Add an explicit leading '::' specifier if needed.
4170 if (NamespaceDeclChain.empty()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004171 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004172 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004173 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004174 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004175 } else if (NamedDecl *ND =
4176 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004177 IdentifierInfo *Name = ND->getIdentifier();
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004178 bool SameNameSpecifier = false;
4179 if (std::find(CurNameSpecifierIdentifiers.begin(),
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004180 CurNameSpecifierIdentifiers.end(),
4181 Name) != CurNameSpecifierIdentifiers.end()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004182 std::string NewNameSpecifier;
4183 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
4184 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
4185 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4186 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4187 SpecifierOStream.flush();
4188 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004189 }
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004190 if (SameNameSpecifier ||
4191 std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
4192 Name) != CurContextIdentifiers.end()) {
4193 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4194 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4195 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004196 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004197 }
4198 }
4199
4200 // If the built NestedNameSpecifier would be replacing an existing
4201 // NestedNameSpecifier, use the number of component identifiers that
4202 // would need to be changed as the edit distance instead of the number
4203 // of components in the built NestedNameSpecifier.
4204 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
4205 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
4206 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4207 NumSpecifiers = llvm::ComputeEditDistance(
Craig Topper8c2a2a02014-08-30 16:55:39 +00004208 llvm::makeArrayRef(CurNameSpecifierIdentifiers),
4209 llvm::makeArrayRef(NewNameSpecifierIdentifiers));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004210 }
4211
Hans Wennborg66010132014-06-11 21:24:13 +00004212 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
4213 DistanceMap[NumSpecifiers].push_back(SI);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004214}
4215
Douglas Gregord507d772010-10-20 03:06:34 +00004216/// \brief Perform name lookup for a possible result for typo correction.
4217static void LookupPotentialTypoResult(Sema &SemaRef,
4218 LookupResult &Res,
4219 IdentifierInfo *Name,
4220 Scope *S, CXXScopeSpec *SS,
4221 DeclContext *MemberContext,
4222 bool EnteringContext,
Richard Smithe156254d2013-08-20 20:35:18 +00004223 bool isObjCIvarLookup,
4224 bool FindHidden) {
Douglas Gregord507d772010-10-20 03:06:34 +00004225 Res.suppressDiagnostics();
4226 Res.clear();
4227 Res.setLookupName(Name);
Richard Smithe156254d2013-08-20 20:35:18 +00004228 Res.setAllowHidden(FindHidden);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004229 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00004230 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004231 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00004232 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
4233 Res.addDecl(Ivar);
4234 Res.resolveKind();
4235 return;
4236 }
4237 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004238
Manman Ren5b786402016-01-28 18:49:28 +00004239 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(
4240 Name, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Douglas Gregord507d772010-10-20 03:06:34 +00004241 Res.addDecl(Prop);
4242 Res.resolveKind();
4243 return;
4244 }
4245 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004246
Douglas Gregord507d772010-10-20 03:06:34 +00004247 SemaRef.LookupQualifiedName(Res, MemberContext);
4248 return;
4249 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004250
4251 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00004252 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004253
Douglas Gregord507d772010-10-20 03:06:34 +00004254 // Fake ivar lookup; this should really be part of
4255 // LookupParsedName.
4256 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
4257 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004258 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00004259 (Res.isSingleResult() &&
4260 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004261 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00004262 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
4263 Res.addDecl(IV);
4264 Res.resolveKind();
4265 }
4266 }
4267 }
4268}
4269
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004270/// \brief Add keywords to the consumer as possible typo corrections.
4271static void AddKeywordsToConsumer(Sema &SemaRef,
4272 TypoCorrectionConsumer &Consumer,
Richard Smithb3a1df02012-06-08 21:35:42 +00004273 Scope *S, CorrectionCandidateCallback &CCC,
4274 bool AfterNestedNameSpecifier) {
4275 if (AfterNestedNameSpecifier) {
4276 // For 'X::', we know exactly which keywords can appear next.
4277 Consumer.addKeywordResult("template");
4278 if (CCC.WantExpressionKeywords)
4279 Consumer.addKeywordResult("operator");
4280 return;
4281 }
4282
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004283 if (CCC.WantObjCSuper)
4284 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004285
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004286 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004287 // Add type-specifier keywords to the set of results.
Craig Topperd6d31ac2013-07-15 08:24:27 +00004288 static const char *const CTypeSpecs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004289 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00004290 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004291 "_Complex", "_Imaginary",
4292 // storage-specifiers as well
4293 "extern", "inline", "static", "typedef"
4294 };
4295
Craig Toppere5ce8312013-07-15 03:38:40 +00004296 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004297 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
4298 Consumer.addKeywordResult(CTypeSpecs[I]);
4299
David Blaikiebbafb8a2012-03-11 07:00:24 +00004300 if (SemaRef.getLangOpts().C99)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004301 Consumer.addKeywordResult("restrict");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004302 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004303 Consumer.addKeywordResult("bool");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004304 else if (SemaRef.getLangOpts().C99)
Douglas Gregor3b22a882011-07-01 21:27:45 +00004305 Consumer.addKeywordResult("_Bool");
4306
David Blaikiebbafb8a2012-03-11 07:00:24 +00004307 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004308 Consumer.addKeywordResult("class");
4309 Consumer.addKeywordResult("typename");
4310 Consumer.addKeywordResult("wchar_t");
4311
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004312 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004313 Consumer.addKeywordResult("char16_t");
4314 Consumer.addKeywordResult("char32_t");
4315 Consumer.addKeywordResult("constexpr");
4316 Consumer.addKeywordResult("decltype");
4317 Consumer.addKeywordResult("thread_local");
4318 }
4319 }
4320
David Blaikiebbafb8a2012-03-11 07:00:24 +00004321 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004322 Consumer.addKeywordResult("typeof");
Kaelyn Takatab04846b2014-07-28 18:14:02 +00004323 } else if (CCC.WantFunctionLikeCasts) {
4324 static const char *const CastableTypeSpecs[] = {
4325 "char", "double", "float", "int", "long", "short",
4326 "signed", "unsigned", "void"
4327 };
4328 for (auto *kw : CastableTypeSpecs)
4329 Consumer.addKeywordResult(kw);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004330 }
4331
David Blaikiebbafb8a2012-03-11 07:00:24 +00004332 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004333 Consumer.addKeywordResult("const_cast");
4334 Consumer.addKeywordResult("dynamic_cast");
4335 Consumer.addKeywordResult("reinterpret_cast");
4336 Consumer.addKeywordResult("static_cast");
4337 }
4338
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004339 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004340 Consumer.addKeywordResult("sizeof");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004341 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004342 Consumer.addKeywordResult("false");
4343 Consumer.addKeywordResult("true");
4344 }
4345
David Blaikiebbafb8a2012-03-11 07:00:24 +00004346 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topperd6d31ac2013-07-15 08:24:27 +00004347 static const char *const CXXExprs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004348 "delete", "new", "operator", "throw", "typeid"
4349 };
Craig Toppere5ce8312013-07-15 03:38:40 +00004350 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004351 for (unsigned I = 0; I != NumCXXExprs; ++I)
4352 Consumer.addKeywordResult(CXXExprs[I]);
4353
4354 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
4355 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
4356 Consumer.addKeywordResult("this");
4357
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004358 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004359 Consumer.addKeywordResult("alignof");
4360 Consumer.addKeywordResult("nullptr");
4361 }
4362 }
Jordan Rose58d54722012-06-30 21:33:57 +00004363
4364 if (SemaRef.getLangOpts().C11) {
4365 // FIXME: We should not suggest _Alignof if the alignof macro
4366 // is present.
4367 Consumer.addKeywordResult("_Alignof");
4368 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004369 }
4370
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004371 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004372 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
4373 // Statements.
Craig Topperd6d31ac2013-07-15 08:24:27 +00004374 static const char *const CStmts[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004375 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Toppere5ce8312013-07-15 03:38:40 +00004376 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004377 for (unsigned I = 0; I != NumCStmts; ++I)
4378 Consumer.addKeywordResult(CStmts[I]);
4379
David Blaikiebbafb8a2012-03-11 07:00:24 +00004380 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004381 Consumer.addKeywordResult("catch");
4382 Consumer.addKeywordResult("try");
4383 }
4384
4385 if (S && S->getBreakParent())
4386 Consumer.addKeywordResult("break");
4387
4388 if (S && S->getContinueParent())
4389 Consumer.addKeywordResult("continue");
4390
4391 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
4392 Consumer.addKeywordResult("case");
4393 Consumer.addKeywordResult("default");
4394 }
4395 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004396 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004397 Consumer.addKeywordResult("namespace");
4398 Consumer.addKeywordResult("template");
4399 }
4400
4401 if (S && S->isClassScope()) {
4402 Consumer.addKeywordResult("explicit");
4403 Consumer.addKeywordResult("friend");
4404 Consumer.addKeywordResult("mutable");
4405 Consumer.addKeywordResult("private");
4406 Consumer.addKeywordResult("protected");
4407 Consumer.addKeywordResult("public");
4408 Consumer.addKeywordResult("virtual");
4409 }
4410 }
4411
David Blaikiebbafb8a2012-03-11 07:00:24 +00004412 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004413 Consumer.addKeywordResult("using");
4414
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004415 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004416 Consumer.addKeywordResult("static_assert");
4417 }
4418 }
4419}
4420
Kaelyn Takata6c759512014-10-27 18:07:37 +00004421std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
4422 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4423 Scope *S, CXXScopeSpec *SS,
4424 std::unique_ptr<CorrectionCandidateCallback> CCC,
4425 DeclContext *MemberContext, bool EnteringContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004426 const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00004427
4428 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4429 DisableTypoCorrection)
4430 return nullptr;
4431
4432 // In Microsoft mode, don't perform typo correction in a template member
4433 // function dependent context because it interferes with the "lookup into
4434 // dependent bases of class templates" feature.
4435 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
4436 isa<CXXMethodDecl>(CurContext))
4437 return nullptr;
4438
4439 // We only attempt to correct typos for identifiers.
4440 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4441 if (!Typo)
4442 return nullptr;
4443
4444 // If the scope specifier itself was invalid, don't try to correct
4445 // typos.
4446 if (SS && SS->isInvalid())
4447 return nullptr;
4448
4449 // Never try to correct typos during template deduction or
4450 // instantiation.
4451 if (!ActiveTemplateInstantiations.empty())
4452 return nullptr;
4453
4454 // Don't try to correct 'super'.
4455 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4456 return nullptr;
4457
4458 // Abort if typo correction already failed for this specific typo.
4459 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4460 if (locs != TypoCorrectionFailures.end() &&
4461 locs->second.count(TypoName.getLoc()))
4462 return nullptr;
4463
4464 // Don't try to correct the identifier "vector" when in AltiVec mode.
4465 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4466 // remove this workaround.
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00004467 if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector"))
Kaelyn Takata6c759512014-10-27 18:07:37 +00004468 return nullptr;
4469
Nick Lewycky24653262014-12-16 21:39:02 +00004470 // Provide a stop gap for files that are just seriously broken. Trying
4471 // to correct all typos can turn into a HUGE performance penalty, causing
4472 // some files to take minutes to get rejected by the parser.
4473 unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
4474 if (Limit && TyposCorrected >= Limit)
4475 return nullptr;
4476 ++TyposCorrected;
4477
Kaelyn Takata6c759512014-10-27 18:07:37 +00004478 // If we're handling a missing symbol error, using modules, and the
4479 // special search all modules option is used, look for a missing import.
4480 if (ErrorRecovery && getLangOpts().Modules &&
4481 getLangOpts().ModulesSearchAll) {
4482 // The following has the side effect of loading the missing module.
4483 getModuleLoader().lookupMissingImports(Typo->getName(),
4484 TypoName.getLocStart());
4485 }
4486
4487 CorrectionCandidateCallback &CCCRef = *CCC;
4488 auto Consumer = llvm::make_unique<TypoCorrectionConsumer>(
4489 *this, TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
4490 EnteringContext);
4491
Kaelyn Takata6c759512014-10-27 18:07:37 +00004492 // Perform name lookup to find visible, similarly-named entities.
Nick Lewycky24653262014-12-16 21:39:02 +00004493 bool IsUnqualifiedLookup = false;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004494 DeclContext *QualifiedDC = MemberContext;
4495 if (MemberContext) {
4496 LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
4497
4498 // Look in qualified interfaces.
4499 if (OPT) {
4500 for (auto *I : OPT->quals())
4501 LookupVisibleDecls(I, LookupKind, *Consumer);
4502 }
4503 } else if (SS && SS->isSet()) {
4504 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4505 if (!QualifiedDC)
4506 return nullptr;
4507
Kaelyn Takata6c759512014-10-27 18:07:37 +00004508 LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
4509 } else {
4510 IsUnqualifiedLookup = true;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004511 }
4512
4513 // Determine whether we are going to search in the various namespaces for
4514 // corrections.
4515 bool SearchNamespaces
4516 = getLangOpts().CPlusPlus &&
4517 (IsUnqualifiedLookup || (SS && SS->isSet()));
4518
4519 if (IsUnqualifiedLookup || SearchNamespaces) {
4520 // For unqualified lookup, look through all of the names that we have
4521 // seen in this translation unit.
4522 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4523 for (const auto &I : Context.Idents)
4524 Consumer->FoundName(I.getKey());
4525
4526 // Walk through identifiers in external identifier sources.
4527 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4528 if (IdentifierInfoLookup *External
4529 = Context.Idents.getExternalIdentifierLookup()) {
4530 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4531 do {
4532 StringRef Name = Iter->Next();
4533 if (Name.empty())
4534 break;
4535
4536 Consumer->FoundName(Name);
4537 } while (true);
4538 }
4539 }
4540
4541 AddKeywordsToConsumer(*this, *Consumer, S, CCCRef, SS && SS->isNotEmpty());
4542
4543 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4544 // to search those namespaces.
4545 if (SearchNamespaces) {
4546 // Load any externally-known namespaces.
4547 if (ExternalSource && !LoadedExternalKnownNamespaces) {
4548 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
4549 LoadedExternalKnownNamespaces = true;
4550 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4551 for (auto *N : ExternalKnownNamespaces)
4552 KnownNamespaces[N] = true;
4553 }
4554
4555 Consumer->addNamespaces(KnownNamespaces);
4556 }
4557
4558 return Consumer;
4559}
4560
Douglas Gregor2d435302009-12-30 17:04:44 +00004561/// \brief Try to "correct" a typo in the source code by finding
4562/// visible declarations whose names are similar to the name that was
4563/// present in the source code.
4564///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004565/// \param TypoName the \c DeclarationNameInfo structure that contains
4566/// the name that was present in the source code along with its location.
4567///
4568/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00004569///
4570/// \param S the scope in which name lookup occurs.
4571///
4572/// \param SS the nested-name-specifier that precedes the name we're
4573/// looking for, if present.
4574///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004575/// \param CCC A CorrectionCandidateCallback object that provides further
4576/// validation of typo correction candidates. It also provides flags for
4577/// determining the set of keywords permitted.
4578///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00004579/// \param MemberContext if non-NULL, the context in which to look for
4580/// a member access expression.
4581///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004582/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00004583/// the nested-name-specifier SS.
4584///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004585/// \param OPT when non-NULL, the search for visible declarations will
4586/// also walk the protocols in the qualified interfaces of \p OPT.
4587///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004588/// \returns a \c TypoCorrection containing the corrected name if the typo
4589/// along with information such as the \c NamedDecl where the corrected name
4590/// was declared, and any additional \c NestedNameSpecifier needed to access
4591/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
4592TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
4593 Sema::LookupNameKind LookupKind,
4594 Scope *S, CXXScopeSpec *SS,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004595 std::unique_ptr<CorrectionCandidateCallback> CCC,
John Thompson2255f2c2014-04-23 12:57:01 +00004596 CorrectTypoKind Mode,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004597 DeclContext *MemberContext,
4598 bool EnteringContext,
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004599 const ObjCObjectPointerType *OPT,
4600 bool RecordFailure) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004601 assert(CCC && "CorrectTypo requires a CorrectionCandidateCallback");
4602
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004603 // Always let the ExternalSource have the first chance at correction, even
4604 // if we would otherwise have given up.
4605 if (ExternalSource) {
4606 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004607 TypoName, LookupKind, S, SS, *CCC, MemberContext, EnteringContext, OPT))
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004608 return Correction;
4609 }
4610
Kaelyn Takata6c759512014-10-27 18:07:37 +00004611 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4612 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4613 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4614 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
4615 bool ObjCMessageReceiver = CCC->WantObjCSuper && !CCC->WantRemainingKeywords;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004616
Kaelyn Takata6c759512014-10-27 18:07:37 +00004617 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Kaelyn Takata6c759512014-10-27 18:07:37 +00004618 auto Consumer = makeTypoCorrectionConsumer(
4619 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004620 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004621
Kaelyn Takata6c759512014-10-27 18:07:37 +00004622 if (!Consumer)
4623 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004624
Douglas Gregor280e1ee2010-04-14 20:04:41 +00004625 // If we haven't found anything, we're done.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004626 if (Consumer->empty())
Nick Lewycky24653262014-12-16 21:39:02 +00004627 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregor2d435302009-12-30 17:04:44 +00004628
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004629 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4630 // is not more that about a third of the length of the typo's identifier.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004631 unsigned ED = Consumer->getBestEditDistance(true);
4632 unsigned TypoLen = Typo->getName().size();
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004633 if (ED > 0 && TypoLen / ED < 3)
Nick Lewycky24653262014-12-16 21:39:02 +00004634 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004635
Kaelyn Takata6c759512014-10-27 18:07:37 +00004636 TypoCorrection BestTC = Consumer->getNextCorrection();
4637 TypoCorrection SecondBestTC = Consumer->getNextCorrection();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004638 if (!BestTC)
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004639 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004640
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004641 ED = BestTC.getEditDistance();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004642
Kaelyn Takata6c759512014-10-27 18:07:37 +00004643 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004644 // If this was an unqualified lookup and we believe the callback
4645 // object wouldn't have filtered out possible corrections, note
4646 // that no correction was found.
Nick Lewycky24653262014-12-16 21:39:02 +00004647 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004648 }
4649
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004650 // If only a single name remains, return that result.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004651 if (!SecondBestTC ||
4652 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
4653 const TypoCorrection &Result = BestTC;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004654
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00004655 // Don't correct to a keyword that's the same as the typo; the keyword
4656 // wasn't actually in scope.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004657 if (ED == 0 && Result.isKeyword())
4658 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004659
David Blaikie04ea41c2012-10-12 20:00:44 +00004660 TypoCorrection TC = Result;
4661 TC.setCorrectionRange(SS, TypoName);
Kaelyn Takataa95ebc62014-06-17 23:47:29 +00004662 checkCorrectionVisibility(*this, TC);
David Blaikie04ea41c2012-10-12 20:00:44 +00004663 return TC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004664 } else if (SecondBestTC && ObjCMessageReceiver) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004665 // Prefer 'super' when we're completing in a message-receiver
4666 // context.
4667
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004668 if (BestTC.getCorrection().getAsString() != "super") {
4669 if (SecondBestTC.getCorrection().getAsString() == "super")
4670 BestTC = SecondBestTC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004671 else if ((*Consumer)["super"].front().isKeyword())
4672 BestTC = (*Consumer)["super"].front();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004673 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004674 // Don't correct to a keyword that's the same as the typo; the keyword
4675 // wasn't actually in scope.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004676 if (BestTC.getEditDistance() == 0 ||
4677 BestTC.getCorrection().getAsString() != "super")
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004678 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004679
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004680 BestTC.setCorrectionRange(SS, TypoName);
4681 return BestTC;
Douglas Gregoraf9eb592010-10-15 13:35:25 +00004682 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004683
Kaelyn Takata73429fd2014-06-10 21:03:49 +00004684 // Record the failure's location if needed and return an empty correction. If
4685 // this was an unqualified lookup and we believe the callback object did not
4686 // filter out possible corrections, also cache the failure for the typo.
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004687 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004688}
4689
Kaelyn Takata6c759512014-10-27 18:07:37 +00004690/// \brief Try to "correct" a typo in the source code by finding
4691/// visible declarations whose names are similar to the name that was
4692/// present in the source code.
4693///
4694/// \param TypoName the \c DeclarationNameInfo structure that contains
4695/// the name that was present in the source code along with its location.
4696///
4697/// \param LookupKind the name-lookup criteria used to search for the name.
4698///
4699/// \param S the scope in which name lookup occurs.
4700///
4701/// \param SS the nested-name-specifier that precedes the name we're
4702/// looking for, if present.
4703///
4704/// \param CCC A CorrectionCandidateCallback object that provides further
4705/// validation of typo correction candidates. It also provides flags for
4706/// determining the set of keywords permitted.
4707///
4708/// \param TDG A TypoDiagnosticGenerator functor that will be used to print
4709/// diagnostics when the actual typo correction is attempted.
4710///
Kaelyn Takata8363f042014-10-27 18:07:42 +00004711/// \param TRC A TypoRecoveryCallback functor that will be used to build an
4712/// Expr from a typo correction candidate.
4713///
Kaelyn Takata6c759512014-10-27 18:07:37 +00004714/// \param MemberContext if non-NULL, the context in which to look for
4715/// a member access expression.
4716///
4717/// \param EnteringContext whether we're entering the context described by
4718/// the nested-name-specifier SS.
4719///
4720/// \param OPT when non-NULL, the search for visible declarations will
4721/// also walk the protocols in the qualified interfaces of \p OPT.
4722///
4723/// \returns a new \c TypoExpr that will later be replaced in the AST with an
4724/// Expr representing the result of performing typo correction, or nullptr if
4725/// typo correction is not possible. If nullptr is returned, no diagnostics will
4726/// be emitted and it is the responsibility of the caller to emit any that are
4727/// needed.
4728TypoExpr *Sema::CorrectTypoDelayed(
4729 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4730 Scope *S, CXXScopeSpec *SS,
4731 std::unique_ptr<CorrectionCandidateCallback> CCC,
Kaelyn Takata8363f042014-10-27 18:07:42 +00004732 TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,
Kaelyn Takata6c759512014-10-27 18:07:37 +00004733 DeclContext *MemberContext, bool EnteringContext,
4734 const ObjCObjectPointerType *OPT) {
4735 assert(CCC && "CorrectTypoDelayed requires a CorrectionCandidateCallback");
4736
4737 TypoCorrection Empty;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004738 auto Consumer = makeTypoCorrectionConsumer(
4739 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004740 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Kaelyn Takata6c759512014-10-27 18:07:37 +00004741
4742 if (!Consumer || Consumer->empty())
4743 return nullptr;
4744
4745 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4746 // is not more that about a third of the length of the typo's identifier.
4747 unsigned ED = Consumer->getBestEditDistance(true);
4748 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4749 if (ED > 0 && Typo->getName().size() / ED < 3)
4750 return nullptr;
4751
4752 ExprEvalContexts.back().NumTypos++;
Kaelyn Takata8363f042014-10-27 18:07:42 +00004753 return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC));
Kaelyn Takata6c759512014-10-27 18:07:37 +00004754}
4755
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004756void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4757 if (!CDecl) return;
4758
4759 if (isKeyword())
4760 CorrectionDecls.clear();
4761
Richard Smithde6d6c42015-12-29 19:43:10 +00004762 CorrectionDecls.push_back(CDecl);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004763
4764 if (!CorrectionName)
4765 CorrectionName = CDecl->getDeclName();
4766}
4767
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004768std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4769 if (CorrectionNameSpec) {
4770 std::string tmpBuffer;
4771 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4772 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikied4da8722013-05-14 21:04:00 +00004773 PrefixOStream << CorrectionName;
Benjamin Kramer73faad62012-04-14 08:26:28 +00004774 return PrefixOStream.str();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004775 }
4776
4777 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00004778}
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004779
Nico Weberb58e51c2014-11-19 05:21:39 +00004780bool CorrectionCandidateCallback::ValidateCandidate(
4781 const TypoCorrection &candidate) {
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004782 if (!candidate.isResolved())
4783 return true;
4784
4785 if (candidate.isKeyword())
4786 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4787 WantRemainingKeywords || WantObjCSuper;
4788
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004789 bool HasNonType = false;
4790 bool HasStaticMethod = false;
4791 bool HasNonStaticMethod = false;
4792 for (Decl *D : candidate) {
4793 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
4794 D = FTD->getTemplatedDecl();
4795 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4796 if (Method->isStatic())
4797 HasStaticMethod = true;
4798 else
4799 HasNonStaticMethod = true;
4800 }
4801 if (!isa<TypeDecl>(D))
4802 HasNonType = true;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004803 }
4804
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004805 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
4806 !candidate.getCorrectionSpecifier())
4807 return false;
4808
4809 return WantTypeSpecifiers || HasNonType;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004810}
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004811
4812FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004813 bool HasExplicitTemplateArgs,
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004814 MemberExpr *ME)
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004815 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004816 CurContext(SemaRef.CurContext), MemberFn(ME) {
Kaelyn Takatab04846b2014-07-28 18:14:02 +00004817 WantTypeSpecifiers = false;
4818 WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus && NumArgs == 1;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004819 WantRemainingKeywords = false;
4820}
4821
4822bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4823 if (!candidate.getCorrectionDecl())
4824 return candidate.isKeyword();
4825
Aaron Ballman1e606f42014-07-15 22:03:49 +00004826 for (auto *C : candidate) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004827 FunctionDecl *FD = nullptr;
Aaron Ballman1e606f42014-07-15 22:03:49 +00004828 NamedDecl *ND = C->getUnderlyingDecl();
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004829 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4830 FD = FTD->getTemplatedDecl();
4831 if (!HasExplicitTemplateArgs && !FD) {
4832 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4833 // If the Decl is neither a function nor a template function,
4834 // determine if it is a pointer or reference to a function. If so,
4835 // check against the number of arguments expected for the pointee.
4836 QualType ValType = cast<ValueDecl>(ND)->getType();
4837 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4838 ValType = ValType->getPointeeType();
4839 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
Alp Toker9cacbab2014-01-20 20:26:09 +00004840 if (FPT->getNumParams() == NumArgs)
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004841 return true;
4842 }
4843 }
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004844
4845 // Skip the current candidate if it is not a FunctionDecl or does not accept
4846 // the current number of arguments.
4847 if (!FD || !(FD->getNumParams() >= NumArgs &&
4848 FD->getMinRequiredArguments() <= NumArgs))
4849 continue;
4850
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004851 // If the current candidate is a non-static C++ method, skip the candidate
4852 // unless the method being corrected--or the current DeclContext, if the
4853 // function being corrected is not a method--is a method in the same class
4854 // or a descendent class of the candidate's parent class.
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004855 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004856 if (MemberFn || !MD->isStatic()) {
4857 CXXMethodDecl *CurMD =
4858 MemberFn
4859 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
4860 : dyn_cast_or_null<CXXMethodDecl>(CurContext);
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004861 CXXRecordDecl *CurRD =
Craig Topperc3ec1492014-05-26 06:22:03 +00004862 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004863 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
4864 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
4865 continue;
4866 }
4867 }
4868 return true;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004869 }
4870 return false;
4871}
Richard Smithf9b15102013-08-17 00:46:16 +00004872
4873void Sema::diagnoseTypo(const TypoCorrection &Correction,
4874 const PartialDiagnostic &TypoDiag,
4875 bool ErrorRecovery) {
4876 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
4877 ErrorRecovery);
4878}
4879
Richard Smithe156254d2013-08-20 20:35:18 +00004880/// Find which declaration we should import to provide the definition of
4881/// the given declaration.
Richard Smith42413142015-05-15 20:05:43 +00004882static NamedDecl *getDefinitionToImport(NamedDecl *D) {
4883 if (VarDecl *VD = dyn_cast<VarDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004884 return VD->getDefinition();
4885 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Richard Smith42413142015-05-15 20:05:43 +00004886 return FD->isDefined(FD) ? const_cast<FunctionDecl*>(FD) : nullptr;
4887 if (TagDecl *TD = dyn_cast<TagDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004888 return TD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00004889 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004890 return ID->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00004891 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004892 return PD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00004893 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004894 return getDefinitionToImport(TD->getTemplatedDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004895 return nullptr;
Richard Smithe156254d2013-08-20 20:35:18 +00004896}
4897
Richard Smithf2b1eb92015-06-15 20:15:48 +00004898void Sema::diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
4899 bool NeedDefinition, bool Recover) {
4900 assert(!isVisible(Decl) && "missing import for non-hidden decl?");
4901
4902 // Suggest importing a module providing the definition of this entity, if
4903 // possible.
4904 NamedDecl *Def = getDefinitionToImport(Decl);
4905 if (!Def)
4906 Def = Decl;
4907
4908 // FIXME: Add a Fix-It that imports the corresponding module or includes
4909 // the header.
4910 Module *Owner = getOwningModule(Decl);
4911 assert(Owner && "definition of hidden declaration is not in a module");
4912
Richard Smith35c1df52015-06-17 20:16:32 +00004913 llvm::SmallVector<Module*, 8> OwningModules;
4914 OwningModules.push_back(Owner);
Richard Smithf2b1eb92015-06-15 20:15:48 +00004915 auto Merged = Context.getModulesWithMergedDefinition(Decl);
Richard Smith35c1df52015-06-17 20:16:32 +00004916 OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end());
4917
4918 diagnoseMissingImport(Loc, Decl, Decl->getLocation(), OwningModules,
4919 NeedDefinition ? MissingImportKind::Definition
4920 : MissingImportKind::Declaration,
4921 Recover);
4922}
4923
4924void Sema::diagnoseMissingImport(SourceLocation UseLoc, NamedDecl *Decl,
4925 SourceLocation DeclLoc,
4926 ArrayRef<Module *> Modules,
4927 MissingImportKind MIK, bool Recover) {
4928 assert(!Modules.empty());
4929
4930 if (Modules.size() > 1) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00004931 std::string ModuleList;
Richard Smithf2b1eb92015-06-15 20:15:48 +00004932 unsigned N = 0;
Richard Smith35c1df52015-06-17 20:16:32 +00004933 for (Module *M : Modules) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00004934 ModuleList += "\n ";
Richard Smith35c1df52015-06-17 20:16:32 +00004935 if (++N == 5 && N != Modules.size()) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00004936 ModuleList += "[...]";
4937 break;
4938 }
4939 ModuleList += M->getFullModuleName();
4940 }
4941
Richard Smith35c1df52015-06-17 20:16:32 +00004942 Diag(UseLoc, diag::err_module_unimported_use_multiple)
4943 << (int)MIK << Decl << ModuleList;
Richard Smithf2b1eb92015-06-15 20:15:48 +00004944 } else {
Richard Smith35c1df52015-06-17 20:16:32 +00004945 Diag(UseLoc, diag::err_module_unimported_use)
4946 << (int)MIK << Decl << Modules[0]->getFullModuleName();
Richard Smithf2b1eb92015-06-15 20:15:48 +00004947 }
Richard Smith35c1df52015-06-17 20:16:32 +00004948
4949 unsigned DiagID;
4950 switch (MIK) {
4951 case MissingImportKind::Declaration:
4952 DiagID = diag::note_previous_declaration;
4953 break;
4954 case MissingImportKind::Definition:
4955 DiagID = diag::note_previous_definition;
4956 break;
4957 case MissingImportKind::DefaultArgument:
4958 DiagID = diag::note_default_argument_declared_here;
4959 break;
4960 }
4961 Diag(DeclLoc, DiagID);
Richard Smithf2b1eb92015-06-15 20:15:48 +00004962
4963 // Try to recover by implicitly importing this module.
4964 if (Recover)
Richard Smith35c1df52015-06-17 20:16:32 +00004965 createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
Richard Smithf2b1eb92015-06-15 20:15:48 +00004966}
4967
Richard Smithf9b15102013-08-17 00:46:16 +00004968/// \brief Diagnose a successfully-corrected typo. Separated from the correction
4969/// itself to allow external validation of the result, etc.
4970///
4971/// \param Correction The result of performing typo correction.
4972/// \param TypoDiag The diagnostic to produce. This will have the corrected
4973/// string added to it (and usually also a fixit).
4974/// \param PrevNote A note to use when indicating the location of the entity to
4975/// which we are correcting. Will have the correction string added to it.
4976/// \param ErrorRecovery If \c true (the default), the caller is going to
4977/// recover from the typo as if the corrected string had been typed.
4978/// In this case, \c PDiag must be an error, and we will attach a fixit
4979/// to it.
4980void Sema::diagnoseTypo(const TypoCorrection &Correction,
4981 const PartialDiagnostic &TypoDiag,
4982 const PartialDiagnostic &PrevNote,
4983 bool ErrorRecovery) {
4984 std::string CorrectedStr = Correction.getAsString(getLangOpts());
4985 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
4986 FixItHint FixTypo = FixItHint::CreateReplacement(
4987 Correction.getCorrectionRange(), CorrectedStr);
4988
Richard Smithe156254d2013-08-20 20:35:18 +00004989 // Maybe we're just missing a module import.
4990 if (Correction.requiresImport()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00004991 NamedDecl *Decl = Correction.getFoundDecl();
Richard Smithe156254d2013-08-20 20:35:18 +00004992 assert(Decl && "import required but no declaration to import");
4993
Richard Smithf2b1eb92015-06-15 20:15:48 +00004994 diagnoseMissingImport(Correction.getCorrectionRange().getBegin(), Decl,
4995 /*NeedDefinition*/ false, ErrorRecovery);
Richard Smithe156254d2013-08-20 20:35:18 +00004996 return;
4997 }
4998
Richard Smithf9b15102013-08-17 00:46:16 +00004999 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
5000 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
5001
5002 NamedDecl *ChosenDecl =
Richard Smithde6d6c42015-12-29 19:43:10 +00005003 Correction.isKeyword() ? nullptr : Correction.getFoundDecl();
Richard Smithf9b15102013-08-17 00:46:16 +00005004 if (PrevNote.getDiagID() && ChosenDecl)
5005 Diag(ChosenDecl->getLocation(), PrevNote)
5006 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
5007}
Kaelyn Takata6c759512014-10-27 18:07:37 +00005008
Kaelyn Takata8363f042014-10-27 18:07:42 +00005009TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
5010 TypoDiagnosticGenerator TDG,
5011 TypoRecoveryCallback TRC) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00005012 assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
5013 auto TE = new (Context) TypoExpr(Context.DependentTy);
5014 auto &State = DelayedTypos[TE];
5015 State.Consumer = std::move(TCC);
5016 State.DiagHandler = std::move(TDG);
Kaelyn Takata8363f042014-10-27 18:07:42 +00005017 State.RecoveryHandler = std::move(TRC);
Kaelyn Takata6c759512014-10-27 18:07:37 +00005018 return TE;
5019}
5020
5021const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
5022 auto Entry = DelayedTypos.find(TE);
5023 assert(Entry != DelayedTypos.end() &&
5024 "Failed to get the state for a TypoExpr!");
5025 return Entry->second;
5026}
5027
5028void Sema::clearDelayedTypo(TypoExpr *TE) {
5029 DelayedTypos.erase(TE);
5030}
Richard Smithba3a4f92016-01-12 21:59:26 +00005031
5032void Sema::ActOnPragmaDump(Scope *S, SourceLocation IILoc, IdentifierInfo *II) {
5033 DeclarationNameInfo Name(II, IILoc);
5034 LookupResult R(*this, Name, LookupAnyName, Sema::NotForRedeclaration);
5035 R.suppressDiagnostics();
5036 R.setHideTags(false);
5037 LookupName(R, S);
5038 R.dump();
5039}