blob: 55ca678a5fae5df4a16300de57baa88ef8147545 [file] [log] [blame]
Hans Wennborgdcfba332015-10-06 23:40:43 +00001//===--------------------- SemaLookup.cpp - Name Lookup --------*- C++ -*-===//
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) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000157 SmallVector<DeclContext*,4> queue;
John McCallf6c8a4e2009-11-10 07:01:13 +0000158 while (true) {
Aaron Ballman804a7fb2014-03-17 17:14:12 +0000159 for (auto UD : DC->using_directives()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000160 DeclContext *NS = UD->getNominatedNamespace();
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
371 // If they have different underlying declarations, pick one arbitrarily
372 // (this happens when two type declarations denote the same type).
373 // FIXME: Should we prefer a struct declaration over a typedef or vice versa?
374 // If a name could be a typedef-name or a class-name, which is it?
375 if (DUnderlying->getCanonicalDecl() != EUnderlying->getCanonicalDecl()) {
376 assert(isa<TypeDecl>(DUnderlying) && isa<TypeDecl>(EUnderlying));
377 return false;
378 }
379
Richard Smithcd31b852015-08-22 21:37:34 +0000380 // Pick the function with more default arguments.
381 // FIXME: In the presence of ambiguous default arguments, we should keep both,
382 // so we can diagnose the ambiguity if the default argument is needed.
383 // See C++ [over.match.best]p3.
384 if (auto *DFD = dyn_cast<FunctionDecl>(DUnderlying)) {
385 auto *EFD = cast<FunctionDecl>(EUnderlying);
386 unsigned DMin = DFD->getMinRequiredArguments();
387 unsigned EMin = EFD->getMinRequiredArguments();
388 // If D has more default arguments, it is preferred.
389 if (DMin != EMin)
390 return DMin < EMin;
Richard Smith535ff802015-09-11 22:39:35 +0000391 // FIXME: When we track visibility for default function arguments, check
392 // that we pick the declaration with more visible default arguments.
Richard Smithcd31b852015-08-22 21:37:34 +0000393 }
394
395 // Pick the template with more default template arguments.
396 if (auto *DTD = dyn_cast<TemplateDecl>(DUnderlying)) {
397 auto *ETD = cast<TemplateDecl>(EUnderlying);
398 unsigned DMin = DTD->getTemplateParameters()->getMinRequiredArguments();
399 unsigned EMin = ETD->getTemplateParameters()->getMinRequiredArguments();
Richard Smith535ff802015-09-11 22:39:35 +0000400 // If D has more default arguments, it is preferred. Note that default
401 // arguments (and their visibility) is monotonically increasing across the
402 // redeclaration chain, so this is a quick proxy for "is more recent".
Richard Smithcd31b852015-08-22 21:37:34 +0000403 if (DMin != EMin)
404 return DMin < EMin;
Richard Smith535ff802015-09-11 22:39:35 +0000405 // If D has more *visible* default arguments, it is preferred. Note, an
406 // earlier default argument being visible does not imply that a later
407 // default argument is visible, so we can't just check the first one.
408 for (unsigned I = DMin, N = DTD->getTemplateParameters()->size();
409 I != N; ++I) {
410 if (!S.hasVisibleDefaultArgument(
411 ETD->getTemplateParameters()->getParam(I)) &&
412 S.hasVisibleDefaultArgument(
413 DTD->getTemplateParameters()->getParam(I)))
414 return true;
415 }
Richard Smithcd31b852015-08-22 21:37:34 +0000416 }
417
418 // For most kinds of declaration, it doesn't really matter which one we pick.
419 if (!isa<FunctionDecl>(DUnderlying) && !isa<VarDecl>(DUnderlying)) {
420 // If the existing declaration is hidden, prefer the new one. Otherwise,
421 // keep what we've got.
422 return !S.isVisible(Existing);
423 }
424
425 // Pick the newer declaration; it might have a more precise type.
Richard Smith826711d2015-07-29 23:38:25 +0000426 for (Decl *Prev = DUnderlying->getPreviousDecl(); Prev;
427 Prev = Prev->getPreviousDecl())
428 if (Prev == EUnderlying)
429 return true;
Richard Smith826711d2015-07-29 23:38:25 +0000430 return false;
Richard Smithcd31b852015-08-22 21:37:34 +0000431
432 // If the existing declaration is hidden, prefer the new one. Otherwise,
433 // keep what we've got.
434 return !S.isVisible(Existing);
Richard Smith826711d2015-07-29 23:38:25 +0000435}
436
John McCall283b9012009-11-22 00:44:51 +0000437/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000438void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000439 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000440
John McCall9f3059a2009-10-09 21:13:30 +0000441 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000442 if (N == 0) {
Richard Smith826711d2015-07-29 23:38:25 +0000443 assert(ResultKind == NotFound ||
444 ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000445 return;
446 }
447
John McCall283b9012009-11-22 00:44:51 +0000448 // If there's a single decl, we need to examine it to decide what
449 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000450 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000451 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
452 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000453 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000454 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000455 ResultKind = FoundUnresolvedValue;
456 return;
457 }
John McCall9f3059a2009-10-09 21:13:30 +0000458
John McCall6538c932009-10-10 05:48:19 +0000459 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000460 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000461
Richard Smitha534a312015-07-21 23:54:07 +0000462 llvm::SmallDenseMap<NamedDecl*, unsigned, 16> Unique;
Richard Smith826711d2015-07-29 23:38:25 +0000463 llvm::SmallDenseMap<QualType, unsigned, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000464
John McCall9f3059a2009-10-09 21:13:30 +0000465 bool Ambiguous = false;
466 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000467 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000468
469 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000470
John McCall9f3059a2009-10-09 21:13:30 +0000471 unsigned I = 0;
472 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000473 NamedDecl *D = Decls[I]->getUnderlyingDecl();
474 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000475
Argyrios Kyrtzidis1fcd7fd2013-02-22 06:58:37 +0000476 // Ignore an invalid declaration unless it's the only one left.
477 if (D->isInvalidDecl() && I < N-1) {
478 Decls[I] = Decls[--N];
479 continue;
480 }
481
Richard Smith826711d2015-07-29 23:38:25 +0000482 llvm::Optional<unsigned> ExistingI;
483
Douglas Gregor13e65872010-08-11 14:45:53 +0000484 // Redeclarations of types via typedef can occur both within a scope
485 // and, through using declarations and directives, across scopes. There is
486 // no ambiguity if they all refer to the same type, so unique based on the
487 // canonical type.
488 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
Richard Smith826711d2015-07-29 23:38:25 +0000489 // FIXME: Why are nested type declarations treated differently?
Douglas Gregor13e65872010-08-11 14:45:53 +0000490 if (!TD->getDeclContext()->isRecord()) {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000491 QualType T = getSema().Context.getTypeDeclType(TD);
Richard Smith826711d2015-07-29 23:38:25 +0000492 auto UniqueResult = UniqueTypes.insert(
493 std::make_pair(getSema().Context.getCanonicalType(T), I));
494 if (!UniqueResult.second) {
495 // The type is not unique.
496 ExistingI = UniqueResult.first->second;
Douglas Gregor13e65872010-08-11 14:45:53 +0000497 }
498 }
499 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000500
Richard Smith826711d2015-07-29 23:38:25 +0000501 // For non-type declarations, check for a prior lookup result naming this
502 // canonical declaration.
503 if (!ExistingI) {
504 auto UniqueResult = Unique.insert(std::make_pair(D, I));
505 if (!UniqueResult.second) {
506 // We've seen this entity before.
507 ExistingI = UniqueResult.first->second;
Richard Smitha534a312015-07-21 23:54:07 +0000508 }
Richard Smith826711d2015-07-29 23:38:25 +0000509 }
510
511 if (ExistingI) {
512 // This is not a unique lookup result. Pick one of the results and
513 // discard the other.
Richard Smithcd31b852015-08-22 21:37:34 +0000514 if (isPreferredLookupResult(getSema(), getLookupKind(), Decls[I],
Richard Smith826711d2015-07-29 23:38:25 +0000515 Decls[*ExistingI]))
516 Decls[*ExistingI] = Decls[I];
517 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000518 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000519 }
520
Douglas Gregor13e65872010-08-11 14:45:53 +0000521 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000522
Douglas Gregor13e65872010-08-11 14:45:53 +0000523 if (isa<UnresolvedUsingValueDecl>(D)) {
524 HasUnresolved = true;
525 } else if (isa<TagDecl>(D)) {
526 if (HasTag)
527 Ambiguous = true;
528 UniqueTagIndex = I;
529 HasTag = true;
530 } else if (isa<FunctionTemplateDecl>(D)) {
531 HasFunction = true;
532 HasFunctionTemplate = true;
533 } else if (isa<FunctionDecl>(D)) {
534 HasFunction = true;
535 } else {
536 if (HasNonFunction)
537 Ambiguous = true;
538 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000539 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000540 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000541 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000542
John McCall9f3059a2009-10-09 21:13:30 +0000543 // C++ [basic.scope.hiding]p2:
544 // A class name or enumeration name can be hidden by the name of
545 // an object, function, or enumerator declared in the same
546 // scope. If a class or enumeration name and an object, function,
547 // or enumerator are declared in the same scope (in any order)
548 // with the same name, the class or enumeration name is hidden
549 // wherever the object, function, or enumerator name is visible.
550 // But it's still an error if there are distinct tag types found,
551 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000552 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000553 (HasFunction || HasNonFunction || HasUnresolved)) {
Richard Smith3876cc82013-10-30 01:02:04 +0000554 if (getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
555 getContextForScopeMatching(Decls[UniqueTagIndex ? 0 : N - 1])))
Douglas Gregore63d0872010-10-23 16:06:17 +0000556 Decls[UniqueTagIndex] = Decls[--N];
557 else
558 Ambiguous = true;
559 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000560
John McCall9f3059a2009-10-09 21:13:30 +0000561 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000562
John McCall80053822009-12-03 00:58:24 +0000563 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000564 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000565
John McCall9f3059a2009-10-09 21:13:30 +0000566 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000567 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000568 else if (HasUnresolved)
569 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000570 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000571 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000572 else
John McCall27b18f82009-11-17 02:14:36 +0000573 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000574}
575
John McCall5cebab12009-11-18 07:57:50 +0000576void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000577 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000578 for (I = P.begin(), E = P.end(); I != E; ++I)
David Blaikieff7d47a2012-12-19 00:45:41 +0000579 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
580 DE = I->Decls.end(); DI != DE; ++DI)
John McCall9f3059a2009-10-09 21:13:30 +0000581 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000582}
583
John McCall5cebab12009-11-18 07:57:50 +0000584void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000585 Paths = new CXXBasePaths;
586 Paths->swap(P);
587 addDeclsFromBasePaths(*Paths);
588 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000589 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000590}
591
John McCall5cebab12009-11-18 07:57:50 +0000592void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000593 Paths = new CXXBasePaths;
594 Paths->swap(P);
595 addDeclsFromBasePaths(*Paths);
596 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000597 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000598}
599
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000600void LookupResult::print(raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000601 Out << Decls.size() << " result(s)";
602 if (isAmbiguous()) Out << ", ambiguous";
603 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000604
John McCall9f3059a2009-10-09 21:13:30 +0000605 for (iterator I = begin(), E = end(); I != E; ++I) {
606 Out << "\n";
607 (*I)->print(Out, 2);
608 }
609}
610
Douglas Gregord3a59182010-02-12 05:48:04 +0000611/// \brief Lookup a builtin function, when name lookup would otherwise
612/// fail.
613static bool LookupBuiltin(Sema &S, LookupResult &R) {
614 Sema::LookupNameKind NameKind = R.getLookupKind();
615
616 // If we didn't find a use of this identifier, and if the identifier
617 // corresponds to a compiler builtin, create the decl object for the builtin
618 // now, injecting it into translation unit scope, and return it.
619 if (NameKind == Sema::LookupOrdinaryName ||
620 NameKind == Sema::LookupRedeclarationWithLinkage) {
621 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
622 if (II) {
Nico Webere1687c52013-06-20 21:44:55 +0000623 if (S.getLangOpts().CPlusPlus11 && S.getLangOpts().GNUMode &&
624 II == S.getFloat128Identifier()) {
625 // libstdc++4.7's type_traits expects type __float128 to exist, so
626 // insert a dummy type to make that header build in gnu++11 mode.
627 R.addDecl(S.getASTContext().getFloat128StubType());
628 return true;
629 }
630
Douglas Gregord3a59182010-02-12 05:48:04 +0000631 // If this is a builtin on this (or all) targets, create the decl.
632 if (unsigned BuiltinID = II->getBuiltinID()) {
633 // In C++, we don't have any predefined library functions like
634 // 'malloc'. Instead, we'll just error.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000635 if (S.getLangOpts().CPlusPlus &&
Douglas Gregord3a59182010-02-12 05:48:04 +0000636 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
637 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000638
639 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
640 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000641 R.isForRedeclaration(),
642 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000643 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000644 return true;
645 }
Douglas Gregord3a59182010-02-12 05:48:04 +0000646 }
647 }
648 }
649
650 return false;
651}
652
Douglas Gregor7454c562010-07-02 20:37:36 +0000653/// \brief Determine whether we can declare a special member function within
654/// the class at this point.
Richard Smith7d125a12012-11-27 21:20:31 +0000655static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +0000656 // We need to have a definition for the class.
657 if (!Class->getDefinition() || Class->isDependentContext())
658 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000659
Douglas Gregor7454c562010-07-02 20:37:36 +0000660 // We can't be in the middle of defining the class.
Richard Smith7d125a12012-11-27 21:20:31 +0000661 return !Class->isBeingDefined();
Douglas Gregor7454c562010-07-02 20:37:36 +0000662}
663
664void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smith7d125a12012-11-27 21:20:31 +0000665 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregora6d69502010-07-02 23:41:54 +0000666 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000667
668 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000669 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000670 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000671
Douglas Gregora6d69502010-07-02 23:41:54 +0000672 // If the copy constructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000673 if (Class->needsImplicitCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +0000674 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000675
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000676 // If the copy assignment operator has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000677 if (Class->needsImplicitCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000678 DeclareImplicitCopyAssignment(Class);
679
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000680 if (getLangOpts().CPlusPlus11) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000681 // If the move constructor has not yet been declared, do so now.
682 if (Class->needsImplicitMoveConstructor())
683 DeclareImplicitMoveConstructor(Class); // might not actually do it
684
685 // If the move assignment operator has not yet been declared, do so now.
686 if (Class->needsImplicitMoveAssignment())
687 DeclareImplicitMoveAssignment(Class); // might not actually do it
688 }
689
Douglas Gregor7454c562010-07-02 20:37:36 +0000690 // If the destructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000691 if (Class->needsImplicitDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000692 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000693}
694
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000695/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000696/// special member function.
697static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
698 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000699 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000700 case DeclarationName::CXXDestructorName:
701 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000702
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000703 case DeclarationName::CXXOperatorName:
704 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000705
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000706 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000707 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000708 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000709
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000710 return false;
711}
712
713/// \brief If there are any implicit member functions with the given name
714/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000715static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000716 DeclarationName Name,
717 const DeclContext *DC) {
718 if (!DC)
719 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000720
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000721 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000722 case DeclarationName::CXXConstructorName:
723 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith7d125a12012-11-27 21:20:31 +0000724 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000725 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000726 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000727 S.DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +0000728 if (Record->needsImplicitCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000729 S.DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000730 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000731 Record->needsImplicitMoveConstructor())
732 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000733 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000734 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000735
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000736 case DeclarationName::CXXDestructorName:
737 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith2be35f52012-12-01 02:35:44 +0000738 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smith7d125a12012-11-27 21:20:31 +0000739 CanDeclareSpecialMemberFunction(Record))
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000740 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000741 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000742
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000743 case DeclarationName::CXXOperatorName:
744 if (Name.getCXXOverloadedOperator() != OO_Equal)
745 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000746
Sebastian Redl22653ba2011-08-30 19:58:05 +0000747 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smith7d125a12012-11-27 21:20:31 +0000748 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000749 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smith2be35f52012-12-01 02:35:44 +0000750 if (Record->needsImplicitCopyAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000751 S.DeclareImplicitCopyAssignment(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000752 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000753 Record->needsImplicitMoveAssignment())
754 S.DeclareImplicitMoveAssignment(Class);
755 }
756 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000757 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000758
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000759 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000760 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000761 }
762}
Douglas Gregor7454c562010-07-02 20:37:36 +0000763
John McCall9f3059a2009-10-09 21:13:30 +0000764// Adds all qualifying matches for a name within a decl context to the
765// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000766static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000767 bool Found = false;
768
Douglas Gregor7454c562010-07-02 20:37:36 +0000769 // Lazily declare C++ special member functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000770 if (S.getLangOpts().CPlusPlus)
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000771 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000772
Douglas Gregor7454c562010-07-02 20:37:36 +0000773 // Perform lookup into this declaration context.
Richard Smithcf4bdde2015-02-21 02:45:19 +0000774 DeclContext::lookup_result DR = DC->lookup(R.getLookupName());
775 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E;
David Blaikieff7d47a2012-12-19 00:45:41 +0000776 ++I) {
John McCall401982f2010-01-20 21:53:11 +0000777 NamedDecl *D = *I;
Douglas Gregor4a814562011-12-14 16:03:29 +0000778 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000779 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000780 Found = true;
781 }
782 }
John McCall9f3059a2009-10-09 21:13:30 +0000783
Douglas Gregord3a59182010-02-12 05:48:04 +0000784 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
785 return true;
786
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000787 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000788 != DeclarationName::CXXConversionFunctionName ||
789 R.getLookupName().getCXXNameType()->isDependentType() ||
790 !isa<CXXRecordDecl>(DC))
791 return Found;
792
793 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000794 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000795 // name lookup. Instead, any conversion function templates visible in the
796 // context of the use are considered. [...]
797 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000798 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000799 return Found;
800
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +0000801 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
802 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruth3a693b72010-01-31 11:44:02 +0000803 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
804 if (!ConvTemplate)
805 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000806
Chandler Carruth3a693b72010-01-31 11:44:02 +0000807 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000808 // add the conversion function template. When we deduce template
809 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000810 // type of the new declaration with the type of the function template.
811 if (R.isForRedeclaration()) {
812 R.addDecl(ConvTemplate);
813 Found = true;
814 continue;
815 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000816
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000817 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000818 // [...] For each such operator, if argument deduction succeeds
819 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000820 // name lookup.
821 //
822 // When referencing a conversion function for any purpose other than
823 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000824 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000825 // specialization into the result set. We do this to avoid forcing all
826 // callers to perform special deduction for conversion functions.
Craig Toppere6706e42012-09-19 02:26:47 +0000827 TemplateDeductionInfo Info(R.getNameLoc());
Craig Topperc3ec1492014-05-26 06:22:03 +0000828 FunctionDecl *Specialization = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000829
830 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000831 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
832 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000833
Chandler Carruth3a693b72010-01-31 11:44:02 +0000834 // Compute the type of the function that we would expect the conversion
835 // function to have, if it were to match the name given.
836 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000837 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
Reid Kleckner78af0702013-08-27 23:08:25 +0000838 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
Richard Smith8acb4282014-07-31 21:57:55 +0000839 EPI.ExceptionSpec = EST_None;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000840 QualType ExpectedType
841 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000842 None, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000843
Chandler Carruth3a693b72010-01-31 11:44:02 +0000844 // Perform template argument deduction against the type that we would
845 // expect the function to have.
Craig Topperc3ec1492014-05-26 06:22:03 +0000846 if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
Chandler Carruth3a693b72010-01-31 11:44:02 +0000847 Specialization, Info)
848 == Sema::TDK_Success) {
849 R.addDecl(Specialization);
850 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000851 }
852 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000853
John McCall9f3059a2009-10-09 21:13:30 +0000854 return Found;
855}
856
John McCallf6c8a4e2009-11-10 07:01:13 +0000857// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000858static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000859CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000860 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000861
862 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
863
John McCallf6c8a4e2009-11-10 07:01:13 +0000864 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000865 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000866
John McCallf6c8a4e2009-11-10 07:01:13 +0000867 // Perform direct name lookup into the namespaces nominated by the
868 // using directives whose common ancestor is this namespace.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000869 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
870 if (LookupDirect(S, R, UUE.getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000871 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000872
873 R.resolveKind();
874
875 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000876}
877
878static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000879 if (DeclContext *Ctx = S->getEntity())
Douglas Gregor700792c2009-02-05 19:25:20 +0000880 return Ctx->isFileContext();
881 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000882}
Douglas Gregored8f2882009-01-30 01:04:22 +0000883
Douglas Gregor66230062010-03-15 14:33:29 +0000884// Find the next outer declaration context from this scope. This
885// routine actually returns the semantic outer context, which may
886// differ from the lexical context (encoded directly in the Scope
887// stack) when we are parsing a member of a class template. In this
888// case, the second element of the pair will be true, to indicate that
889// name lookup should continue searching in this semantic context when
890// it leaves the current template parameter scope.
891static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000892 DeclContext *DC = S->getEntity();
Craig Topperc3ec1492014-05-26 06:22:03 +0000893 DeclContext *Lexical = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000894 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000895 OuterS = OuterS->getParent()) {
896 if (OuterS->getEntity()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000897 Lexical = OuterS->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +0000898 break;
899 }
900 }
901
902 // C++ [temp.local]p8:
903 // In the definition of a member of a class template that appears
904 // outside of the namespace containing the class template
905 // definition, the name of a template-parameter hides the name of
906 // a member of this namespace.
907 //
908 // Example:
909 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000910 // namespace N {
911 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000912 //
913 // template<class T> class B {
914 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000915 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000916 // }
917 //
918 // template<class C> void N::B<C>::f(C) {
919 // C b; // C is the template parameter, not N::C
920 // }
921 //
922 // In this example, the lexical context we return is the
923 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000924 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000925 !S->getParent()->isTemplateParamScope())
926 return std::make_pair(Lexical, false);
927
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000928 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000929 // For the example, this is the scope for the template parameters of
930 // template<class C>.
931 Scope *OutermostTemplateScope = S->getParent();
932 while (OutermostTemplateScope->getParent() &&
933 OutermostTemplateScope->getParent()->isTemplateParamScope())
934 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000935
Douglas Gregor66230062010-03-15 14:33:29 +0000936 // Find the namespace context in which the original scope occurs. In
937 // the example, this is namespace N.
938 DeclContext *Semantic = DC;
939 while (!Semantic->isFileContext())
940 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000941
Douglas Gregor66230062010-03-15 14:33:29 +0000942 // Find the declaration context just outside of the template
943 // parameter scope. This is the context in which the template is
944 // being lexically declaration (a namespace context). In the
945 // example, this is the global scope.
946 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
947 Lexical->Encloses(Semantic))
948 return std::make_pair(Semantic, true);
949
950 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000951}
952
Richard Smith541b38b2013-09-20 01:15:31 +0000953namespace {
954/// An RAII object to specify that we want to find block scope extern
955/// declarations.
956struct FindLocalExternScope {
957 FindLocalExternScope(LookupResult &R)
958 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
959 Decl::IDNS_LocalExtern) {
960 R.setFindLocalExtern(R.getIdentifierNamespace() & Decl::IDNS_Ordinary);
961 }
962 void restore() {
963 R.setFindLocalExtern(OldFindLocalExtern);
964 }
965 ~FindLocalExternScope() {
966 restore();
967 }
968 LookupResult &R;
969 bool OldFindLocalExtern;
970};
Hans Wennborgdcfba332015-10-06 23:40:43 +0000971} // end anonymous namespace
Richard Smith541b38b2013-09-20 01:15:31 +0000972
John McCall27b18f82009-11-17 02:14:36 +0000973bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000974 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000975
976 DeclarationName Name = R.getLookupName();
Richard Smith1c34fb72013-08-13 18:18:50 +0000977 Sema::LookupNameKind NameKind = R.getLookupKind();
John McCall27b18f82009-11-17 02:14:36 +0000978
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000979 // If this is the name of an implicitly-declared special member function,
980 // go through the scope stack to implicitly declare
981 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
982 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +0000983 if (DeclContext *DC = PreS->getEntity())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000984 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
985 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000986
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000987 // Implicitly declare member functions with the name we're looking for, if in
988 // fact we are in a scope where it matters.
989
Douglas Gregor889ceb72009-02-03 19:21:40 +0000990 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000991 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000992 I = IdResolver.begin(Name),
993 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000994
Douglas Gregor889ceb72009-02-03 19:21:40 +0000995 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000996 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000997 // ...During unqualified name lookup (3.4.1), the names appear as if
998 // they were declared in the nearest enclosing namespace which contains
999 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +00001000 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +00001001 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +00001002 //
1003 // For example:
1004 // namespace A { int i; }
1005 // void foo() {
1006 // int i;
1007 // {
1008 // using namespace A;
1009 // ++i; // finds local 'i', A::i appears at global scope
1010 // }
1011 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +00001012 //
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001013 UnqualUsingDirectiveSet UDirs;
1014 bool VisitedUsingDirectives = false;
Richard Smith1c34fb72013-08-13 18:18:50 +00001015 bool LeftStartingScope = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00001016 DeclContext *OutsideOfTemplateParamDC = nullptr;
Richard Smith541b38b2013-09-20 01:15:31 +00001017
1018 // When performing a scope lookup, we want to find local extern decls.
1019 FindLocalExternScope FindLocals(R);
1020
Douglas Gregor700792c2009-02-05 19:25:20 +00001021 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00001022 DeclContext *Ctx = S->getEntity();
Douglas Gregor3e51e172010-05-20 20:58:56 +00001023
Douglas Gregor889ceb72009-02-03 19:21:40 +00001024 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +00001025 bool Found = false;
John McCall48871652010-08-21 09:40:31 +00001026 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001027 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Richard Smith1c34fb72013-08-13 18:18:50 +00001028 if (NameKind == LookupRedeclarationWithLinkage) {
1029 // Determine whether this (or a previous) declaration is
1030 // out-of-scope.
1031 if (!LeftStartingScope && !Initial->isDeclScope(*I))
1032 LeftStartingScope = true;
1033
1034 // If we found something outside of our starting scope that
Richard Smith9a00bbf2013-10-16 21:12:00 +00001035 // does not have linkage, skip it. If it's a template parameter,
1036 // we still find it, so we can diagnose the invalid redeclaration.
1037 if (LeftStartingScope && !((*I)->hasLinkage()) &&
1038 !(*I)->isTemplateParameter()) {
Richard Smith1c34fb72013-08-13 18:18:50 +00001039 R.setShadowed();
1040 continue;
1041 }
1042 }
1043
John McCall9f3059a2009-10-09 21:13:30 +00001044 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +00001045 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001046 }
1047 }
John McCall9f3059a2009-10-09 21:13:30 +00001048 if (Found) {
1049 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +00001050 if (S->isClassScope())
1051 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
1052 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +00001053 return true;
1054 }
1055
Richard Smith1c34fb72013-08-13 18:18:50 +00001056 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
Richard Smith114394f2013-08-09 04:35:01 +00001057 // C++11 [class.friend]p11:
1058 // If a friend declaration appears in a local class and the name
1059 // specified is an unqualified name, a prior declaration is
1060 // looked up without considering scopes that are outside the
1061 // innermost enclosing non-class scope.
1062 return false;
1063 }
1064
Douglas Gregor66230062010-03-15 14:33:29 +00001065 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1066 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1067 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001068 // found nothing, so look into the contexts between the
Douglas Gregor66230062010-03-15 14:33:29 +00001069 // lexical and semantic declaration contexts returned by
1070 // findOuterContext(). This implements the name lookup behavior
1071 // of C++ [temp.local]p8.
1072 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +00001073 OutsideOfTemplateParamDC = nullptr;
Douglas Gregor66230062010-03-15 14:33:29 +00001074 }
1075
1076 if (Ctx) {
1077 DeclContext *OuterCtx;
1078 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001079 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregor66230062010-03-15 14:33:29 +00001080 if (SearchAfterTemplateScope)
1081 OutsideOfTemplateParamDC = OuterCtx;
1082
Douglas Gregorea166062010-03-15 15:26:48 +00001083 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +00001084 // We do not directly look into transparent contexts, since
1085 // those entities will be found in the nearest enclosing
1086 // non-transparent context.
1087 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +00001088 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +00001089
1090 // We do not look directly into function or method contexts,
1091 // since all of the local variables and parameters of the
1092 // function/method are present within the Scope.
1093 if (Ctx->isFunctionOrMethod()) {
1094 // If we have an Objective-C instance method, look for ivars
1095 // in the corresponding interface.
1096 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
1097 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1098 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1099 ObjCInterfaceDecl *ClassDeclared;
1100 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001101 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +00001102 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001103 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1104 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +00001105 R.resolveKind();
1106 return true;
1107 }
1108 }
1109 }
1110 }
1111
1112 continue;
1113 }
1114
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001115 // If this is a file context, we need to perform unqualified name
1116 // lookup considering using directives.
1117 if (Ctx->isFileContext()) {
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001118 // If we haven't handled using directives yet, do so now.
1119 if (!VisitedUsingDirectives) {
1120 // Add using directives from this context up to the top level.
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001121 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1122 if (UCtx->isTransparentContext())
1123 continue;
1124
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001125 UDirs.visit(UCtx, UCtx);
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001126 }
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001127
1128 // Find the innermost file scope, so we can add using directives
1129 // from local scopes.
1130 Scope *InnermostFileScope = S;
1131 while (InnermostFileScope &&
1132 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1133 InnermostFileScope = InnermostFileScope->getParent();
1134 UDirs.visitScopeChain(Initial, InnermostFileScope);
1135
1136 UDirs.done();
1137
1138 VisitedUsingDirectives = true;
1139 }
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001140
1141 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1142 R.resolveKind();
1143 return true;
1144 }
1145
1146 continue;
1147 }
1148
Douglas Gregor7f737c02009-09-10 16:57:35 +00001149 // Perform qualified name lookup into this context.
1150 // FIXME: In some cases, we know that every name that could be found by
1151 // this qualified name lookup will also be on the identifier chain. For
1152 // example, inside a class without any base classes, we never need to
1153 // perform qualified lookup because all of the members are on top of the
1154 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001155 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +00001156 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +00001157 }
Douglas Gregor700792c2009-02-05 19:25:20 +00001158 }
Douglas Gregored8f2882009-01-30 01:04:22 +00001159 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001160
John McCallf6c8a4e2009-11-10 07:01:13 +00001161 // Stop if we ran out of scopes.
1162 // FIXME: This really, really shouldn't be happening.
1163 if (!S) return false;
1164
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001165 // If we are looking for members, no need to look into global/namespace scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00001166 if (NameKind == LookupMemberName)
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001167 return false;
1168
Douglas Gregor700792c2009-02-05 19:25:20 +00001169 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +00001170 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +00001171 //
Mike Stump87c57ac2009-05-16 07:39:55 +00001172 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1173 // don't build it for each lookup!
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001174 if (!VisitedUsingDirectives) {
1175 UDirs.visitScopeChain(Initial, S);
1176 UDirs.done();
1177 }
Richard Smith541b38b2013-09-20 01:15:31 +00001178
1179 // If we're not performing redeclaration lookup, do not look for local
1180 // extern declarations outside of a function scope.
1181 if (!R.isForRedeclaration())
1182 FindLocals.restore();
1183
Douglas Gregor700792c2009-02-05 19:25:20 +00001184 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +00001185 // Unqualified name lookup in C++ requires looking into scopes
1186 // that aren't strictly lexical, and therefore we walk through the
1187 // context as well as walking through the scopes.
1188 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001189 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +00001190 bool Found = false;
John McCall48871652010-08-21 09:40:31 +00001191 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001192 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001193 // We found something. Look for anything else in our scope
1194 // with this same name and in an acceptable identifier
1195 // namespace, so that we can construct an overload set if we
1196 // need to.
John McCall9f3059a2009-10-09 21:13:30 +00001197 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +00001198 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001199 }
1200 }
1201
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001202 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +00001203 R.resolveKind();
1204 return true;
1205 }
1206
Ted Kremenekc37877d2013-10-08 17:08:03 +00001207 DeclContext *Ctx = S->getEntity();
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001208 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1209 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1210 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001211 // found nothing, so look into the contexts between the
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001212 // lexical and semantic declaration contexts returned by
1213 // findOuterContext(). This implements the name lookup behavior
1214 // of C++ [temp.local]p8.
1215 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +00001216 OutsideOfTemplateParamDC = nullptr;
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001217 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001218
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001219 if (Ctx) {
1220 DeclContext *OuterCtx;
1221 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001222 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001223 if (SearchAfterTemplateScope)
1224 OutsideOfTemplateParamDC = OuterCtx;
1225
1226 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1227 // We do not directly look into transparent contexts, since
1228 // those entities will be found in the nearest enclosing
1229 // non-transparent context.
1230 if (Ctx->isTransparentContext())
1231 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001232
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001233 // If we have a context, and it's not a context stashed in the
1234 // template parameter scope for an out-of-line definition, also
1235 // look into that context.
1236 if (!(Found && S && S->isTemplateParamScope())) {
1237 assert(Ctx->isFileContext() &&
1238 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001239
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001240 // Look into context considering using-directives.
1241 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1242 Found = true;
1243 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001244
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001245 if (Found) {
1246 R.resolveKind();
1247 return true;
1248 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001249
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001250 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1251 return false;
1252 }
1253 }
1254
Douglas Gregor3ce74932010-02-05 07:07:10 +00001255 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001256 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001257 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001258
John McCall9f3059a2009-10-09 21:13:30 +00001259 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001260}
1261
Richard Smith0e5d7b82013-07-25 23:08:39 +00001262/// \brief Find the declaration that a class temploid member specialization was
1263/// instantiated from, or the member itself if it is an explicit specialization.
1264static Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) {
1265 return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom();
1266}
1267
Richard Smith42413142015-05-15 20:05:43 +00001268Module *Sema::getOwningModule(Decl *Entity) {
1269 // If it's imported, grab its owning module.
1270 Module *M = Entity->getImportedOwningModule();
1271 if (M || !isa<NamedDecl>(Entity) || !cast<NamedDecl>(Entity)->isHidden())
1272 return M;
1273 assert(!Entity->isFromASTFile() &&
1274 "hidden entity from AST file has no owning module");
1275
Richard Smith87bb5692015-06-09 00:35:49 +00001276 if (!getLangOpts().ModulesLocalVisibility) {
1277 // If we're not tracking visibility locally, the only way a declaration
1278 // can be hidden and local is if it's hidden because it's parent is (for
1279 // instance, maybe this is a lazily-declared special member of an imported
1280 // class).
1281 auto *Parent = cast<NamedDecl>(Entity->getDeclContext());
1282 assert(Parent->isHidden() && "unexpectedly hidden decl");
1283 return getOwningModule(Parent);
1284 }
1285
Richard Smith42413142015-05-15 20:05:43 +00001286 // It's local and hidden; grab or compute its owning module.
1287 M = Entity->getLocalOwningModule();
1288 if (M)
1289 return M;
1290
1291 if (auto *Containing =
1292 PP.getModuleContainingLocation(Entity->getLocation())) {
1293 M = Containing;
1294 } else if (Entity->isInvalidDecl() || Entity->getLocation().isInvalid()) {
1295 // Don't bother tracking visibility for invalid declarations with broken
1296 // locations.
1297 cast<NamedDecl>(Entity)->setHidden(false);
1298 } else {
1299 // We need to assign a module to an entity that exists outside of any
1300 // module, so that we can hide it from modules that we textually enter.
1301 // Invent a fake module for all such entities.
1302 if (!CachedFakeTopLevelModule) {
1303 CachedFakeTopLevelModule =
1304 PP.getHeaderSearchInfo().getModuleMap().findOrCreateModule(
1305 "<top-level>", nullptr, false, false).first;
1306
1307 auto &SrcMgr = PP.getSourceManager();
1308 SourceLocation StartLoc =
1309 SrcMgr.getLocForStartOfFile(SrcMgr.getMainFileID());
1310 auto &TopLevel =
1311 VisibleModulesStack.empty() ? VisibleModules : VisibleModulesStack[0];
1312 TopLevel.setVisible(CachedFakeTopLevelModule, StartLoc);
1313 }
1314
1315 M = CachedFakeTopLevelModule;
1316 }
1317
1318 if (M)
1319 Entity->setLocalOwningModule(M);
1320 return M;
1321}
1322
Richard Smithd9ba2242015-05-07 03:54:19 +00001323void Sema::makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc) {
Richard Smith87bb5692015-06-09 00:35:49 +00001324 if (auto *M = PP.getModuleContainingLocation(Loc))
1325 Context.mergeDefinitionIntoModule(ND, M);
1326 else
1327 // We're not building a module; just make the definition visible.
1328 ND->setHidden(false);
Richard Smith63e09bf2015-06-17 20:39:41 +00001329
1330 // If ND is a template declaration, make the template parameters
1331 // visible too. They're not (necessarily) within a mergeable DeclContext.
1332 if (auto *TD = dyn_cast<TemplateDecl>(ND))
1333 for (auto *Param : *TD->getTemplateParameters())
1334 makeMergedDefinitionVisible(Param, Loc);
Richard Smithd9ba2242015-05-07 03:54:19 +00001335}
1336
Richard Smith0e5d7b82013-07-25 23:08:39 +00001337/// \brief Find the module in which the given declaration was defined.
Richard Smith42413142015-05-15 20:05:43 +00001338static Module *getDefiningModule(Sema &S, Decl *Entity) {
Richard Smith0e5d7b82013-07-25 23:08:39 +00001339 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1340 // If this function was instantiated from a template, the defining module is
1341 // the module containing the pattern.
1342 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1343 Entity = Pattern;
1344 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
Reid Klecknere7367d62014-10-14 20:28:40 +00001345 if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
1346 Entity = Pattern;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001347 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1348 if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo())
1349 Entity = getInstantiatedFrom(ED, MSInfo);
1350 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1351 // FIXME: Map from variable template specializations back to the template.
1352 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo())
1353 Entity = getInstantiatedFrom(VD, MSInfo);
1354 }
1355
1356 // Walk up to the containing context. That might also have been instantiated
1357 // from a template.
1358 DeclContext *Context = Entity->getDeclContext();
1359 if (Context->isFileContext())
Richard Smith42413142015-05-15 20:05:43 +00001360 return S.getOwningModule(Entity);
1361 return getDefiningModule(S, cast<Decl>(Context));
Richard Smith0e5d7b82013-07-25 23:08:39 +00001362}
1363
1364llvm::DenseSet<Module*> &Sema::getLookupModules() {
1365 unsigned N = ActiveTemplateInstantiations.size();
1366 for (unsigned I = ActiveTemplateInstantiationLookupModules.size();
1367 I != N; ++I) {
Richard Smith42413142015-05-15 20:05:43 +00001368 Module *M =
1369 getDefiningModule(*this, ActiveTemplateInstantiations[I].Entity);
Richard Smith0e5d7b82013-07-25 23:08:39 +00001370 if (M && !LookupModulesCache.insert(M).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00001371 M = nullptr;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001372 ActiveTemplateInstantiationLookupModules.push_back(M);
1373 }
1374 return LookupModulesCache;
1375}
1376
Richard Smith42413142015-05-15 20:05:43 +00001377bool Sema::hasVisibleMergedDefinition(NamedDecl *Def) {
1378 for (Module *Merged : Context.getModulesWithMergedDefinition(Def))
1379 if (isModuleVisible(Merged))
1380 return true;
1381 return false;
1382}
1383
Richard Smithe7bd6de2015-06-10 20:30:23 +00001384template<typename ParmDecl>
Richard Smith35c1df52015-06-17 20:16:32 +00001385static bool
1386hasVisibleDefaultArgument(Sema &S, const ParmDecl *D,
1387 llvm::SmallVectorImpl<Module *> *Modules) {
Richard Smithe7bd6de2015-06-10 20:30:23 +00001388 if (!D->hasDefaultArgument())
1389 return false;
1390
1391 while (D) {
1392 auto &DefaultArg = D->getDefaultArgStorage();
1393 if (!DefaultArg.isInherited() && S.isVisible(D))
1394 return true;
1395
Richard Smith63e09bf2015-06-17 20:39:41 +00001396 if (!DefaultArg.isInherited() && Modules) {
1397 auto *NonConstD = const_cast<ParmDecl*>(D);
1398 Modules->push_back(S.getOwningModule(NonConstD));
1399 const auto &Merged = S.Context.getModulesWithMergedDefinition(NonConstD);
1400 Modules->insert(Modules->end(), Merged.begin(), Merged.end());
1401 }
Richard Smith35c1df52015-06-17 20:16:32 +00001402
Richard Smithe7bd6de2015-06-10 20:30:23 +00001403 // If there was a previous default argument, maybe its parameter is visible.
1404 D = DefaultArg.getInheritedFrom();
1405 }
1406 return false;
1407}
1408
Richard Smith35c1df52015-06-17 20:16:32 +00001409bool Sema::hasVisibleDefaultArgument(const NamedDecl *D,
1410 llvm::SmallVectorImpl<Module *> *Modules) {
Richard Smithe7bd6de2015-06-10 20:30:23 +00001411 if (auto *P = dyn_cast<TemplateTypeParmDecl>(D))
Richard Smith35c1df52015-06-17 20:16:32 +00001412 return ::hasVisibleDefaultArgument(*this, P, Modules);
Richard Smithe7bd6de2015-06-10 20:30:23 +00001413 if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))
Richard Smith35c1df52015-06-17 20:16:32 +00001414 return ::hasVisibleDefaultArgument(*this, P, Modules);
1415 return ::hasVisibleDefaultArgument(*this, cast<TemplateTemplateParmDecl>(D),
1416 Modules);
Richard Smithe7bd6de2015-06-10 20:30:23 +00001417}
1418
Richard Smith0e5d7b82013-07-25 23:08:39 +00001419/// \brief Determine whether a declaration is visible to name lookup.
1420///
1421/// This routine determines whether the declaration D is visible in the current
1422/// lookup context, taking into account the current template instantiation
1423/// stack. During template instantiation, a declaration is visible if it is
1424/// visible from a module containing any entity on the template instantiation
1425/// path (by instantiating a template, you allow it to see the declarations that
1426/// your module can see, including those later on in your module).
1427bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001428 assert(D->isHidden() && "should not call this: not in slow case");
Richard Smith5196a172015-08-24 03:38:11 +00001429 Module *DeclModule = nullptr;
1430
1431 if (SemaRef.getLangOpts().ModulesLocalVisibility) {
1432 DeclModule = SemaRef.getOwningModule(D);
1433 if (!DeclModule) {
1434 // getOwningModule() may have decided the declaration should not be hidden.
1435 assert(!D->isHidden() && "hidden decl not from a module");
Richard Smith42413142015-05-15 20:05:43 +00001436 return true;
Richard Smith5196a172015-08-24 03:38:11 +00001437 }
1438
1439 // If the owning module is visible, and the decl is not module private,
1440 // then the decl is visible too. (Module private is ignored within the same
1441 // top-level module.)
1442 if ((!D->isFromASTFile() || !D->isModulePrivate()) &&
1443 (SemaRef.isModuleVisible(DeclModule) ||
1444 SemaRef.hasVisibleMergedDefinition(D)))
Richard Smith42413142015-05-15 20:05:43 +00001445 return true;
1446 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001447
Richard Smithbe3980b2015-03-27 00:41:57 +00001448 // If this declaration is not at namespace scope nor module-private,
1449 // then it is visible if its lexical parent has a visible definition.
1450 DeclContext *DC = D->getLexicalDeclContext();
1451 if (!D->isModulePrivate() &&
1452 DC && !DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) {
Richard Smithc7d48d12015-05-20 17:50:35 +00001453 // For a parameter, check whether our current template declaration's
1454 // lexical context is visible, not whether there's some other visible
1455 // definition of it, because parameters aren't "within" the definition.
1456 if ((D->isTemplateParameter() || isa<ParmVarDecl>(D))
1457 ? isVisible(SemaRef, cast<NamedDecl>(DC))
1458 : SemaRef.hasVisibleDefinition(cast<NamedDecl>(DC))) {
Richard Smith42413142015-05-15 20:05:43 +00001459 if (SemaRef.ActiveTemplateInstantiations.empty() &&
1460 // FIXME: Do something better in this case.
1461 !SemaRef.getLangOpts().ModulesLocalVisibility) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001462 // Cache the fact that this declaration is implicitly visible because
1463 // its parent has a visible definition.
1464 D->setHidden(false);
1465 }
1466 return true;
1467 }
1468 return false;
1469 }
1470
Richard Smith0e5d7b82013-07-25 23:08:39 +00001471 // Find the extra places where we need to look.
1472 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
1473 if (LookupModules.empty())
1474 return false;
1475
Richard Smith5196a172015-08-24 03:38:11 +00001476 if (!DeclModule) {
1477 DeclModule = SemaRef.getOwningModule(D);
1478 assert(DeclModule && "hidden decl not from a module");
1479 }
1480
Richard Smith0e5d7b82013-07-25 23:08:39 +00001481 // If our lookup set contains the decl's module, it's visible.
1482 if (LookupModules.count(DeclModule))
1483 return true;
1484
1485 // If the declaration isn't exported, it's not visible in any other module.
1486 if (D->isModulePrivate())
1487 return false;
1488
1489 // Check whether DeclModule is transitively exported to an import of
1490 // the lookup set.
1491 for (llvm::DenseSet<Module *>::iterator I = LookupModules.begin(),
1492 E = LookupModules.end();
1493 I != E; ++I)
1494 if ((*I)->isModuleVisible(DeclModule))
1495 return true;
1496 return false;
1497}
1498
Richard Smith42413142015-05-15 20:05:43 +00001499bool Sema::isVisibleSlow(const NamedDecl *D) {
1500 return LookupResult::isVisible(*this, const_cast<NamedDecl*>(D));
1501}
1502
Douglas Gregor4a814562011-12-14 16:03:29 +00001503/// \brief Retrieve the visible declaration corresponding to D, if any.
1504///
1505/// This routine determines whether the declaration D is visible in the current
1506/// module, with the current imports. If not, it checks whether any
1507/// redeclaration of D is visible, and if so, returns that declaration.
Richard Smith0e5d7b82013-07-25 23:08:39 +00001508///
Douglas Gregor4a814562011-12-14 16:03:29 +00001509/// \returns D, or a visible previous declaration of D, whichever is more recent
1510/// and visible. If no declaration of D is visible, returns null.
Richard Smithe156254d2013-08-20 20:35:18 +00001511static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
1512 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
Richard Smith0e5d7b82013-07-25 23:08:39 +00001513
Aaron Ballman86c93902014-03-06 23:45:36 +00001514 for (auto RD : D->redecls()) {
1515 if (auto ND = dyn_cast<NamedDecl>(RD)) {
Richard Smithe8292b12015-02-10 03:28:10 +00001516 // FIXME: This is wrong in the case where the previous declaration is not
1517 // visible in the same scope as D. This needs to be done much more
1518 // carefully.
Richard Smithe156254d2013-08-20 20:35:18 +00001519 if (LookupResult::isVisible(SemaRef, ND))
Douglas Gregor54079202012-01-06 22:05:37 +00001520 return ND;
1521 }
Douglas Gregor4a814562011-12-14 16:03:29 +00001522 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001523
Craig Topperc3ec1492014-05-26 06:22:03 +00001524 return nullptr;
Douglas Gregor4a814562011-12-14 16:03:29 +00001525}
1526
Richard Smithe156254d2013-08-20 20:35:18 +00001527NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +00001528 return findAcceptableDecl(getSema(), D);
Richard Smithe156254d2013-08-20 20:35:18 +00001529}
1530
Douglas Gregor34074322009-01-14 22:20:51 +00001531/// @brief Perform unqualified name lookup starting from a given
1532/// scope.
1533///
1534/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1535/// used to find names within the current scope. For example, 'x' in
1536/// @code
1537/// int x;
1538/// int f() {
1539/// return x; // unqualified name look finds 'x' in the global scope
1540/// }
1541/// @endcode
1542///
1543/// Different lookup criteria can find different names. For example, a
1544/// particular scope can have both a struct and a function of the same
1545/// name, and each can be found by certain lookup criteria. For more
1546/// information about lookup criteria, see the documentation for the
1547/// class LookupCriteria.
1548///
1549/// @param S The scope from which unqualified name lookup will
1550/// begin. If the lookup criteria permits, name lookup may also search
1551/// in the parent scopes.
1552///
James Dennett91738ff2012-06-22 10:32:46 +00001553/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1554/// look up and the lookup kind), and is updated with the results of lookup
1555/// including zero or more declarations and possibly additional information
1556/// used to diagnose ambiguities.
Douglas Gregor34074322009-01-14 22:20:51 +00001557///
James Dennett91738ff2012-06-22 10:32:46 +00001558/// @returns \c true if lookup succeeded and false otherwise.
John McCall27b18f82009-11-17 02:14:36 +00001559bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1560 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001561 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001562
John McCall27b18f82009-11-17 02:14:36 +00001563 LookupNameKind NameKind = R.getLookupKind();
1564
David Blaikiebbafb8a2012-03-11 07:00:24 +00001565 if (!getLangOpts().CPlusPlus) {
Douglas Gregor34074322009-01-14 22:20:51 +00001566 // Unqualified name lookup in C/Objective-C is purely lexical, so
1567 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001568 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001569 // Find the nearest non-transparent declaration scope.
1570 while (!(S->getFlags() & Scope::DeclScope) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001571 (S->getEntity() && S->getEntity()->isTransparentContext()))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001572 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001573 }
1574
Richard Smith541b38b2013-09-20 01:15:31 +00001575 // When performing a scope lookup, we want to find local extern decls.
1576 FindLocalExternScope FindLocals(R);
1577
Douglas Gregor34074322009-01-14 22:20:51 +00001578 // Scan up the scope chain looking for a decl that matches this
1579 // identifier that is in the appropriate namespace. This search
1580 // should not take long, as shadowing of names is uncommon, and
1581 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001582 bool LeftStartingScope = false;
1583
Douglas Gregored8f2882009-01-30 01:04:22 +00001584 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001585 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001586 I != IEnd; ++I)
Richard Smith0e5d7b82013-07-25 23:08:39 +00001587 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001588 if (NameKind == LookupRedeclarationWithLinkage) {
1589 // Determine whether this (or a previous) declaration is
1590 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001591 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001592 LeftStartingScope = true;
1593
1594 // If we found something outside of our starting scope that
1595 // does not have linkage, skip it.
Richard Smith1c34fb72013-08-13 18:18:50 +00001596 if (LeftStartingScope && !((*I)->hasLinkage())) {
1597 R.setShadowed();
Douglas Gregoreddf4332009-02-24 20:03:32 +00001598 continue;
Richard Smith1c34fb72013-08-13 18:18:50 +00001599 }
Douglas Gregoreddf4332009-02-24 20:03:32 +00001600 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001601 else if (NameKind == LookupObjCImplicitSelfParam &&
1602 !isa<ImplicitParamDecl>(*I))
1603 continue;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001604
Douglas Gregor4a814562011-12-14 16:03:29 +00001605 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001606
Douglas Gregorb59643b2012-01-03 23:26:26 +00001607 // Check whether there are any other declarations with the same name
1608 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001609 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001610 // Find the scope in which this declaration was declared (if it
1611 // actually exists in a Scope).
1612 while (S && !S->isDeclScope(D))
1613 S = S->getParent();
1614
1615 // If the scope containing the declaration is the translation unit,
1616 // then we'll need to perform our checks based on the matching
1617 // DeclContexts rather than matching scopes.
1618 if (S && isNamespaceOrTranslationUnitScope(S))
Craig Topperc3ec1492014-05-26 06:22:03 +00001619 S = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001620
1621 // Compute the DeclContext, if we need it.
Craig Topperc3ec1492014-05-26 06:22:03 +00001622 DeclContext *DC = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001623 if (!S)
1624 DC = (*I)->getDeclContext()->getRedeclContext();
1625
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001626 IdentifierResolver::iterator LastI = I;
1627 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001628 if (S) {
1629 // Match based on scope.
1630 if (!S->isDeclScope(*LastI))
1631 break;
1632 } else {
1633 // Match based on DeclContext.
1634 DeclContext *LastDC
1635 = (*LastI)->getDeclContext()->getRedeclContext();
1636 if (!LastDC->Equals(DC))
1637 break;
1638 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001639
1640 // If the declaration is in the right namespace and visible, add it.
1641 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1642 R.addDecl(LastD);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001643 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001644
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001645 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001646 }
Richard Smith541b38b2013-09-20 01:15:31 +00001647
John McCall9f3059a2009-10-09 21:13:30 +00001648 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001649 }
Douglas Gregor34074322009-01-14 22:20:51 +00001650 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001651 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001652 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001653 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001654 }
1655
1656 // If we didn't find a use of this identifier, and if the identifier
1657 // corresponds to a compiler builtin, create the decl object for the builtin
1658 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001659 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1660 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001661
Axel Naumann016538a2011-02-24 16:47:47 +00001662 // If we didn't find a use of this identifier, the ExternalSource
1663 // may be able to handle the situation.
1664 // Note: some lookup failures are expected!
1665 // See e.g. R.isForRedeclaration().
1666 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001667}
1668
John McCall6538c932009-10-10 05:48:19 +00001669/// @brief Perform qualified name lookup in the namespaces nominated by
1670/// using directives by the given context.
1671///
1672/// C++98 [namespace.qual]p2:
James Dennett51a8d8b2012-06-19 21:05:49 +00001673/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6538c932009-10-10 05:48:19 +00001674/// (where X is the global namespace), let S be the set of all
1675/// declarations of m in X and in the transitive closure of all
1676/// namespaces nominated by using-directives in X and its used
1677/// namespaces, except that using-directives are ignored in any
1678/// namespace, including X, directly containing one or more
1679/// declarations of m. No namespace is searched more than once in
1680/// the lookup of a name. If S is the empty set, the program is
1681/// ill-formed. Otherwise, if S has exactly one member, or if the
1682/// context of the reference is a using-declaration
1683/// (namespace.udecl), S is the required set of declarations of
1684/// m. Otherwise if the use of m is not one that allows a unique
1685/// declaration to be chosen from S, the program is ill-formed.
James Dennett51a8d8b2012-06-19 21:05:49 +00001686///
John McCall6538c932009-10-10 05:48:19 +00001687/// C++98 [namespace.qual]p5:
1688/// During the lookup of a qualified namespace member name, if the
1689/// lookup finds more than one declaration of the member, and if one
1690/// declaration introduces a class name or enumeration name and the
1691/// other declarations either introduce the same object, the same
1692/// enumerator or a set of functions, the non-type name hides the
1693/// class or enumeration name if and only if the declarations are
1694/// from the same namespace; otherwise (the declarations are from
1695/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001696static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001697 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001698 assert(StartDC->isFileContext() && "start context is not a file context");
1699
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001700 DeclContext::udir_range UsingDirectives = StartDC->using_directives();
1701 if (UsingDirectives.begin() == UsingDirectives.end()) return false;
John McCall6538c932009-10-10 05:48:19 +00001702
1703 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001704 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001705 Visited.insert(StartDC);
1706
1707 // We have not yet looked into these namespaces, much less added
1708 // their "using-children" to the queue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001709 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001710
1711 // We have already looked into the initial namespace; seed the queue
1712 // with its using-children.
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001713 for (auto *I : UsingDirectives) {
1714 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +00001715 if (Visited.insert(ND).second)
John McCall6538c932009-10-10 05:48:19 +00001716 Queue.push_back(ND);
1717 }
1718
1719 // The easiest way to implement the restriction in [namespace.qual]p5
1720 // is to check whether any of the individual results found a tag
1721 // and, if so, to declare an ambiguity if the final result is not
1722 // a tag.
1723 bool FoundTag = false;
1724 bool FoundNonTag = false;
1725
John McCall5cebab12009-11-18 07:57:50 +00001726 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001727
1728 bool Found = false;
1729 while (!Queue.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001730 NamespaceDecl *ND = Queue.pop_back_val();
John McCall6538c932009-10-10 05:48:19 +00001731
1732 // We go through some convolutions here to avoid copying results
1733 // between LookupResults.
1734 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001735 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001736 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001737
1738 if (FoundDirect) {
1739 // First do any local hiding.
1740 DirectR.resolveKind();
1741
1742 // If the local result is a tag, remember that.
1743 if (DirectR.isSingleTagDecl())
1744 FoundTag = true;
1745 else
1746 FoundNonTag = true;
1747
1748 // Append the local results to the total results if necessary.
1749 if (UseLocal) {
1750 R.addAllDecls(LocalR);
1751 LocalR.clear();
1752 }
1753 }
1754
1755 // If we find names in this namespace, ignore its using directives.
1756 if (FoundDirect) {
1757 Found = true;
1758 continue;
1759 }
1760
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001761 for (auto I : ND->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00001762 NamespaceDecl *Nom = I->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +00001763 if (Visited.insert(Nom).second)
John McCall6538c932009-10-10 05:48:19 +00001764 Queue.push_back(Nom);
1765 }
1766 }
1767
1768 if (Found) {
1769 if (FoundTag && FoundNonTag)
1770 R.setAmbiguousQualifiedTagHiding();
1771 else
1772 R.resolveKind();
1773 }
1774
1775 return Found;
1776}
1777
Douglas Gregor39982192010-08-15 06:18:01 +00001778/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001779static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00001780 CXXBasePath &Path, DeclarationName Name) {
Douglas Gregor39982192010-08-15 06:18:01 +00001781 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001782
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00001783 Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00001784 return !Path.Decls.empty();
Douglas Gregor39982192010-08-15 06:18:01 +00001785}
1786
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001787/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001788/// static members, nested types, and enumerators.
1789template<typename InputIterator>
1790static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1791 Decl *D = (*First)->getUnderlyingDecl();
1792 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1793 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001794
Douglas Gregorc0d24902010-10-22 22:08:47 +00001795 if (isa<CXXMethodDecl>(D)) {
1796 // Determine whether all of the methods are static.
1797 bool AllMethodsAreStatic = true;
1798 for(; First != Last; ++First) {
1799 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001800
Douglas Gregorc0d24902010-10-22 22:08:47 +00001801 if (!isa<CXXMethodDecl>(D)) {
1802 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1803 break;
1804 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001805
Douglas Gregorc0d24902010-10-22 22:08:47 +00001806 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1807 AllMethodsAreStatic = false;
1808 break;
1809 }
1810 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001811
Douglas Gregorc0d24902010-10-22 22:08:47 +00001812 if (AllMethodsAreStatic)
1813 return true;
1814 }
1815
1816 return false;
1817}
1818
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001819/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001820///
1821/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1822/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001823/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001824///
1825/// Different lookup criteria can find different names. For example, a
1826/// particular scope can have both a struct and a function of the same
1827/// name, and each can be found by certain lookup criteria. For more
1828/// information about lookup criteria, see the documentation for the
1829/// class LookupCriteria.
1830///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001831/// \param R captures both the lookup criteria and any lookup results found.
1832///
1833/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001834/// search. If the lookup criteria permits, name lookup may also search
1835/// in the parent contexts or (for C++ classes) base classes.
1836///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001837/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001838/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001839///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001840/// \returns true if lookup succeeded, false if it failed.
1841bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1842 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001843 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001844
John McCall27b18f82009-11-17 02:14:36 +00001845 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001846 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001847
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001848 // Make sure that the declaration context is complete.
1849 assert((!isa<TagDecl>(LookupCtx) ||
1850 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00001851 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith7d137e32012-03-23 03:33:32 +00001852 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001853 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001854
Douglas Gregor34074322009-01-14 22:20:51 +00001855 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001856 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001857 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001858 if (isa<CXXRecordDecl>(LookupCtx))
1859 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001860 return true;
1861 }
Douglas Gregor34074322009-01-14 22:20:51 +00001862
John McCall6538c932009-10-10 05:48:19 +00001863 // Don't descend into implied contexts for redeclarations.
1864 // C++98 [namespace.qual]p6:
1865 // In a declaration for a namespace member in which the
1866 // declarator-id is a qualified-id, given that the qualified-id
1867 // for the namespace member has the form
1868 // nested-name-specifier unqualified-id
1869 // the unqualified-id shall name a member of the namespace
1870 // designated by the nested-name-specifier.
1871 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001872 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001873 return false;
1874
John McCall27b18f82009-11-17 02:14:36 +00001875 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001876 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001877 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001878
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001879 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001880 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001881 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001882 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001883 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001884
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001885 // If we're performing qualified name lookup into a dependent class,
1886 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001887 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001888 // template instantiation time (at which point all bases will be available)
1889 // or we have to fail.
1890 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1891 LookupRec->hasAnyDependentBases()) {
1892 R.setNotFoundInCurrentInstantiation();
1893 return false;
1894 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001895
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001896 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001897 CXXBasePaths Paths;
1898 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001899
1900 // Look for this member in our base classes
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00001901 bool (*BaseCallback)(const CXXBaseSpecifier *Specifier, CXXBasePath &Path,
1902 DeclarationName Name) = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00001903 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001904 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001905 case LookupOrdinaryName:
1906 case LookupMemberName:
1907 case LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +00001908 case LookupLocalFriendName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001909 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1910 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001911
Douglas Gregor36d1b142009-10-06 17:59:45 +00001912 case LookupTagName:
1913 BaseCallback = &CXXRecordDecl::FindTagMember;
1914 break;
John McCall84d87672009-12-10 09:41:52 +00001915
Douglas Gregor39982192010-08-15 06:18:01 +00001916 case LookupAnyName:
1917 BaseCallback = &LookupAnyMember;
1918 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001919
John McCall84d87672009-12-10 09:41:52 +00001920 case LookupUsingDeclName:
1921 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001922
Douglas Gregor36d1b142009-10-06 17:59:45 +00001923 case LookupOperatorName:
1924 case LookupNamespaceName:
1925 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001926 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001927 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001928 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001929
Douglas Gregor36d1b142009-10-06 17:59:45 +00001930 case LookupNestedNameSpecifierName:
1931 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1932 break;
1933 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001934
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00001935 DeclarationName Name = R.getLookupName();
1936 if (!LookupRec->lookupInBases(
1937 [=](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
1938 return BaseCallback(Specifier, Path, Name);
1939 },
1940 Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001941 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001942
John McCall553c0792010-01-23 00:46:32 +00001943 R.setNamingClass(LookupRec);
1944
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001945 // C++ [class.member.lookup]p2:
1946 // [...] If the resulting set of declarations are not all from
1947 // sub-objects of the same type, or the set has a nonstatic member
1948 // and includes members from distinct sub-objects, there is an
1949 // ambiguity and the program is ill-formed. Otherwise that set is
1950 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001951 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001952 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001953 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001954
Douglas Gregor36d1b142009-10-06 17:59:45 +00001955 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001956 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001957 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001958
John McCall401982f2010-01-20 21:53:11 +00001959 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1960 // across all paths.
1961 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001962
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001963 // Determine whether we're looking at a distinct sub-object or not.
1964 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001965 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001966 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1967 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001968 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001969 }
1970
Douglas Gregorc0d24902010-10-22 22:08:47 +00001971 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001972 != Context.getCanonicalType(PathElement.Base->getType())) {
1973 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001974 // different types. If the declaration sets aren't the same, this
Nikola Smiljanic1c125682014-07-09 05:42:35 +00001975 // lookup is ambiguous.
David Blaikieff7d47a2012-12-19 00:45:41 +00001976 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00001977 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikieff7d47a2012-12-19 00:45:41 +00001978 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
1979 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001980
David Blaikieff7d47a2012-12-19 00:45:41 +00001981 while (FirstD != FirstPath->Decls.end() &&
1982 CurrentD != Path->Decls.end()) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00001983 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1984 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1985 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001986
Douglas Gregorc0d24902010-10-22 22:08:47 +00001987 ++FirstD;
1988 ++CurrentD;
1989 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001990
David Blaikieff7d47a2012-12-19 00:45:41 +00001991 if (FirstD == FirstPath->Decls.end() &&
1992 CurrentD == Path->Decls.end())
Douglas Gregorc0d24902010-10-22 22:08:47 +00001993 continue;
1994 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001995
John McCall9f3059a2009-10-09 21:13:30 +00001996 R.setAmbiguousBaseSubobjectTypes(Paths);
1997 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001998 }
1999
Douglas Gregorc0d24902010-10-22 22:08:47 +00002000 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002001 // We have a different subobject of the same type.
2002
2003 // C++ [class.member.lookup]p5:
2004 // A static member, a nested type or an enumerator defined in
2005 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00002006 // has more than one base class subobject of type T.
David Blaikieff7d47a2012-12-19 00:45:41 +00002007 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002008 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002009
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002010 // We have found a nonstatic member name in multiple, distinct
2011 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00002012 R.setAmbiguousBaseSubobjects(Paths);
2013 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002014 }
2015 }
2016
2017 // Lookup in a base class succeeded; return these results.
2018
Aaron Ballman1e606f42014-07-15 22:03:49 +00002019 for (auto *D : Paths.front().Decls) {
John McCall553c0792010-01-23 00:46:32 +00002020 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
2021 D->getAccess());
2022 R.addDecl(D, AS);
2023 }
John McCall9f3059a2009-10-09 21:13:30 +00002024 R.resolveKind();
2025 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00002026}
2027
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00002028/// \brief Performs qualified name lookup or special type of lookup for
2029/// "__super::" scope specifier.
2030///
2031/// This routine is a convenience overload meant to be called from contexts
2032/// that need to perform a qualified name lookup with an optional C++ scope
2033/// specifier that might require special kind of lookup.
2034///
2035/// \param R captures both the lookup criteria and any lookup results found.
2036///
2037/// \param LookupCtx The context in which qualified name lookup will
2038/// search.
2039///
2040/// \param SS An optional C++ scope-specifier.
2041///
2042/// \returns true if lookup succeeded, false if it failed.
2043bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2044 CXXScopeSpec &SS) {
2045 auto *NNS = SS.getScopeRep();
2046 if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
2047 return LookupInSuper(R, NNS->getAsRecordDecl());
2048 else
2049
2050 return LookupQualifiedName(R, LookupCtx);
2051}
2052
Douglas Gregor34074322009-01-14 22:20:51 +00002053/// @brief Performs name lookup for a name that was parsed in the
2054/// source code, and may contain a C++ scope specifier.
2055///
2056/// This routine is a convenience routine meant to be called from
2057/// contexts that receive a name and an optional C++ scope specifier
2058/// (e.g., "N::M::x"). It will then perform either qualified or
2059/// unqualified name lookup (with LookupQualifiedName or LookupName,
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002060/// respectively) on the given name and return those results. It will
2061/// perform a special type of lookup for "__super::" scope specifier.
Douglas Gregor34074322009-01-14 22:20:51 +00002062///
2063/// @param S The scope from which unqualified name lookup will
2064/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00002065///
Douglas Gregore861bac2009-08-25 22:51:20 +00002066/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00002067///
Douglas Gregore861bac2009-08-25 22:51:20 +00002068/// @param EnteringContext Indicates whether we are going to enter the
2069/// context of the scope-specifier SS (if present).
2070///
John McCall9f3059a2009-10-09 21:13:30 +00002071/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002072bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00002073 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00002074 if (SS && SS->isInvalid()) {
2075 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002076 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00002077 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00002078 }
Mike Stump11289f42009-09-09 15:08:12 +00002079
Douglas Gregore861bac2009-08-25 22:51:20 +00002080 if (SS && SS->isSet()) {
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002081 NestedNameSpecifier *NNS = SS->getScopeRep();
2082 if (NNS->getKind() == NestedNameSpecifier::Super)
2083 return LookupInSuper(R, NNS->getAsRecordDecl());
2084
Douglas Gregore861bac2009-08-25 22:51:20 +00002085 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00002086 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00002087 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00002088 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00002089 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002090
John McCall27b18f82009-11-17 02:14:36 +00002091 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00002092 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00002093 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002094
Douglas Gregore861bac2009-08-25 22:51:20 +00002095 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00002096 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00002097 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00002098 R.setNotFoundInCurrentInstantiation();
2099 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00002100 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00002101 }
2102
Mike Stump11289f42009-09-09 15:08:12 +00002103 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00002104 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00002105}
2106
Nikola Smiljanic67860242014-09-26 00:28:20 +00002107/// \brief Perform qualified name lookup into all base classes of the given
2108/// class.
2109///
2110/// \param R captures both the lookup criteria and any lookup results found.
2111///
2112/// \param Class The context in which qualified name lookup will
2113/// search. Name lookup will search in all base classes merging the results.
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002114///
2115/// @returns True if any decls were found (but possibly ambiguous)
2116bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
John McCallf4a1b772015-09-09 23:04:17 +00002117 // The access-control rules we use here are essentially the rules for
2118 // doing a lookup in Class that just magically skipped the direct
2119 // members of Class itself. That is, the naming class is Class, and the
2120 // access includes the access of the base.
Nikola Smiljanic67860242014-09-26 00:28:20 +00002121 for (const auto &BaseSpec : Class->bases()) {
2122 CXXRecordDecl *RD = cast<CXXRecordDecl>(
2123 BaseSpec.getType()->castAs<RecordType>()->getDecl());
2124 LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
2125 Result.setBaseObjectType(Context.getRecordType(Class));
2126 LookupQualifiedName(Result, RD);
John McCallf4a1b772015-09-09 23:04:17 +00002127
2128 // Copy the lookup results into the target, merging the base's access into
2129 // the path access.
2130 for (auto I = Result.begin(), E = Result.end(); I != E; ++I) {
2131 R.addDecl(I.getDecl(),
2132 CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(),
2133 I.getAccess()));
2134 }
2135
2136 Result.suppressDiagnostics();
Nikola Smiljanic67860242014-09-26 00:28:20 +00002137 }
2138
2139 R.resolveKind();
John McCallf4a1b772015-09-09 23:04:17 +00002140 R.setNamingClass(Class);
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002141
2142 return !R.empty();
Nikola Smiljanic67860242014-09-26 00:28:20 +00002143}
Douglas Gregor889ceb72009-02-03 19:21:40 +00002144
James Dennett41725122012-06-22 10:16:05 +00002145/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002146/// from name lookup.
2147///
James Dennett41725122012-06-22 10:16:05 +00002148/// \param Result The result of the ambiguous lookup to be diagnosed.
Serge Pavlov99292092013-08-29 07:23:24 +00002149void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002150 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
2151
John McCall27b18f82009-11-17 02:14:36 +00002152 DeclarationName Name = Result.getLookupName();
2153 SourceLocation NameLoc = Result.getNameLoc();
2154 SourceRange LookupRange = Result.getContextRange();
2155
John McCall6538c932009-10-10 05:48:19 +00002156 switch (Result.getAmbiguityKind()) {
2157 case LookupResult::AmbiguousBaseSubobjects: {
2158 CXXBasePaths *Paths = Result.getBasePaths();
2159 QualType SubobjectType = Paths->front().back().Base->getType();
2160 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
2161 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
2162 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002163
David Blaikieff7d47a2012-12-19 00:45:41 +00002164 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6538c932009-10-10 05:48:19 +00002165 while (isa<CXXMethodDecl>(*Found) &&
2166 cast<CXXMethodDecl>(*Found)->isStatic())
2167 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002168
John McCall6538c932009-10-10 05:48:19 +00002169 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
Serge Pavlov99292092013-08-29 07:23:24 +00002170 break;
John McCall6538c932009-10-10 05:48:19 +00002171 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00002172
John McCall6538c932009-10-10 05:48:19 +00002173 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00002174 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
2175 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002176
John McCall6538c932009-10-10 05:48:19 +00002177 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002178 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00002179 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
2180 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002181 Path != PathEnd; ++Path) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002182 Decl *D = Path->Decls.front();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002183 if (DeclsPrinted.insert(D).second)
2184 Diag(D->getLocation(), diag::note_ambiguous_member_found);
2185 }
Serge Pavlov99292092013-08-29 07:23:24 +00002186 break;
Douglas Gregor1c846b02009-01-16 00:38:09 +00002187 }
2188
John McCall6538c932009-10-10 05:48:19 +00002189 case LookupResult::AmbiguousTagHiding: {
2190 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00002191
John McCall6538c932009-10-10 05:48:19 +00002192 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
2193
Aaron Ballman1e606f42014-07-15 22:03:49 +00002194 for (auto *D : Result)
2195 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
John McCall6538c932009-10-10 05:48:19 +00002196 TagDecls.insert(TD);
2197 Diag(TD->getLocation(), diag::note_hidden_tag);
2198 }
2199
Aaron Ballman1e606f42014-07-15 22:03:49 +00002200 for (auto *D : Result)
2201 if (!isa<TagDecl>(D))
2202 Diag(D->getLocation(), diag::note_hiding_object);
John McCall6538c932009-10-10 05:48:19 +00002203
2204 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00002205 LookupResult::Filter F = Result.makeFilter();
2206 while (F.hasNext()) {
2207 if (TagDecls.count(F.next()))
2208 F.erase();
2209 }
2210 F.done();
Serge Pavlov99292092013-08-29 07:23:24 +00002211 break;
John McCall6538c932009-10-10 05:48:19 +00002212 }
2213
2214 case LookupResult::AmbiguousReference: {
2215 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002216
Aaron Ballman1e606f42014-07-15 22:03:49 +00002217 for (auto *D : Result)
2218 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
Serge Pavlov99292092013-08-29 07:23:24 +00002219 break;
John McCall6538c932009-10-10 05:48:19 +00002220 }
Serge Pavlov99292092013-08-29 07:23:24 +00002221 }
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002222}
Douglas Gregore254f902009-02-04 00:32:51 +00002223
John McCallf24d7bb2010-05-28 18:45:08 +00002224namespace {
2225 struct AssociatedLookup {
John McCall7d8b0412012-08-24 20:38:34 +00002226 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallf24d7bb2010-05-28 18:45:08 +00002227 Sema::AssociatedNamespaceSet &Namespaces,
2228 Sema::AssociatedClassSet &Classes)
John McCall7d8b0412012-08-24 20:38:34 +00002229 : S(S), Namespaces(Namespaces), Classes(Classes),
2230 InstantiationLoc(InstantiationLoc) {
John McCallf24d7bb2010-05-28 18:45:08 +00002231 }
2232
2233 Sema &S;
2234 Sema::AssociatedNamespaceSet &Namespaces;
2235 Sema::AssociatedClassSet &Classes;
John McCall7d8b0412012-08-24 20:38:34 +00002236 SourceLocation InstantiationLoc;
John McCallf24d7bb2010-05-28 18:45:08 +00002237 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002238} // end anonymous namespace
John McCallf24d7bb2010-05-28 18:45:08 +00002239
Mike Stump11289f42009-09-09 15:08:12 +00002240static void
John McCallf24d7bb2010-05-28 18:45:08 +00002241addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00002242
Douglas Gregor8b895222010-04-30 07:08:38 +00002243static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
2244 DeclContext *Ctx) {
2245 // Add the associated namespace for this class.
2246
2247 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
2248 // be a locally scoped record.
2249
Sebastian Redlbd595762010-08-31 20:53:31 +00002250 // We skip out of inline namespaces. The innermost non-inline namespace
2251 // contains all names of all its nested inline namespaces anyway, so we can
2252 // replace the entire inline namespace tree with its root.
2253 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
2254 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00002255 Ctx = Ctx->getParent();
2256
John McCallc7e8e792009-08-07 22:18:02 +00002257 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00002258 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00002259}
Douglas Gregor197e5f72009-07-08 07:51:57 +00002260
Mike Stump11289f42009-09-09 15:08:12 +00002261// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00002262// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00002263static void
John McCallf24d7bb2010-05-28 18:45:08 +00002264addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2265 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002266 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00002267 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00002268 switch (Arg.getKind()) {
2269 case TemplateArgument::Null:
2270 break;
Mike Stump11289f42009-09-09 15:08:12 +00002271
Douglas Gregor197e5f72009-07-08 07:51:57 +00002272 case TemplateArgument::Type:
2273 // [...] the namespaces and classes associated with the types of the
2274 // template arguments provided for template type parameters (excluding
2275 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00002276 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00002277 break;
Mike Stump11289f42009-09-09 15:08:12 +00002278
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002279 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002280 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00002281 // [...] the namespaces in which any template template arguments are
2282 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00002283 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002284 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00002285 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002286 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002287 DeclContext *Ctx = ClassTemplate->getDeclContext();
2288 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002289 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002290 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002291 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002292 }
2293 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002294 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002295
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002296 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00002297 case TemplateArgument::Integral:
2298 case TemplateArgument::Expression:
Eli Friedmanb826a002012-09-26 02:36:12 +00002299 case TemplateArgument::NullPtr:
Mike Stump11289f42009-09-09 15:08:12 +00002300 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00002301 // associated namespaces. ]
2302 break;
Mike Stump11289f42009-09-09 15:08:12 +00002303
Douglas Gregor197e5f72009-07-08 07:51:57 +00002304 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00002305 for (const auto &P : Arg.pack_elements())
2306 addAssociatedClassesAndNamespaces(Result, P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002307 break;
2308 }
2309}
2310
Douglas Gregore254f902009-02-04 00:32:51 +00002311// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00002312// argument-dependent lookup with an argument of class type
2313// (C++ [basic.lookup.koenig]p2).
2314static void
John McCallf24d7bb2010-05-28 18:45:08 +00002315addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2316 CXXRecordDecl *Class) {
2317
2318 // Just silently ignore anything whose name is __va_list_tag.
2319 if (Class->getDeclName() == Result.S.VAListTagName)
2320 return;
2321
Douglas Gregore254f902009-02-04 00:32:51 +00002322 // C++ [basic.lookup.koenig]p2:
2323 // [...]
2324 // -- If T is a class type (including unions), its associated
2325 // classes are: the class itself; the class of which it is a
2326 // member, if any; and its direct and indirect base
2327 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00002328 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00002329
2330 // Add the class of which it is a member, if any.
2331 DeclContext *Ctx = Class->getDeclContext();
2332 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002333 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002334 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002335 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002336
Douglas Gregore254f902009-02-04 00:32:51 +00002337 // Add the class itself. If we've already seen this class, we don't
2338 // need to visit base classes.
Richard Smith594461f2014-03-14 22:07:27 +00002339 //
2340 // FIXME: That's not correct, we may have added this class only because it
2341 // was the enclosing class of another class, and in that case we won't have
2342 // added its base classes yet.
David Blaikie82e95a32014-11-19 07:49:47 +00002343 if (!Result.Classes.insert(Class).second)
Douglas Gregore254f902009-02-04 00:32:51 +00002344 return;
2345
Mike Stump11289f42009-09-09 15:08:12 +00002346 // -- If T is a template-id, its associated namespaces and classes are
2347 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002348 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00002349 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00002350 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00002351 // namespaces in which any template template arguments are defined; and
2352 // the classes in which any member templates used as template template
2353 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00002354 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00002355 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00002356 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2357 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2358 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002359 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002360 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002361 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002362
Douglas Gregor197e5f72009-07-08 07:51:57 +00002363 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2364 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00002365 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002366 }
Mike Stump11289f42009-09-09 15:08:12 +00002367
John McCall67da35c2010-02-04 22:26:26 +00002368 // Only recurse into base classes for complete types.
Richard Smith594461f2014-03-14 22:07:27 +00002369 if (!Class->hasDefinition())
2370 return;
John McCall67da35c2010-02-04 22:26:26 +00002371
Douglas Gregore254f902009-02-04 00:32:51 +00002372 // Add direct and indirect base classes along with their associated
2373 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002374 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00002375 Bases.push_back(Class);
2376 while (!Bases.empty()) {
2377 // Pop this class off the stack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002378 Class = Bases.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002379
2380 // Visit the base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +00002381 for (const auto &Base : Class->bases()) {
2382 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00002383 // In dependent contexts, we do ADL twice, and the first time around,
2384 // the base type might be a dependent TemplateSpecializationType, or a
2385 // TemplateTypeParmType. If that happens, simply ignore it.
2386 // FIXME: If we want to support export, we probably need to add the
2387 // namespace of the template in a TemplateSpecializationType, or even
2388 // the classes and namespaces of known non-dependent arguments.
2389 if (!BaseType)
2390 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002391 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
David Blaikie82e95a32014-11-19 07:49:47 +00002392 if (Result.Classes.insert(BaseDecl).second) {
Douglas Gregore254f902009-02-04 00:32:51 +00002393 // Find the associated namespace for this base class.
2394 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00002395 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00002396
2397 // Make sure we visit the bases of this base class.
2398 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2399 Bases.push_back(BaseDecl);
2400 }
2401 }
2402 }
2403}
2404
2405// \brief Add the associated classes and namespaces for
2406// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00002407// (C++ [basic.lookup.koenig]p2).
2408static void
John McCallf24d7bb2010-05-28 18:45:08 +00002409addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00002410 // C++ [basic.lookup.koenig]p2:
2411 //
2412 // For each argument type T in the function call, there is a set
2413 // of zero or more associated namespaces and a set of zero or more
2414 // associated classes to be considered. The sets of namespaces and
2415 // classes is determined entirely by the types of the function
2416 // arguments (and the namespace of any template template
2417 // argument). Typedef names and using-declarations used to specify
2418 // the types do not contribute to this set. The sets of namespaces
2419 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00002420
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002421 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00002422 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2423
Douglas Gregore254f902009-02-04 00:32:51 +00002424 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00002425 switch (T->getTypeClass()) {
2426
2427#define TYPE(Class, Base)
2428#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2429#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2430#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2431#define ABSTRACT_TYPE(Class, Base)
2432#include "clang/AST/TypeNodes.def"
2433 // T is canonical. We can also ignore dependent types because
2434 // we don't need to do ADL at the definition point, but if we
2435 // wanted to implement template export (or if we find some other
2436 // use for associated classes and namespaces...) this would be
2437 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00002438 break;
Douglas Gregore254f902009-02-04 00:32:51 +00002439
John McCall0af3d3b2010-05-28 06:08:54 +00002440 // -- If T is a pointer to U or an array of U, its associated
2441 // namespaces and classes are those associated with U.
2442 case Type::Pointer:
2443 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2444 continue;
2445 case Type::ConstantArray:
2446 case Type::IncompleteArray:
2447 case Type::VariableArray:
2448 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2449 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002450
John McCall0af3d3b2010-05-28 06:08:54 +00002451 // -- If T is a fundamental type, its associated sets of
2452 // namespaces and classes are both empty.
2453 case Type::Builtin:
2454 break;
2455
2456 // -- If T is a class type (including unions), its associated
2457 // classes are: the class itself; the class of which it is a
2458 // member, if any; and its direct and indirect base
2459 // classes. Its associated namespaces are the namespaces in
2460 // which its associated classes are defined.
2461 case Type::Record: {
Richard Smith594461f2014-03-14 22:07:27 +00002462 Result.S.RequireCompleteType(Result.InstantiationLoc, QualType(T, 0),
2463 /*no diagnostic*/ 0);
John McCall0af3d3b2010-05-28 06:08:54 +00002464 CXXRecordDecl *Class
2465 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002466 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00002467 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00002468 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00002469
John McCall0af3d3b2010-05-28 06:08:54 +00002470 // -- If T is an enumeration type, its associated namespace is
2471 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002472 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00002473 // it has no associated class.
2474 case Type::Enum: {
2475 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002476
John McCall0af3d3b2010-05-28 06:08:54 +00002477 DeclContext *Ctx = Enum->getDeclContext();
2478 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002479 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002480
John McCall0af3d3b2010-05-28 06:08:54 +00002481 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002482 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00002483
John McCall0af3d3b2010-05-28 06:08:54 +00002484 break;
2485 }
2486
2487 // -- If T is a function type, its associated namespaces and
2488 // classes are those associated with the function parameter
2489 // types and those associated with the return type.
2490 case Type::FunctionProto: {
2491 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002492 for (const auto &Arg : Proto->param_types())
2493 Queue.push_back(Arg.getTypePtr());
John McCall0af3d3b2010-05-28 06:08:54 +00002494 // fallthrough
2495 }
2496 case Type::FunctionNoProto: {
2497 const FunctionType *FnType = cast<FunctionType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00002498 T = FnType->getReturnType().getTypePtr();
John McCall0af3d3b2010-05-28 06:08:54 +00002499 continue;
2500 }
2501
2502 // -- If T is a pointer to a member function of a class X, its
2503 // associated namespaces and classes are those associated
2504 // with the function parameter types and return type,
2505 // together with those associated with X.
2506 //
2507 // -- If T is a pointer to a data member of class X, its
2508 // associated namespaces and classes are those associated
2509 // with the member type together with those associated with
2510 // X.
2511 case Type::MemberPointer: {
2512 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2513
2514 // Queue up the class type into which this points.
2515 Queue.push_back(MemberPtr->getClass());
2516
2517 // And directly continue with the pointee type.
2518 T = MemberPtr->getPointeeType().getTypePtr();
2519 continue;
2520 }
2521
2522 // As an extension, treat this like a normal pointer.
2523 case Type::BlockPointer:
2524 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2525 continue;
2526
2527 // References aren't covered by the standard, but that's such an
2528 // obvious defect that we cover them anyway.
2529 case Type::LValueReference:
2530 case Type::RValueReference:
2531 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2532 continue;
2533
2534 // These are fundamental types.
2535 case Type::Vector:
2536 case Type::ExtVector:
2537 case Type::Complex:
2538 break;
2539
Richard Smith27d807c2013-04-30 13:56:41 +00002540 // Non-deduced auto types only get here for error cases.
2541 case Type::Auto:
2542 break;
2543
Douglas Gregor8e936662011-04-12 01:02:45 +00002544 // If T is an Objective-C object or interface type, or a pointer to an
2545 // object or interface type, the associated namespace is the global
2546 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002547 case Type::ObjCObject:
2548 case Type::ObjCInterface:
2549 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002550 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002551 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002552
2553 // Atomic types are just wrappers; use the associations of the
2554 // contained type.
2555 case Type::Atomic:
2556 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2557 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002558 }
2559
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002560 if (Queue.empty())
2561 break;
2562 T = Queue.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002563 }
Douglas Gregore254f902009-02-04 00:32:51 +00002564}
2565
2566/// \brief Find the associated classes and namespaces for
2567/// argument-dependent lookup for a call with the given set of
2568/// arguments.
2569///
2570/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002571/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002572/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00002573void Sema::FindAssociatedClassesAndNamespaces(
2574 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2575 AssociatedNamespaceSet &AssociatedNamespaces,
2576 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002577 AssociatedNamespaces.clear();
2578 AssociatedClasses.clear();
2579
John McCall7d8b0412012-08-24 20:38:34 +00002580 AssociatedLookup Result(*this, InstantiationLoc,
2581 AssociatedNamespaces, AssociatedClasses);
John McCallf24d7bb2010-05-28 18:45:08 +00002582
Douglas Gregore254f902009-02-04 00:32:51 +00002583 // C++ [basic.lookup.koenig]p2:
2584 // For each argument type T in the function call, there is a set
2585 // of zero or more associated namespaces and a set of zero or more
2586 // associated classes to be considered. The sets of namespaces and
2587 // classes is determined entirely by the types of the function
2588 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002589 // argument).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002590 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregore254f902009-02-04 00:32:51 +00002591 Expr *Arg = Args[ArgIdx];
2592
2593 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002594 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002595 continue;
2596 }
2597
2598 // [...] In addition, if the argument is the name or address of a
2599 // set of overloaded functions and/or function templates, its
2600 // associated classes and namespaces are the union of those
2601 // associated with each of the members of the set: the namespace
2602 // in which the function or function template is defined and the
2603 // classes and namespaces associated with its (non-dependent)
2604 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002605 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002606 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002607 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002608 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002609
John McCallf24d7bb2010-05-28 18:45:08 +00002610 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2611 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002612
Aaron Ballman1e606f42014-07-15 22:03:49 +00002613 for (const auto *D : ULE->decls()) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002614 // Look through any using declarations to find the underlying function.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002615 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
Douglas Gregore254f902009-02-04 00:32:51 +00002616
2617 // Add the classes and namespaces associated with the parameter
2618 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002619 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002620 }
2621 }
2622}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002623
John McCall5cebab12009-11-18 07:57:50 +00002624NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002625 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002626 LookupNameKind NameKind,
2627 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002628 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002629 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002630 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002631}
2632
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002633/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002634ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002635 SourceLocation IdLoc,
2636 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002637 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002638 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002639 return cast_or_null<ObjCProtocolDecl>(D);
2640}
2641
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002642void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002643 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002644 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002645 // C++ [over.match.oper]p3:
2646 // -- The set of non-member candidates is the result of the
2647 // unqualified lookup of operator@ in the context of the
2648 // expression according to the usual rules for name lookup in
2649 // unqualified function calls (3.4.2) except that all member
Richard Smith100b24a2014-04-17 01:52:14 +00002650 // functions are ignored.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002651 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002652 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2653 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002654
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002655 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
Richard Smith100b24a2014-04-17 01:52:14 +00002656 Functions.append(Operators.begin(), Operators.end());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002657}
2658
Alexis Hunt1da39282011-06-24 02:11:39 +00002659Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002660 CXXSpecialMember SM,
2661 bool ConstArg,
2662 bool VolatileArg,
2663 bool RValueThis,
2664 bool ConstThis,
2665 bool VolatileThis) {
Richard Smith7d125a12012-11-27 21:20:31 +00002666 assert(CanDeclareSpecialMemberFunction(RD) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002667 "doing special member lookup into record that isn't fully complete");
Richard Smith7d125a12012-11-27 21:20:31 +00002668 RD = RD->getDefinition();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002669 if (RValueThis || ConstThis || VolatileThis)
2670 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2671 "constructors and destructors always have unqualified lvalue this");
2672 if (ConstArg || VolatileArg)
2673 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2674 "parameter-less special members can't have qualified arguments");
2675
2676 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002677 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002678 ID.AddInteger(SM);
2679 ID.AddInteger(ConstArg);
2680 ID.AddInteger(VolatileArg);
2681 ID.AddInteger(RValueThis);
2682 ID.AddInteger(ConstThis);
2683 ID.AddInteger(VolatileThis);
2684
2685 void *InsertPoint;
2686 SpecialMemberOverloadResult *Result =
2687 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2688
2689 // This was already cached
2690 if (Result)
2691 return Result;
2692
Alexis Huntba8e18d2011-06-07 00:11:58 +00002693 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2694 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002695 SpecialMemberCache.InsertNode(Result, InsertPoint);
2696
2697 if (SM == CXXDestructor) {
Richard Smith2be35f52012-12-01 02:35:44 +00002698 if (RD->needsImplicitDestructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002699 DeclareImplicitDestructor(RD);
2700 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002701 assert(DD && "record without a destructor");
2702 Result->setMethod(DD);
Richard Smith852265f2012-03-30 20:53:28 +00002703 Result->setKind(DD->isDeleted() ?
2704 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith83c478d2012-04-20 18:46:14 +00002705 SpecialMemberOverloadResult::Success);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002706 return Result;
2707 }
2708
Alexis Hunteef8ee02011-06-10 03:50:41 +00002709 // Prepare for overload resolution. Here we construct a synthetic argument
2710 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002711 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002712 DeclarationName Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002713 Expr *Arg = nullptr;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002714 unsigned NumArgs;
2715
Richard Smith83c478d2012-04-20 18:46:14 +00002716 QualType ArgType = CanTy;
2717 ExprValueKind VK = VK_LValue;
2718
Alexis Hunteef8ee02011-06-10 03:50:41 +00002719 if (SM == CXXDefaultConstructor) {
2720 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2721 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002722 if (RD->needsImplicitDefaultConstructor())
2723 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002724 } else {
2725 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2726 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smith2be35f52012-12-01 02:35:44 +00002727 if (RD->needsImplicitCopyConstructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002728 DeclareImplicitCopyConstructor(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002729 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002730 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002731 } else {
2732 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smith2be35f52012-12-01 02:35:44 +00002733 if (RD->needsImplicitCopyAssignment())
Alexis Hunt1da39282011-06-24 02:11:39 +00002734 DeclareImplicitCopyAssignment(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002735 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002736 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002737 }
2738
Alexis Hunteef8ee02011-06-10 03:50:41 +00002739 if (ConstArg)
2740 ArgType.addConst();
2741 if (VolatileArg)
2742 ArgType.addVolatile();
2743
2744 // This isn't /really/ specified by the standard, but it's implied
2745 // we should be working from an RValue in the case of move to ensure
2746 // that we prefer to bind to rvalue references, and an LValue in the
2747 // case of copy to ensure we don't bind to rvalue references.
2748 // Possibly an XValue is actually correct in the case of move, but
2749 // there is no semantic difference for class types in this restricted
2750 // case.
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002751 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002752 VK = VK_LValue;
2753 else
2754 VK = VK_RValue;
Richard Smith83c478d2012-04-20 18:46:14 +00002755 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00002756
Richard Smith83c478d2012-04-20 18:46:14 +00002757 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2758
2759 if (SM != CXXDefaultConstructor) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002760 NumArgs = 1;
Richard Smith83c478d2012-04-20 18:46:14 +00002761 Arg = &FakeArg;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002762 }
2763
2764 // Create the object argument
2765 QualType ThisTy = CanTy;
2766 if (ConstThis)
2767 ThisTy.addConst();
2768 if (VolatileThis)
2769 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002770 Expr::Classification Classification =
Richard Smith83c478d2012-04-20 18:46:14 +00002771 OpaqueValueExpr(SourceLocation(), ThisTy,
2772 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002773
2774 // Now we perform lookup on the name we computed earlier and do overload
2775 // resolution. Lookup is only performed directly into the class since there
2776 // will always be a (possibly implicit) declaration to shadow any others.
Richard Smith100b24a2014-04-17 01:52:14 +00002777 OverloadCandidateSet OCS(RD->getLocation(), OverloadCandidateSet::CSK_Normal);
David Blaikieff7d47a2012-12-19 00:45:41 +00002778 DeclContext::lookup_result R = RD->lookup(Name);
Richard Smith8c37ab52015-02-11 01:48:47 +00002779
2780 if (R.empty()) {
2781 // We might have no default constructor because we have a lambda's closure
2782 // type, rather than because there's some other declared constructor.
2783 // Every class has a copy/move constructor, copy/move assignment, and
2784 // destructor.
2785 assert(SM == CXXDefaultConstructor &&
2786 "lookup for a constructor or assignment operator was empty");
2787 Result->setMethod(nullptr);
2788 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
2789 return Result;
2790 }
Chandler Carruth7deaae72013-08-18 07:20:52 +00002791
2792 // Copy the candidates as our processing of them may load new declarations
2793 // from an external source and invalidate lookup_result.
2794 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2795
Aaron Ballman1e606f42014-07-15 22:03:49 +00002796 for (auto *Cand : Candidates) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002797 if (Cand->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002798 continue;
2799
Alexis Hunt1da39282011-06-24 02:11:39 +00002800 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2801 // FIXME: [namespace.udecl]p15 says that we should only consider a
2802 // using declaration here if it does not match a declaration in the
2803 // derived class. We do not implement this correctly in other cases
2804 // either.
2805 Cand = U->getTargetDecl();
2806
2807 if (Cand->isInvalidDecl())
2808 continue;
2809 }
2810
2811 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002812 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Alexis Hunt1da39282011-06-24 02:11:39 +00002813 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002814 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2815 OCS, true);
Alexis Hunt080709f2011-06-23 00:26:20 +00002816 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002817 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2818 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt2949f022011-06-22 02:58:46 +00002819 } else if (FunctionTemplateDecl *Tmpl =
Alexis Hunt1da39282011-06-24 02:11:39 +00002820 dyn_cast<FunctionTemplateDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002821 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2822 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Craig Topperc3ec1492014-05-26 06:22:03 +00002823 RD, nullptr, ThisTy, Classification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002824 llvm::makeArrayRef(&Arg, NumArgs),
Alexis Hunt080709f2011-06-23 00:26:20 +00002825 OCS, true);
2826 else
2827 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Craig Topperc3ec1492014-05-26 06:22:03 +00002828 nullptr, llvm::makeArrayRef(&Arg, NumArgs),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002829 OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002830 } else {
2831 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002832 }
2833 }
2834
2835 OverloadCandidateSet::iterator Best;
2836 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2837 case OR_Success:
2838 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith83c478d2012-04-20 18:46:14 +00002839 Result->setKind(SpecialMemberOverloadResult::Success);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002840 break;
2841
2842 case OR_Deleted:
2843 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith852265f2012-03-30 20:53:28 +00002844 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002845 break;
2846
2847 case OR_Ambiguous:
Craig Topperc3ec1492014-05-26 06:22:03 +00002848 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00002849 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2850 break;
2851
Alexis Hunteef8ee02011-06-10 03:50:41 +00002852 case OR_No_Viable_Function:
Craig Topperc3ec1492014-05-26 06:22:03 +00002853 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00002854 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002855 break;
2856 }
2857
2858 return Result;
2859}
2860
2861/// \brief Look up the default constructor for the given class.
2862CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002863 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002864 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2865 false, false);
2866
2867 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002868}
2869
Alexis Hunt491ec602011-06-21 23:42:56 +00002870/// \brief Look up the copying constructor for the given class.
2871CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith83c478d2012-04-20 18:46:14 +00002872 unsigned Quals) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002873 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2874 "non-const, non-volatile qualifiers for copy ctor arg");
2875 SpecialMemberOverloadResult *Result =
2876 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2877 Quals & Qualifiers::Volatile, false, false, false);
2878
Alexis Hunt899bd442011-06-10 04:44:37 +00002879 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2880}
2881
Sebastian Redl22653ba2011-08-30 19:58:05 +00002882/// \brief Look up the moving constructor for the given class.
Richard Smith1c6461e2012-07-18 03:36:00 +00002883CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2884 unsigned Quals) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002885 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002886 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2887 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002888
2889 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2890}
2891
Douglas Gregor52b72822010-07-02 23:12:18 +00002892/// \brief Look up the constructors for the given class.
2893DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002894 // If the implicit constructors have not yet been declared, do so now.
Richard Smith7d125a12012-11-27 21:20:31 +00002895 if (CanDeclareSpecialMemberFunction(Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00002896 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002897 DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +00002898 if (Class->needsImplicitCopyConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002899 DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002900 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002901 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00002902 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002903
Douglas Gregor52b72822010-07-02 23:12:18 +00002904 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2905 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2906 return Class->lookup(Name);
2907}
2908
Alexis Hunt491ec602011-06-21 23:42:56 +00002909/// \brief Look up the copying assignment operator for the given class.
2910CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2911 unsigned Quals, bool RValueThis,
Richard Smith83c478d2012-04-20 18:46:14 +00002912 unsigned ThisQuals) {
Alexis Hunt491ec602011-06-21 23:42:56 +00002913 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2914 "non-const, non-volatile qualifiers for copy assignment arg");
2915 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2916 "non-const, non-volatile qualifiers for copy assignment this");
2917 SpecialMemberOverloadResult *Result =
2918 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2919 Quals & Qualifiers::Volatile, RValueThis,
2920 ThisQuals & Qualifiers::Const,
2921 ThisQuals & Qualifiers::Volatile);
2922
Alexis Hunt491ec602011-06-21 23:42:56 +00002923 return Result->getMethod();
2924}
2925
Sebastian Redl22653ba2011-08-30 19:58:05 +00002926/// \brief Look up the moving assignment operator for the given class.
2927CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith1c6461e2012-07-18 03:36:00 +00002928 unsigned Quals,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002929 bool RValueThis,
2930 unsigned ThisQuals) {
2931 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2932 "non-const, non-volatile qualifiers for copy assignment this");
2933 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002934 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2935 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002936 ThisQuals & Qualifiers::Const,
2937 ThisQuals & Qualifiers::Volatile);
2938
2939 return Result->getMethod();
2940}
2941
Douglas Gregore71edda2010-07-01 22:47:18 +00002942/// \brief Look for the destructor of the given class.
2943///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00002944/// During semantic analysis, this routine should be used in lieu of
2945/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00002946///
2947/// \returns The destructor for this class.
2948CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002949 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2950 false, false, false,
2951 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00002952}
2953
Richard Smithbcc22fc2012-03-09 08:00:36 +00002954/// LookupLiteralOperator - Determine which literal operator should be used for
2955/// a user-defined literal, per C++11 [lex.ext].
2956///
2957/// Normal overload resolution is not used to select which literal operator to
2958/// call for a user-defined literal. Look up the provided literal operator name,
2959/// and filter the results to the appropriate set for the given argument types.
2960Sema::LiteralOperatorLookupResult
2961Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2962 ArrayRef<QualType> ArgTys,
Richard Smithb8b41d32013-10-07 19:57:58 +00002963 bool AllowRaw, bool AllowTemplate,
2964 bool AllowStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002965 LookupName(R, S);
2966 assert(R.getResultKind() != LookupResult::Ambiguous &&
2967 "literal operator lookup can't be ambiguous");
2968
2969 // Filter the lookup results appropriately.
2970 LookupResult::Filter F = R.makeFilter();
2971
Richard Smithbcc22fc2012-03-09 08:00:36 +00002972 bool FoundRaw = false;
Richard Smithb8b41d32013-10-07 19:57:58 +00002973 bool FoundTemplate = false;
2974 bool FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002975 bool FoundExactMatch = false;
2976
2977 while (F.hasNext()) {
2978 Decl *D = F.next();
2979 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2980 D = USD->getTargetDecl();
2981
Douglas Gregorc1970572013-04-10 05:18:00 +00002982 // If the declaration we found is invalid, skip it.
2983 if (D->isInvalidDecl()) {
2984 F.erase();
2985 continue;
2986 }
2987
Richard Smithb8b41d32013-10-07 19:57:58 +00002988 bool IsRaw = false;
2989 bool IsTemplate = false;
2990 bool IsStringTemplate = false;
2991 bool IsExactMatch = false;
2992
Richard Smithbcc22fc2012-03-09 08:00:36 +00002993 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2994 if (FD->getNumParams() == 1 &&
2995 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2996 IsRaw = true;
Richard Smith550de452013-01-15 07:12:59 +00002997 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002998 IsExactMatch = true;
2999 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
3000 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
3001 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
3002 IsExactMatch = false;
3003 break;
3004 }
3005 }
3006 }
3007 }
Richard Smithb8b41d32013-10-07 19:57:58 +00003008 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
3009 TemplateParameterList *Params = FD->getTemplateParameters();
3010 if (Params->size() == 1)
3011 IsTemplate = true;
3012 else
3013 IsStringTemplate = true;
3014 }
Richard Smithbcc22fc2012-03-09 08:00:36 +00003015
3016 if (IsExactMatch) {
3017 FoundExactMatch = true;
Richard Smithb8b41d32013-10-07 19:57:58 +00003018 AllowRaw = false;
3019 AllowTemplate = false;
3020 AllowStringTemplate = false;
3021 if (FoundRaw || FoundTemplate || FoundStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003022 // Go through again and remove the raw and template decls we've
3023 // already found.
3024 F.restart();
Richard Smithb8b41d32013-10-07 19:57:58 +00003025 FoundRaw = FoundTemplate = FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003026 }
Richard Smithb8b41d32013-10-07 19:57:58 +00003027 } else if (AllowRaw && IsRaw) {
3028 FoundRaw = true;
3029 } else if (AllowTemplate && IsTemplate) {
3030 FoundTemplate = true;
3031 } else if (AllowStringTemplate && IsStringTemplate) {
3032 FoundStringTemplate = true;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003033 } else {
3034 F.erase();
3035 }
3036 }
3037
3038 F.done();
3039
3040 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
3041 // parameter type, that is used in preference to a raw literal operator
3042 // or literal operator template.
3043 if (FoundExactMatch)
3044 return LOLR_Cooked;
3045
3046 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
3047 // operator template, but not both.
3048 if (FoundRaw && FoundTemplate) {
3049 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
Alp Tokera2794f92014-01-22 07:29:52 +00003050 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3051 NoteOverloadCandidate((*I)->getUnderlyingDecl()->getAsFunction());
Richard Smithbcc22fc2012-03-09 08:00:36 +00003052 return LOLR_Error;
3053 }
3054
3055 if (FoundRaw)
3056 return LOLR_Raw;
3057
3058 if (FoundTemplate)
3059 return LOLR_Template;
3060
Richard Smithb8b41d32013-10-07 19:57:58 +00003061 if (FoundStringTemplate)
3062 return LOLR_StringTemplate;
3063
Richard Smithbcc22fc2012-03-09 08:00:36 +00003064 // Didn't find anything we could use.
3065 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
3066 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
Richard Smithb8b41d32013-10-07 19:57:58 +00003067 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
3068 << (AllowTemplate || AllowStringTemplate);
Richard Smithbcc22fc2012-03-09 08:00:36 +00003069 return LOLR_Error;
3070}
3071
John McCall8fe68082010-01-26 07:16:45 +00003072void ADLResult::insert(NamedDecl *New) {
3073 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
3074
3075 // If we haven't yet seen a decl for this key, or the last decl
3076 // was exactly this one, we're done.
Craig Topperc3ec1492014-05-26 06:22:03 +00003077 if (Old == nullptr || Old == New) {
John McCall8fe68082010-01-26 07:16:45 +00003078 Old = New;
3079 return;
3080 }
3081
3082 // Otherwise, decide which is a more recent redeclaration.
Alp Tokera2794f92014-01-22 07:29:52 +00003083 FunctionDecl *OldFD = Old->getAsFunction();
3084 FunctionDecl *NewFD = New->getAsFunction();
John McCall8fe68082010-01-26 07:16:45 +00003085
3086 FunctionDecl *Cursor = NewFD;
3087 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00003088 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00003089
3090 // If we got to the end without finding OldFD, OldFD is the newer
3091 // declaration; leave things as they are.
3092 if (!Cursor) return;
3093
3094 // If we do find OldFD, then NewFD is newer.
3095 if (Cursor == OldFD) break;
3096
3097 // Otherwise, keep looking.
3098 }
3099
3100 Old = New;
3101}
3102
Richard Smith100b24a2014-04-17 01:52:14 +00003103void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3104 ArrayRef<Expr *> Args, ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003105 // Find all of the associated namespaces and classes based on the
3106 // arguments we have.
3107 AssociatedNamespaceSet AssociatedNamespaces;
3108 AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00003109 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCallc7e8e792009-08-07 22:18:02 +00003110 AssociatedNamespaces,
3111 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003112
3113 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003114 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3115 // and let Y be the lookup set produced by argument dependent
3116 // lookup (defined as follows). If X contains [...] then Y is
3117 // empty. Otherwise Y is the set of declarations found in the
3118 // namespaces associated with the argument types as described
3119 // below. The set of declarations found by the lookup of the name
3120 // is the union of X and Y.
3121 //
3122 // Here, we compute Y and add its members to the overloaded
3123 // candidate set.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003124 for (auto *NS : AssociatedNamespaces) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003125 // When considering an associated namespace, the lookup is the
3126 // same as the lookup performed when the associated namespace is
3127 // used as a qualifier (3.4.3.2) except that:
3128 //
3129 // -- Any using-directives in the associated namespace are
3130 // ignored.
3131 //
John McCallc7e8e792009-08-07 22:18:02 +00003132 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003133 // associated classes are visible within their respective
3134 // namespaces even if they are not visible during an ordinary
3135 // lookup (11.4).
Aaron Ballman1e606f42014-07-15 22:03:49 +00003136 DeclContext::lookup_result R = NS->lookup(Name);
3137 for (auto *D : R) {
John McCallaa74a0c2009-08-28 07:59:38 +00003138 // If the only declaration here is an ordinary friend, consider
3139 // it only if it was declared in an associated classes.
Richard Smith541b38b2013-09-20 01:15:31 +00003140 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) {
3141 // If it's neither ordinarily visible nor a friend, we can't find it.
3142 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0)
3143 continue;
3144
Richard Smith64017682013-07-17 23:53:16 +00003145 bool DeclaredInAssociatedClass = false;
3146 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
3147 DeclContext *LexDC = DI->getLexicalDeclContext();
3148 if (isa<CXXRecordDecl>(LexDC) &&
3149 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) {
3150 DeclaredInAssociatedClass = true;
3151 break;
3152 }
3153 }
3154 if (!DeclaredInAssociatedClass)
John McCalld1e9d832009-08-11 06:59:38 +00003155 continue;
3156 }
Mike Stump11289f42009-09-09 15:08:12 +00003157
John McCall91f61fc2010-01-26 06:04:06 +00003158 if (isa<UsingShadowDecl>(D))
3159 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00003160
Richard Smith100b24a2014-04-17 01:52:14 +00003161 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D))
John McCall8fe68082010-01-26 07:16:45 +00003162 continue;
3163
Richard Smitha1431072015-06-12 01:32:13 +00003164 if (!isVisible(D) && !(D = findAcceptableDecl(*this, D)))
3165 continue;
3166
John McCall8fe68082010-01-26 07:16:45 +00003167 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00003168 }
3169 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003170}
Douglas Gregor2d435302009-12-30 17:04:44 +00003171
3172//----------------------------------------------------------------------------
3173// Search for all visible declarations.
3174//----------------------------------------------------------------------------
3175VisibleDeclConsumer::~VisibleDeclConsumer() { }
3176
Richard Smithe156254d2013-08-20 20:35:18 +00003177bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
3178
Douglas Gregor2d435302009-12-30 17:04:44 +00003179namespace {
3180
3181class ShadowContextRAII;
3182
3183class VisibleDeclsRecord {
3184public:
3185 /// \brief An entry in the shadow map, which is optimized to store a
3186 /// single declaration (the common case) but can also store a list
3187 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00003188 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00003189
3190private:
3191 /// \brief A mapping from declaration names to the declarations that have
3192 /// this name within a particular scope.
3193 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
3194
3195 /// \brief A list of shadow maps, which is used to model name hiding.
3196 std::list<ShadowMap> ShadowMaps;
3197
3198 /// \brief The declaration contexts we have already visited.
3199 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
3200
3201 friend class ShadowContextRAII;
3202
3203public:
3204 /// \brief Determine whether we have already visited this context
3205 /// (and, if not, note that we are going to visit that context now).
3206 bool visitedContext(DeclContext *Ctx) {
David Blaikie82e95a32014-11-19 07:49:47 +00003207 return !VisitedContexts.insert(Ctx).second;
Douglas Gregor2d435302009-12-30 17:04:44 +00003208 }
3209
Douglas Gregor39982192010-08-15 06:18:01 +00003210 bool alreadyVisitedContext(DeclContext *Ctx) {
3211 return VisitedContexts.count(Ctx);
3212 }
3213
Douglas Gregor2d435302009-12-30 17:04:44 +00003214 /// \brief Determine whether the given declaration is hidden in the
3215 /// current scope.
3216 ///
3217 /// \returns the declaration that hides the given declaration, or
3218 /// NULL if no such declaration exists.
3219 NamedDecl *checkHidden(NamedDecl *ND);
3220
3221 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00003222 void add(NamedDecl *ND) {
3223 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
3224 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003225};
3226
3227/// \brief RAII object that records when we've entered a shadow context.
3228class ShadowContextRAII {
3229 VisibleDeclsRecord &Visible;
3230
3231 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
3232
3233public:
3234 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
Benjamin Kramer3204b152015-05-29 19:42:19 +00003235 Visible.ShadowMaps.emplace_back();
Douglas Gregor2d435302009-12-30 17:04:44 +00003236 }
3237
3238 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00003239 Visible.ShadowMaps.pop_back();
3240 }
3241};
3242
3243} // end anonymous namespace
3244
Douglas Gregor2d435302009-12-30 17:04:44 +00003245NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00003246 // Look through using declarations.
3247 ND = ND->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003248
Douglas Gregor2d435302009-12-30 17:04:44 +00003249 unsigned IDNS = ND->getIdentifierNamespace();
3250 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
3251 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3252 SM != SMEnd; ++SM) {
3253 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
3254 if (Pos == SM->end())
3255 continue;
3256
Aaron Ballman1e606f42014-07-15 22:03:49 +00003257 for (auto *D : Pos->second) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003258 // A tag declaration does not hide a non-tag declaration.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003259 if (D->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003260 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00003261 Decl::IDNS_ObjCProtocol)))
3262 continue;
3263
3264 // Protocols are in distinct namespaces from everything else.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003265 if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor2d435302009-12-30 17:04:44 +00003266 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Aaron Ballman1e606f42014-07-15 22:03:49 +00003267 D->getIdentifierNamespace() != IDNS)
Douglas Gregor2d435302009-12-30 17:04:44 +00003268 continue;
3269
Douglas Gregor09bbc652010-01-14 15:47:35 +00003270 // Functions and function templates in the same scope overload
3271 // rather than hide. FIXME: Look for hiding based on function
3272 // signatures!
Aaron Ballman1e606f42014-07-15 22:03:49 +00003273 if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Alp Tokera2794f92014-01-22 07:29:52 +00003274 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00003275 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00003276 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003277
Douglas Gregor2d435302009-12-30 17:04:44 +00003278 // We've found a declaration that hides this one.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003279 return D;
Douglas Gregor2d435302009-12-30 17:04:44 +00003280 }
3281 }
3282
Craig Topperc3ec1492014-05-26 06:22:03 +00003283 return nullptr;
Douglas Gregor2d435302009-12-30 17:04:44 +00003284}
3285
3286static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
3287 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003288 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00003289 VisibleDeclConsumer &Consumer,
3290 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00003291 if (!Ctx)
3292 return;
3293
Douglas Gregor2d435302009-12-30 17:04:44 +00003294 // Make sure we don't visit the same context twice.
3295 if (Visited.visitedContext(Ctx->getPrimaryContext()))
3296 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003297
Richard Smith9e2341d2015-03-23 03:25:59 +00003298 // Outside C++, lookup results for the TU live on identifiers.
3299 if (isa<TranslationUnitDecl>(Ctx) &&
3300 !Result.getSema().getLangOpts().CPlusPlus) {
3301 auto &S = Result.getSema();
3302 auto &Idents = S.Context.Idents;
3303
3304 // Ensure all external identifiers are in the identifier table.
3305 if (IdentifierInfoLookup *External = Idents.getExternalIdentifierLookup()) {
3306 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
3307 for (StringRef Name = Iter->Next(); !Name.empty(); Name = Iter->Next())
3308 Idents.get(Name);
3309 }
3310
3311 // Walk all lookup results in the TU for each identifier.
3312 for (const auto &Ident : Idents) {
3313 for (auto I = S.IdResolver.begin(Ident.getValue()),
3314 E = S.IdResolver.end();
3315 I != E; ++I) {
3316 if (S.IdResolver.isDeclInScope(*I, Ctx)) {
3317 if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
3318 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3319 Visited.add(ND);
3320 }
3321 }
3322 }
3323 }
3324
3325 return;
3326 }
3327
Douglas Gregor7454c562010-07-02 20:37:36 +00003328 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3329 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3330
Douglas Gregor2d435302009-12-30 17:04:44 +00003331 // Enumerate all of the results in this context.
Richard Trieu20abd6b2015-04-15 03:48:48 +00003332 for (DeclContextLookupResult R : Ctx->lookups()) {
Richard Smith9e2341d2015-03-23 03:25:59 +00003333 for (auto *D : R) {
3334 if (auto *ND = Result.getAcceptableDecl(D)) {
3335 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3336 Visited.add(ND);
Douglas Gregora3b23b02010-12-09 21:44:02 +00003337 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003338 }
3339 }
3340
3341 // Traverse using directives for qualified name lookup.
3342 if (QualifiedNameLookup) {
3343 ShadowContextRAII Shadow(Visited);
Aaron Ballman804a7fb2014-03-17 17:14:12 +00003344 for (auto I : Ctx->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00003345 LookupVisibleDecls(I->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003346 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003347 }
3348 }
3349
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003350 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00003351 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00003352 if (!Record->hasDefinition())
3353 return;
3354
Aaron Ballman574705e2014-03-13 15:41:46 +00003355 for (const auto &B : Record->bases()) {
3356 QualType BaseType = B.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003357
Douglas Gregor2d435302009-12-30 17:04:44 +00003358 // Don't look into dependent bases, because name lookup can't look
3359 // there anyway.
3360 if (BaseType->isDependentType())
3361 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003362
Douglas Gregor2d435302009-12-30 17:04:44 +00003363 const RecordType *Record = BaseType->getAs<RecordType>();
3364 if (!Record)
3365 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003366
Douglas Gregor2d435302009-12-30 17:04:44 +00003367 // FIXME: It would be nice to be able to determine whether referencing
3368 // a particular member would be ambiguous. For example, given
3369 //
3370 // struct A { int member; };
3371 // struct B { int member; };
3372 // struct C : A, B { };
3373 //
3374 // void f(C *c) { c->### }
3375 //
3376 // accessing 'member' would result in an ambiguity. However, we
3377 // could be smart enough to qualify the member with the base
3378 // class, e.g.,
3379 //
3380 // c->B::member
3381 //
3382 // or
3383 //
3384 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003385
Douglas Gregor2d435302009-12-30 17:04:44 +00003386 // Find results in this base class (and its bases).
3387 ShadowContextRAII Shadow(Visited);
3388 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003389 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003390 }
3391 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003392
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003393 // Traverse the contexts of Objective-C classes.
3394 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3395 // Traverse categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003396 for (auto *Cat : IFace->visible_categories()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003397 ShadowContextRAII Shadow(Visited);
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003398 LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003399 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003400 }
3401
3402 // Traverse protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003403 for (auto *I : IFace->all_referenced_protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003404 ShadowContextRAII Shadow(Visited);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003405 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003406 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003407 }
3408
3409 // Traverse the superclass.
3410 if (IFace->getSuperClass()) {
3411 ShadowContextRAII Shadow(Visited);
3412 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003413 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003414 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003415
Douglas Gregor0b59e802010-04-19 18:02:19 +00003416 // If there is an implementation, traverse it. We do this to find
3417 // synthesized ivars.
3418 if (IFace->getImplementation()) {
3419 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003420 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky13668f22012-04-03 20:26:45 +00003421 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor0b59e802010-04-19 18:02:19 +00003422 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003423 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003424 for (auto *I : Protocol->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003425 ShadowContextRAII Shadow(Visited);
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003426 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003427 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003428 }
3429 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003430 for (auto *I : Category->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003431 ShadowContextRAII Shadow(Visited);
Aaron Ballman19a41762014-03-14 12:55:57 +00003432 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003433 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003434 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003435
Douglas Gregor0b59e802010-04-19 18:02:19 +00003436 // If there is an implementation, traverse it.
3437 if (Category->getImplementation()) {
3438 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003439 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00003440 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003441 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003442 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003443}
3444
3445static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3446 UnqualUsingDirectiveSet &UDirs,
3447 VisibleDeclConsumer &Consumer,
3448 VisibleDeclsRecord &Visited) {
3449 if (!S)
3450 return;
3451
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003452 if (!S->getEntity() ||
3453 (!S->getParent() &&
Ted Kremenekc37877d2013-10-08 17:08:03 +00003454 !Visited.alreadyVisitedContext(S->getEntity())) ||
3455 (S->getEntity())->isFunctionOrMethod()) {
Richard Smith541b38b2013-09-20 01:15:31 +00003456 FindLocalExternScope FindLocals(Result);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003457 // Walk through the declarations in this Scope.
Aaron Ballman35c54952014-03-17 16:55:25 +00003458 for (auto *D : S->decls()) {
3459 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Douglas Gregor4a814562011-12-14 16:03:29 +00003460 if ((ND = Result.getAcceptableDecl(ND))) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003461 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003462 Visited.add(ND);
3463 }
3464 }
3465 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003466
Douglas Gregor66230062010-03-15 14:33:29 +00003467 // FIXME: C++ [temp.local]p8
Craig Topperc3ec1492014-05-26 06:22:03 +00003468 DeclContext *Entity = nullptr;
Douglas Gregor4f248632010-01-01 17:44:25 +00003469 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003470 // Look into this scope's declaration context, along with any of its
3471 // parent lookup contexts (e.g., enclosing classes), up to the point
3472 // where we hit the context stored in the next outer scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00003473 Entity = S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00003474 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003475
Douglas Gregorea166062010-03-15 15:26:48 +00003476 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00003477 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003478 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3479 if (Method->isInstanceMethod()) {
3480 // For instance methods, look for ivars in the method's interface.
3481 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3482 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003483 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003484 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Richard Smithe156254d2013-08-20 20:35:18 +00003485 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003486 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003487 }
3488
3489 // We've already performed all of the name lookup that we need
3490 // to for Objective-C methods; the next context will be the
3491 // outer scope.
3492 break;
3493 }
3494
Douglas Gregor2d435302009-12-30 17:04:44 +00003495 if (Ctx->isFunctionOrMethod())
3496 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003497
3498 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003499 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003500 }
3501 } else if (!S->getParent()) {
3502 // Look into the translation unit scope. We walk through the translation
3503 // unit's declaration context, because the Scope itself won't have all of
3504 // the declarations if we loaded a precompiled header.
3505 // FIXME: We would like the translation unit's Scope object to point to the
3506 // translation unit, so we don't need this special "if" branch. However,
3507 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003508 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00003509 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003510 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00003511 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003512 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003513 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003514 }
3515
Douglas Gregor2d435302009-12-30 17:04:44 +00003516 if (Entity) {
3517 // Lookup visible declarations in any namespaces found by using
3518 // directives.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003519 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
3520 LookupVisibleDecls(const_cast<DeclContext *>(UUE.getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003521 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003522 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003523 }
3524
3525 // Lookup names in the parent scope.
3526 ShadowContextRAII Shadow(Visited);
3527 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3528}
3529
3530void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003531 VisibleDeclConsumer &Consumer,
3532 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003533 // Determine the set of using directives available during
3534 // unqualified name lookup.
3535 Scope *Initial = S;
3536 UnqualUsingDirectiveSet UDirs;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003537 if (getLangOpts().CPlusPlus) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003538 // Find the first namespace or translation-unit scope.
3539 while (S && !isNamespaceOrTranslationUnitScope(S))
3540 S = S->getParent();
3541
3542 UDirs.visitScopeChain(Initial, S);
3543 }
3544 UDirs.done();
3545
3546 // Look for visible declarations.
3547 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003548 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003549 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003550 if (!IncludeGlobalScope)
3551 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003552 ShadowContextRAII Shadow(Visited);
3553 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3554}
3555
3556void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003557 VisibleDeclConsumer &Consumer,
3558 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003559 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003560 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003561 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003562 if (!IncludeGlobalScope)
3563 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003564 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003565 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003566 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003567}
3568
Chris Lattner43e7f312011-02-18 02:08:43 +00003569/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003570/// If GnuLabelLoc is a valid source location, then this is a definition
3571/// of an __label__ label name, otherwise it is a normal label definition
3572/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003573LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003574 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003575 // Do a lookup to see if we have a label with this name already.
Craig Topperc3ec1492014-05-26 06:22:03 +00003576 NamedDecl *Res = nullptr;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003577
3578 if (GnuLabelLoc.isValid()) {
3579 // Local label definitions always shadow existing labels.
3580 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3581 Scope *S = CurScope;
3582 PushOnScopeChains(Res, S, true);
3583 return cast<LabelDecl>(Res);
3584 }
3585
3586 // Not a GNU local label.
3587 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3588 // If we found a label, check to see if it is in the same context as us.
3589 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003590 if (Res && Res->getDeclContext() != CurContext)
Craig Topperc3ec1492014-05-26 06:22:03 +00003591 Res = nullptr;
3592 if (!Res) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003593 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003594 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3595 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003596 assert(S && "Not in a function?");
3597 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003598 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003599 return cast<LabelDecl>(Res);
3600}
3601
3602//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003603// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003604//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003605
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003606static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3607 TypoCorrection &Candidate) {
3608 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3609 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3610}
3611
3612static void LookupPotentialTypoResult(Sema &SemaRef,
3613 LookupResult &Res,
3614 IdentifierInfo *Name,
3615 Scope *S, CXXScopeSpec *SS,
3616 DeclContext *MemberContext,
3617 bool EnteringContext,
3618 bool isObjCIvarLookup,
3619 bool FindHidden);
3620
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003621/// \brief Check whether the declarations found for a typo correction are
3622/// visible, and if none of them are, convert the correction to an 'import
3623/// a module' correction.
3624static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
3625 if (TC.begin() == TC.end())
3626 return;
3627
3628 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3629
3630 for (/**/; DI != DE; ++DI)
3631 if (!LookupResult::isVisible(SemaRef, *DI))
3632 break;
3633 // Nothing to do if all decls are visible.
3634 if (DI == DE)
3635 return;
3636
3637 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3638 bool AnyVisibleDecls = !NewDecls.empty();
3639
3640 for (/**/; DI != DE; ++DI) {
3641 NamedDecl *VisibleDecl = *DI;
3642 if (!LookupResult::isVisible(SemaRef, *DI))
3643 VisibleDecl = findAcceptableDecl(SemaRef, *DI);
3644
3645 if (VisibleDecl) {
3646 if (!AnyVisibleDecls) {
3647 // Found a visible decl, discard all hidden ones.
3648 AnyVisibleDecls = true;
3649 NewDecls.clear();
3650 }
3651 NewDecls.push_back(VisibleDecl);
3652 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
3653 NewDecls.push_back(*DI);
3654 }
3655
3656 if (NewDecls.empty())
3657 TC = TypoCorrection();
3658 else {
3659 TC.setCorrectionDecls(NewDecls);
3660 TC.setRequiresImport(!AnyVisibleDecls);
3661 }
3662}
3663
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003664// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3665// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3666// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3667static void getNestedNameSpecifierIdentifiers(
3668 NestedNameSpecifier *NNS,
3669 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3670 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3671 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3672 else
3673 Identifiers.clear();
3674
3675 const IdentifierInfo *II = nullptr;
3676
3677 switch (NNS->getKind()) {
3678 case NestedNameSpecifier::Identifier:
3679 II = NNS->getAsIdentifier();
3680 break;
3681
3682 case NestedNameSpecifier::Namespace:
3683 if (NNS->getAsNamespace()->isAnonymousNamespace())
3684 return;
3685 II = NNS->getAsNamespace()->getIdentifier();
3686 break;
3687
3688 case NestedNameSpecifier::NamespaceAlias:
3689 II = NNS->getAsNamespaceAlias()->getIdentifier();
3690 break;
3691
3692 case NestedNameSpecifier::TypeSpecWithTemplate:
3693 case NestedNameSpecifier::TypeSpec:
3694 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3695 break;
3696
3697 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00003698 case NestedNameSpecifier::Super:
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003699 return;
3700 }
3701
3702 if (II)
3703 Identifiers.push_back(II);
3704}
3705
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003706void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003707 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003708 // Don't consider hidden names for typo correction.
3709 if (Hiding)
3710 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003711
Douglas Gregor2d435302009-12-30 17:04:44 +00003712 // Only consider entities with identifiers for names, ignoring
3713 // special names (constructors, overloaded operators, selectors,
3714 // etc.).
3715 IdentifierInfo *Name = ND->getIdentifier();
3716 if (!Name)
3717 return;
3718
Richard Smithe156254d2013-08-20 20:35:18 +00003719 // Only consider visible declarations and declarations from modules with
3720 // names that exactly match.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003721 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo &&
Richard Smithe156254d2013-08-20 20:35:18 +00003722 !findAcceptableDecl(SemaRef, ND))
3723 return;
3724
Douglas Gregor57756ea2010-10-14 22:11:03 +00003725 FoundName(Name->getName());
3726}
3727
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003728void TypoCorrectionConsumer::FoundName(StringRef Name) {
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003729 // Compute the edit distance between the typo and the name of this
3730 // entity, and add the identifier to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003731 addName(Name, nullptr);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003732}
3733
3734void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3735 // Compute the edit distance between the typo and this keyword,
3736 // and add the keyword to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003737 addName(Keyword, nullptr, nullptr, true);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003738}
3739
3740void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
3741 NestedNameSpecifier *NNS, bool isKeyword) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003742 // Use a simple length-based heuristic to determine the minimum possible
3743 // edit distance. If the minimum isn't good enough, bail out early.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003744 StringRef TypoStr = Typo->getName();
3745 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
3746 if (MinED && TypoStr.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00003747 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003748
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003749 // Compute an upper bound on the allowable edit distance, so that the
3750 // edit-distance algorithm can short-circuit.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003751 unsigned UpperBound = (TypoStr.size() + 2) / 3 + 1;
3752 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003753 if (ED >= UpperBound) return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003754
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003755 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003756 if (isKeyword) TC.makeKeyword();
Kaelyn Takata0a313022014-11-20 22:06:26 +00003757 TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003758 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003759}
3760
Kaelyn Takatad2287c32014-10-27 18:07:13 +00003761static const unsigned MaxTypoDistanceResultSets = 5;
3762
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003763void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003764 StringRef TypoStr = Typo->getName();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003765 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003766
3767 // For very short typos, ignore potential corrections that have a different
3768 // base identifier from the typo or which have a normalized edit distance
3769 // longer than the typo itself.
3770 if (TypoStr.size() < 3 &&
3771 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
3772 return;
3773
3774 // If the correction is resolved but is not viable, ignore it.
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003775 if (Correction.isResolved()) {
3776 checkCorrectionVisibility(SemaRef, Correction);
3777 if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
3778 return;
3779 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003780
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003781 TypoResultList &CList =
3782 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003783
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003784 if (!CList.empty() && !CList.back().isResolved())
3785 CList.pop_back();
3786 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3787 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3788 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3789 RI != RIEnd; ++RI) {
3790 // If the Correction refers to a decl already in the result list,
3791 // replace the existing result if the string representation of Correction
3792 // comes before the current result alphabetically, then stop as there is
3793 // nothing more to be done to add Correction to the candidate set.
3794 if (RI->getCorrectionDecl() == NewND) {
3795 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3796 *RI = Correction;
3797 return;
3798 }
3799 }
3800 }
3801 if (CList.empty() || Correction.isResolved())
3802 CList.push_back(Correction);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003803
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003804 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003805 CorrectionResults.erase(std::prev(CorrectionResults.end()));
3806}
3807
3808void TypoCorrectionConsumer::addNamespaces(
3809 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
3810 SearchNamespaces = true;
3811
3812 for (auto KNPair : KnownNamespaces)
3813 Namespaces.addNameSpecifier(KNPair.first);
3814
3815 bool SSIsTemplate = false;
3816 if (NestedNameSpecifier *NNS =
3817 (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
3818 if (const Type *T = NNS->getAsType())
3819 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
3820 }
3821 for (const auto *TI : SemaRef.getASTContext().types()) {
Kaelyn Takata26487022015-10-01 22:38:51 +00003822 if (!TI->isClassType() && isa<TemplateSpecializationType>(TI))
3823 continue;
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003824 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
3825 CD = CD->getCanonicalDecl();
3826 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
3827 !CD->isUnion() && CD->getIdentifier() &&
3828 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
3829 (CD->isBeingDefined() || CD->isCompleteDefinition()))
3830 Namespaces.addNameSpecifier(CD);
3831 }
3832 }
3833}
3834
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003835const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
3836 if (++CurrentTCIndex < ValidatedCorrections.size())
3837 return ValidatedCorrections[CurrentTCIndex];
3838
3839 CurrentTCIndex = ValidatedCorrections.size();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003840 while (!CorrectionResults.empty()) {
3841 auto DI = CorrectionResults.begin();
3842 if (DI->second.empty()) {
3843 CorrectionResults.erase(DI);
3844 continue;
3845 }
3846
3847 auto RI = DI->second.begin();
3848 if (RI->second.empty()) {
3849 DI->second.erase(RI);
3850 performQualifiedLookups();
3851 continue;
3852 }
3853
3854 TypoCorrection TC = RI->second.pop_back_val();
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003855 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003856 ValidatedCorrections.push_back(TC);
3857 return ValidatedCorrections[CurrentTCIndex];
3858 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003859 }
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003860 return ValidatedCorrections[0]; // The empty correction.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003861}
3862
3863bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
3864 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
3865 DeclContext *TempMemberContext = MemberContext;
Kaelyn Takata6c759512014-10-27 18:07:37 +00003866 CXXScopeSpec *TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003867retry_lookup:
3868 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
3869 EnteringContext,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00003870 CorrectionValidator->IsObjCIvarLookup,
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003871 Name == Typo && !Candidate.WillReplaceSpecifier());
3872 switch (Result.getResultKind()) {
3873 case LookupResult::NotFound:
3874 case LookupResult::NotFoundInCurrentInstantiation:
3875 case LookupResult::FoundUnresolvedValue:
3876 if (TempSS) {
3877 // Immediately retry the lookup without the given CXXScopeSpec
3878 TempSS = nullptr;
3879 Candidate.WillReplaceSpecifier(true);
3880 goto retry_lookup;
3881 }
3882 if (TempMemberContext) {
3883 if (SS && !TempSS)
Kaelyn Takata6c759512014-10-27 18:07:37 +00003884 TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003885 TempMemberContext = nullptr;
3886 goto retry_lookup;
3887 }
3888 if (SearchNamespaces)
3889 QualifiedResults.push_back(Candidate);
3890 break;
3891
3892 case LookupResult::Ambiguous:
3893 // We don't deal with ambiguities.
3894 break;
3895
3896 case LookupResult::Found:
3897 case LookupResult::FoundOverloaded:
3898 // Store all of the Decls for overloaded symbols
3899 for (auto *TRD : Result)
3900 Candidate.addCorrectionDecl(TRD);
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003901 checkCorrectionVisibility(SemaRef, Candidate);
Kaelyn Takata89c881b2014-10-27 18:07:29 +00003902 if (!isCandidateViable(*CorrectionValidator, Candidate)) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003903 if (SearchNamespaces)
3904 QualifiedResults.push_back(Candidate);
3905 break;
3906 }
Kaelyn Takata20deb1d2015-01-28 00:46:09 +00003907 Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003908 return true;
3909 }
3910 return false;
3911}
3912
3913void TypoCorrectionConsumer::performQualifiedLookups() {
3914 unsigned TypoLen = Typo->getName().size();
3915 for (auto QR : QualifiedResults) {
3916 for (auto NSI : Namespaces) {
3917 DeclContext *Ctx = NSI.DeclCtx;
3918 const Type *NSType = NSI.NameSpecifier->getAsType();
3919
3920 // If the current NestedNameSpecifier refers to a class and the
3921 // current correction candidate is the name of that class, then skip
3922 // it as it is unlikely a qualified version of the class' constructor
3923 // is an appropriate correction.
Hans Wennborgdcfba332015-10-06 23:40:43 +00003924 if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() :
3925 nullptr) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003926 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
3927 continue;
3928 }
3929
3930 TypoCorrection TC(QR);
3931 TC.ClearCorrectionDecls();
3932 TC.setCorrectionSpecifier(NSI.NameSpecifier);
3933 TC.setQualifierDistance(NSI.EditDistance);
3934 TC.setCallbackDistance(0); // Reset the callback distance
3935
3936 // If the current correction candidate and namespace combination are
3937 // too far away from the original typo based on the normalized edit
3938 // distance, then skip performing a qualified name lookup.
3939 unsigned TmpED = TC.getEditDistance(true);
3940 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
3941 TypoLen / TmpED < 3)
3942 continue;
3943
3944 Result.clear();
3945 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
3946 if (!SemaRef.LookupQualifiedName(Result, Ctx))
3947 continue;
3948
3949 // Any corrections added below will be validated in subsequent
3950 // iterations of the main while() loop over the Consumer's contents.
3951 switch (Result.getResultKind()) {
3952 case LookupResult::Found:
3953 case LookupResult::FoundOverloaded: {
3954 if (SS && SS->isValid()) {
3955 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
3956 std::string OldQualified;
3957 llvm::raw_string_ostream OldOStream(OldQualified);
3958 SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
3959 OldOStream << Typo->getName();
3960 // If correction candidate would be an identical written qualified
3961 // identifer, then the existing CXXScopeSpec probably included a
3962 // typedef that didn't get accounted for properly.
3963 if (OldOStream.str() == NewQualified)
3964 break;
3965 }
3966 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
3967 TRD != TRDEnd; ++TRD) {
3968 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
3969 NSType ? NSType->getAsCXXRecordDecl()
3970 : nullptr,
3971 TRD.getPair()) == Sema::AR_accessible)
3972 TC.addCorrectionDecl(*TRD);
3973 }
Kaelyn Takata0a313022014-11-20 22:06:26 +00003974 if (TC.isResolved()) {
3975 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003976 addCorrection(TC);
Kaelyn Takata0a313022014-11-20 22:06:26 +00003977 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003978 break;
3979 }
3980 case LookupResult::NotFound:
3981 case LookupResult::NotFoundInCurrentInstantiation:
3982 case LookupResult::Ambiguous:
3983 case LookupResult::FoundUnresolvedValue:
3984 break;
3985 }
3986 }
3987 }
3988 QualifiedResults.clear();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003989}
3990
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00003991TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
3992 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
Benjamin Kramer15537272015-03-13 16:10:42 +00003993 : Context(Context), CurContextChain(buildContextChain(CurContext)) {
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00003994 if (NestedNameSpecifier *NNS =
3995 CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
3996 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
3997 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3998
3999 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
4000 }
4001 // Build the list of identifiers that would be used for an absolute
4002 // (from the global context) NestedNameSpecifier referring to the current
4003 // context.
4004 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
4005 CEnd = CurContextChain.rend();
4006 C != CEnd; ++C) {
4007 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
4008 CurContextIdentifiers.push_back(ND->getIdentifier());
4009 }
4010
4011 // Add the global context as a NestedNameSpecifier
Hans Wennborg66010132014-06-11 21:24:13 +00004012 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
4013 NestedNameSpecifier::GlobalSpecifier(Context), 1};
4014 DistanceMap[1].push_back(SI);
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004015}
4016
Kaelyn Takata7dcc0e62014-06-11 18:07:08 +00004017auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
4018 DeclContext *Start) -> DeclContextList {
Nick Lewycky0d9b3192013-04-08 21:55:21 +00004019 assert(Start && "Building a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004020 DeclContextList Chain;
Craig Topperc3ec1492014-05-26 06:22:03 +00004021 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004022 DC = DC->getLookupParent()) {
4023 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
4024 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
4025 !(ND && ND->isAnonymousNamespace()))
4026 Chain.push_back(DC->getPrimaryContext());
4027 }
4028 return Chain;
4029}
4030
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004031unsigned
4032TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
4033 DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004034 unsigned NumSpecifiers = 0;
4035 for (DeclContextList::reverse_iterator C = DeclChain.rbegin(),
4036 CEnd = DeclChain.rend();
4037 C != CEnd; ++C) {
4038 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) {
4039 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
4040 ++NumSpecifiers;
4041 } else if (RecordDecl *RD = dyn_cast_or_null<RecordDecl>(*C)) {
4042 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
4043 RD->getTypeForDecl());
4044 ++NumSpecifiers;
4045 }
4046 }
4047 return NumSpecifiers;
4048}
4049
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004050void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
4051 DeclContext *Ctx) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004052 NestedNameSpecifier *NNS = nullptr;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004053 unsigned NumSpecifiers = 0;
Kaelyn Takata0fc75192014-06-11 18:06:56 +00004054 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004055 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
4056
4057 // Eliminate common elements from the two DeclContext chains.
4058 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
4059 CEnd = CurContextChain.rend();
4060 C != CEnd && !NamespaceDeclChain.empty() &&
4061 NamespaceDeclChain.back() == *C; ++C) {
4062 NamespaceDeclChain.pop_back();
4063 }
4064
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004065 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004066 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004067
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004068 // Add an explicit leading '::' specifier if needed.
4069 if (NamespaceDeclChain.empty()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004070 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004071 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004072 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004073 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004074 } else if (NamedDecl *ND =
4075 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004076 IdentifierInfo *Name = ND->getIdentifier();
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004077 bool SameNameSpecifier = false;
4078 if (std::find(CurNameSpecifierIdentifiers.begin(),
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004079 CurNameSpecifierIdentifiers.end(),
4080 Name) != CurNameSpecifierIdentifiers.end()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004081 std::string NewNameSpecifier;
4082 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
4083 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
4084 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4085 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4086 SpecifierOStream.flush();
4087 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004088 }
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004089 if (SameNameSpecifier ||
4090 std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
4091 Name) != CurContextIdentifiers.end()) {
4092 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4093 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4094 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004095 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004096 }
4097 }
4098
4099 // If the built NestedNameSpecifier would be replacing an existing
4100 // NestedNameSpecifier, use the number of component identifiers that
4101 // would need to be changed as the edit distance instead of the number
4102 // of components in the built NestedNameSpecifier.
4103 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
4104 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
4105 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4106 NumSpecifiers = llvm::ComputeEditDistance(
Craig Topper8c2a2a02014-08-30 16:55:39 +00004107 llvm::makeArrayRef(CurNameSpecifierIdentifiers),
4108 llvm::makeArrayRef(NewNameSpecifierIdentifiers));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004109 }
4110
Hans Wennborg66010132014-06-11 21:24:13 +00004111 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
4112 DistanceMap[NumSpecifiers].push_back(SI);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004113}
4114
Douglas Gregord507d772010-10-20 03:06:34 +00004115/// \brief Perform name lookup for a possible result for typo correction.
4116static void LookupPotentialTypoResult(Sema &SemaRef,
4117 LookupResult &Res,
4118 IdentifierInfo *Name,
4119 Scope *S, CXXScopeSpec *SS,
4120 DeclContext *MemberContext,
4121 bool EnteringContext,
Richard Smithe156254d2013-08-20 20:35:18 +00004122 bool isObjCIvarLookup,
4123 bool FindHidden) {
Douglas Gregord507d772010-10-20 03:06:34 +00004124 Res.suppressDiagnostics();
4125 Res.clear();
4126 Res.setLookupName(Name);
Richard Smithe156254d2013-08-20 20:35:18 +00004127 Res.setAllowHidden(FindHidden);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004128 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00004129 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004130 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00004131 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
4132 Res.addDecl(Ivar);
4133 Res.resolveKind();
4134 return;
4135 }
4136 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004137
Douglas Gregord507d772010-10-20 03:06:34 +00004138 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
4139 Res.addDecl(Prop);
4140 Res.resolveKind();
4141 return;
4142 }
4143 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004144
Douglas Gregord507d772010-10-20 03:06:34 +00004145 SemaRef.LookupQualifiedName(Res, MemberContext);
4146 return;
4147 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004148
4149 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00004150 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004151
Douglas Gregord507d772010-10-20 03:06:34 +00004152 // Fake ivar lookup; this should really be part of
4153 // LookupParsedName.
4154 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
4155 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004156 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00004157 (Res.isSingleResult() &&
4158 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004159 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00004160 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
4161 Res.addDecl(IV);
4162 Res.resolveKind();
4163 }
4164 }
4165 }
4166}
4167
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004168/// \brief Add keywords to the consumer as possible typo corrections.
4169static void AddKeywordsToConsumer(Sema &SemaRef,
4170 TypoCorrectionConsumer &Consumer,
Richard Smithb3a1df02012-06-08 21:35:42 +00004171 Scope *S, CorrectionCandidateCallback &CCC,
4172 bool AfterNestedNameSpecifier) {
4173 if (AfterNestedNameSpecifier) {
4174 // For 'X::', we know exactly which keywords can appear next.
4175 Consumer.addKeywordResult("template");
4176 if (CCC.WantExpressionKeywords)
4177 Consumer.addKeywordResult("operator");
4178 return;
4179 }
4180
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004181 if (CCC.WantObjCSuper)
4182 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004183
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004184 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004185 // Add type-specifier keywords to the set of results.
Craig Topperd6d31ac2013-07-15 08:24:27 +00004186 static const char *const CTypeSpecs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004187 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00004188 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004189 "_Complex", "_Imaginary",
4190 // storage-specifiers as well
4191 "extern", "inline", "static", "typedef"
4192 };
4193
Craig Toppere5ce8312013-07-15 03:38:40 +00004194 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004195 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
4196 Consumer.addKeywordResult(CTypeSpecs[I]);
4197
David Blaikiebbafb8a2012-03-11 07:00:24 +00004198 if (SemaRef.getLangOpts().C99)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004199 Consumer.addKeywordResult("restrict");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004200 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004201 Consumer.addKeywordResult("bool");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004202 else if (SemaRef.getLangOpts().C99)
Douglas Gregor3b22a882011-07-01 21:27:45 +00004203 Consumer.addKeywordResult("_Bool");
4204
David Blaikiebbafb8a2012-03-11 07:00:24 +00004205 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004206 Consumer.addKeywordResult("class");
4207 Consumer.addKeywordResult("typename");
4208 Consumer.addKeywordResult("wchar_t");
4209
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004210 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004211 Consumer.addKeywordResult("char16_t");
4212 Consumer.addKeywordResult("char32_t");
4213 Consumer.addKeywordResult("constexpr");
4214 Consumer.addKeywordResult("decltype");
4215 Consumer.addKeywordResult("thread_local");
4216 }
4217 }
4218
David Blaikiebbafb8a2012-03-11 07:00:24 +00004219 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004220 Consumer.addKeywordResult("typeof");
Kaelyn Takatab04846b2014-07-28 18:14:02 +00004221 } else if (CCC.WantFunctionLikeCasts) {
4222 static const char *const CastableTypeSpecs[] = {
4223 "char", "double", "float", "int", "long", "short",
4224 "signed", "unsigned", "void"
4225 };
4226 for (auto *kw : CastableTypeSpecs)
4227 Consumer.addKeywordResult(kw);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004228 }
4229
David Blaikiebbafb8a2012-03-11 07:00:24 +00004230 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004231 Consumer.addKeywordResult("const_cast");
4232 Consumer.addKeywordResult("dynamic_cast");
4233 Consumer.addKeywordResult("reinterpret_cast");
4234 Consumer.addKeywordResult("static_cast");
4235 }
4236
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004237 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004238 Consumer.addKeywordResult("sizeof");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004239 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004240 Consumer.addKeywordResult("false");
4241 Consumer.addKeywordResult("true");
4242 }
4243
David Blaikiebbafb8a2012-03-11 07:00:24 +00004244 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topperd6d31ac2013-07-15 08:24:27 +00004245 static const char *const CXXExprs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004246 "delete", "new", "operator", "throw", "typeid"
4247 };
Craig Toppere5ce8312013-07-15 03:38:40 +00004248 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004249 for (unsigned I = 0; I != NumCXXExprs; ++I)
4250 Consumer.addKeywordResult(CXXExprs[I]);
4251
4252 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
4253 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
4254 Consumer.addKeywordResult("this");
4255
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004256 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004257 Consumer.addKeywordResult("alignof");
4258 Consumer.addKeywordResult("nullptr");
4259 }
4260 }
Jordan Rose58d54722012-06-30 21:33:57 +00004261
4262 if (SemaRef.getLangOpts().C11) {
4263 // FIXME: We should not suggest _Alignof if the alignof macro
4264 // is present.
4265 Consumer.addKeywordResult("_Alignof");
4266 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004267 }
4268
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004269 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004270 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
4271 // Statements.
Craig Topperd6d31ac2013-07-15 08:24:27 +00004272 static const char *const CStmts[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004273 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Toppere5ce8312013-07-15 03:38:40 +00004274 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004275 for (unsigned I = 0; I != NumCStmts; ++I)
4276 Consumer.addKeywordResult(CStmts[I]);
4277
David Blaikiebbafb8a2012-03-11 07:00:24 +00004278 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004279 Consumer.addKeywordResult("catch");
4280 Consumer.addKeywordResult("try");
4281 }
4282
4283 if (S && S->getBreakParent())
4284 Consumer.addKeywordResult("break");
4285
4286 if (S && S->getContinueParent())
4287 Consumer.addKeywordResult("continue");
4288
4289 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
4290 Consumer.addKeywordResult("case");
4291 Consumer.addKeywordResult("default");
4292 }
4293 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004294 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004295 Consumer.addKeywordResult("namespace");
4296 Consumer.addKeywordResult("template");
4297 }
4298
4299 if (S && S->isClassScope()) {
4300 Consumer.addKeywordResult("explicit");
4301 Consumer.addKeywordResult("friend");
4302 Consumer.addKeywordResult("mutable");
4303 Consumer.addKeywordResult("private");
4304 Consumer.addKeywordResult("protected");
4305 Consumer.addKeywordResult("public");
4306 Consumer.addKeywordResult("virtual");
4307 }
4308 }
4309
David Blaikiebbafb8a2012-03-11 07:00:24 +00004310 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004311 Consumer.addKeywordResult("using");
4312
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004313 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004314 Consumer.addKeywordResult("static_assert");
4315 }
4316 }
4317}
4318
Kaelyn Takata6c759512014-10-27 18:07:37 +00004319std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
4320 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4321 Scope *S, CXXScopeSpec *SS,
4322 std::unique_ptr<CorrectionCandidateCallback> CCC,
4323 DeclContext *MemberContext, bool EnteringContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004324 const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00004325
4326 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4327 DisableTypoCorrection)
4328 return nullptr;
4329
4330 // In Microsoft mode, don't perform typo correction in a template member
4331 // function dependent context because it interferes with the "lookup into
4332 // dependent bases of class templates" feature.
4333 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
4334 isa<CXXMethodDecl>(CurContext))
4335 return nullptr;
4336
4337 // We only attempt to correct typos for identifiers.
4338 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4339 if (!Typo)
4340 return nullptr;
4341
4342 // If the scope specifier itself was invalid, don't try to correct
4343 // typos.
4344 if (SS && SS->isInvalid())
4345 return nullptr;
4346
4347 // Never try to correct typos during template deduction or
4348 // instantiation.
4349 if (!ActiveTemplateInstantiations.empty())
4350 return nullptr;
4351
4352 // Don't try to correct 'super'.
4353 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4354 return nullptr;
4355
4356 // Abort if typo correction already failed for this specific typo.
4357 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4358 if (locs != TypoCorrectionFailures.end() &&
4359 locs->second.count(TypoName.getLoc()))
4360 return nullptr;
4361
4362 // Don't try to correct the identifier "vector" when in AltiVec mode.
4363 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4364 // remove this workaround.
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00004365 if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector"))
Kaelyn Takata6c759512014-10-27 18:07:37 +00004366 return nullptr;
4367
Nick Lewycky24653262014-12-16 21:39:02 +00004368 // Provide a stop gap for files that are just seriously broken. Trying
4369 // to correct all typos can turn into a HUGE performance penalty, causing
4370 // some files to take minutes to get rejected by the parser.
4371 unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
4372 if (Limit && TyposCorrected >= Limit)
4373 return nullptr;
4374 ++TyposCorrected;
4375
Kaelyn Takata6c759512014-10-27 18:07:37 +00004376 // If we're handling a missing symbol error, using modules, and the
4377 // special search all modules option is used, look for a missing import.
4378 if (ErrorRecovery && getLangOpts().Modules &&
4379 getLangOpts().ModulesSearchAll) {
4380 // The following has the side effect of loading the missing module.
4381 getModuleLoader().lookupMissingImports(Typo->getName(),
4382 TypoName.getLocStart());
4383 }
4384
4385 CorrectionCandidateCallback &CCCRef = *CCC;
4386 auto Consumer = llvm::make_unique<TypoCorrectionConsumer>(
4387 *this, TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
4388 EnteringContext);
4389
Kaelyn Takata6c759512014-10-27 18:07:37 +00004390 // Perform name lookup to find visible, similarly-named entities.
Nick Lewycky24653262014-12-16 21:39:02 +00004391 bool IsUnqualifiedLookup = false;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004392 DeclContext *QualifiedDC = MemberContext;
4393 if (MemberContext) {
4394 LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
4395
4396 // Look in qualified interfaces.
4397 if (OPT) {
4398 for (auto *I : OPT->quals())
4399 LookupVisibleDecls(I, LookupKind, *Consumer);
4400 }
4401 } else if (SS && SS->isSet()) {
4402 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4403 if (!QualifiedDC)
4404 return nullptr;
4405
Kaelyn Takata6c759512014-10-27 18:07:37 +00004406 LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
4407 } else {
4408 IsUnqualifiedLookup = true;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004409 }
4410
4411 // Determine whether we are going to search in the various namespaces for
4412 // corrections.
4413 bool SearchNamespaces
4414 = getLangOpts().CPlusPlus &&
4415 (IsUnqualifiedLookup || (SS && SS->isSet()));
4416
4417 if (IsUnqualifiedLookup || SearchNamespaces) {
4418 // For unqualified lookup, look through all of the names that we have
4419 // seen in this translation unit.
4420 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4421 for (const auto &I : Context.Idents)
4422 Consumer->FoundName(I.getKey());
4423
4424 // Walk through identifiers in external identifier sources.
4425 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4426 if (IdentifierInfoLookup *External
4427 = Context.Idents.getExternalIdentifierLookup()) {
4428 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4429 do {
4430 StringRef Name = Iter->Next();
4431 if (Name.empty())
4432 break;
4433
4434 Consumer->FoundName(Name);
4435 } while (true);
4436 }
4437 }
4438
4439 AddKeywordsToConsumer(*this, *Consumer, S, CCCRef, SS && SS->isNotEmpty());
4440
4441 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4442 // to search those namespaces.
4443 if (SearchNamespaces) {
4444 // Load any externally-known namespaces.
4445 if (ExternalSource && !LoadedExternalKnownNamespaces) {
4446 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
4447 LoadedExternalKnownNamespaces = true;
4448 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4449 for (auto *N : ExternalKnownNamespaces)
4450 KnownNamespaces[N] = true;
4451 }
4452
4453 Consumer->addNamespaces(KnownNamespaces);
4454 }
4455
4456 return Consumer;
4457}
4458
Douglas Gregor2d435302009-12-30 17:04:44 +00004459/// \brief Try to "correct" a typo in the source code by finding
4460/// visible declarations whose names are similar to the name that was
4461/// present in the source code.
4462///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004463/// \param TypoName the \c DeclarationNameInfo structure that contains
4464/// the name that was present in the source code along with its location.
4465///
4466/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00004467///
4468/// \param S the scope in which name lookup occurs.
4469///
4470/// \param SS the nested-name-specifier that precedes the name we're
4471/// looking for, if present.
4472///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004473/// \param CCC A CorrectionCandidateCallback object that provides further
4474/// validation of typo correction candidates. It also provides flags for
4475/// determining the set of keywords permitted.
4476///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00004477/// \param MemberContext if non-NULL, the context in which to look for
4478/// a member access expression.
4479///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004480/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00004481/// the nested-name-specifier SS.
4482///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004483/// \param OPT when non-NULL, the search for visible declarations will
4484/// also walk the protocols in the qualified interfaces of \p OPT.
4485///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004486/// \returns a \c TypoCorrection containing the corrected name if the typo
4487/// along with information such as the \c NamedDecl where the corrected name
4488/// was declared, and any additional \c NestedNameSpecifier needed to access
4489/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
4490TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
4491 Sema::LookupNameKind LookupKind,
4492 Scope *S, CXXScopeSpec *SS,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004493 std::unique_ptr<CorrectionCandidateCallback> CCC,
John Thompson2255f2c2014-04-23 12:57:01 +00004494 CorrectTypoKind Mode,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004495 DeclContext *MemberContext,
4496 bool EnteringContext,
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004497 const ObjCObjectPointerType *OPT,
4498 bool RecordFailure) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004499 assert(CCC && "CorrectTypo requires a CorrectionCandidateCallback");
4500
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004501 // Always let the ExternalSource have the first chance at correction, even
4502 // if we would otherwise have given up.
4503 if (ExternalSource) {
4504 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004505 TypoName, LookupKind, S, SS, *CCC, MemberContext, EnteringContext, OPT))
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004506 return Correction;
4507 }
4508
Kaelyn Takata6c759512014-10-27 18:07:37 +00004509 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4510 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4511 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4512 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
4513 bool ObjCMessageReceiver = CCC->WantObjCSuper && !CCC->WantRemainingKeywords;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004514
Kaelyn Takata6c759512014-10-27 18:07:37 +00004515 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Kaelyn Takata6c759512014-10-27 18:07:37 +00004516 auto Consumer = makeTypoCorrectionConsumer(
4517 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004518 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004519
Kaelyn Takata6c759512014-10-27 18:07:37 +00004520 if (!Consumer)
4521 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004522
Douglas Gregor280e1ee2010-04-14 20:04:41 +00004523 // If we haven't found anything, we're done.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004524 if (Consumer->empty())
Nick Lewycky24653262014-12-16 21:39:02 +00004525 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregor2d435302009-12-30 17:04:44 +00004526
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004527 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4528 // is not more that about a third of the length of the typo's identifier.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004529 unsigned ED = Consumer->getBestEditDistance(true);
4530 unsigned TypoLen = Typo->getName().size();
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004531 if (ED > 0 && TypoLen / ED < 3)
Nick Lewycky24653262014-12-16 21:39:02 +00004532 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004533
Kaelyn Takata6c759512014-10-27 18:07:37 +00004534 TypoCorrection BestTC = Consumer->getNextCorrection();
4535 TypoCorrection SecondBestTC = Consumer->getNextCorrection();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004536 if (!BestTC)
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004537 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004538
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004539 ED = BestTC.getEditDistance();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004540
Kaelyn Takata6c759512014-10-27 18:07:37 +00004541 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004542 // If this was an unqualified lookup and we believe the callback
4543 // object wouldn't have filtered out possible corrections, note
4544 // that no correction was found.
Nick Lewycky24653262014-12-16 21:39:02 +00004545 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004546 }
4547
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004548 // If only a single name remains, return that result.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004549 if (!SecondBestTC ||
4550 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
4551 const TypoCorrection &Result = BestTC;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004552
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00004553 // Don't correct to a keyword that's the same as the typo; the keyword
4554 // wasn't actually in scope.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004555 if (ED == 0 && Result.isKeyword())
4556 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004557
David Blaikie04ea41c2012-10-12 20:00:44 +00004558 TypoCorrection TC = Result;
4559 TC.setCorrectionRange(SS, TypoName);
Kaelyn Takataa95ebc62014-06-17 23:47:29 +00004560 checkCorrectionVisibility(*this, TC);
David Blaikie04ea41c2012-10-12 20:00:44 +00004561 return TC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004562 } else if (SecondBestTC && ObjCMessageReceiver) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004563 // Prefer 'super' when we're completing in a message-receiver
4564 // context.
4565
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004566 if (BestTC.getCorrection().getAsString() != "super") {
4567 if (SecondBestTC.getCorrection().getAsString() == "super")
4568 BestTC = SecondBestTC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004569 else if ((*Consumer)["super"].front().isKeyword())
4570 BestTC = (*Consumer)["super"].front();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004571 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004572 // Don't correct to a keyword that's the same as the typo; the keyword
4573 // wasn't actually in scope.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004574 if (BestTC.getEditDistance() == 0 ||
4575 BestTC.getCorrection().getAsString() != "super")
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004576 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004577
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004578 BestTC.setCorrectionRange(SS, TypoName);
4579 return BestTC;
Douglas Gregoraf9eb592010-10-15 13:35:25 +00004580 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004581
Kaelyn Takata73429fd2014-06-10 21:03:49 +00004582 // Record the failure's location if needed and return an empty correction. If
4583 // this was an unqualified lookup and we believe the callback object did not
4584 // filter out possible corrections, also cache the failure for the typo.
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004585 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004586}
4587
Kaelyn Takata6c759512014-10-27 18:07:37 +00004588/// \brief Try to "correct" a typo in the source code by finding
4589/// visible declarations whose names are similar to the name that was
4590/// present in the source code.
4591///
4592/// \param TypoName the \c DeclarationNameInfo structure that contains
4593/// the name that was present in the source code along with its location.
4594///
4595/// \param LookupKind the name-lookup criteria used to search for the name.
4596///
4597/// \param S the scope in which name lookup occurs.
4598///
4599/// \param SS the nested-name-specifier that precedes the name we're
4600/// looking for, if present.
4601///
4602/// \param CCC A CorrectionCandidateCallback object that provides further
4603/// validation of typo correction candidates. It also provides flags for
4604/// determining the set of keywords permitted.
4605///
4606/// \param TDG A TypoDiagnosticGenerator functor that will be used to print
4607/// diagnostics when the actual typo correction is attempted.
4608///
Kaelyn Takata8363f042014-10-27 18:07:42 +00004609/// \param TRC A TypoRecoveryCallback functor that will be used to build an
4610/// Expr from a typo correction candidate.
4611///
Kaelyn Takata6c759512014-10-27 18:07:37 +00004612/// \param MemberContext if non-NULL, the context in which to look for
4613/// a member access expression.
4614///
4615/// \param EnteringContext whether we're entering the context described by
4616/// the nested-name-specifier SS.
4617///
4618/// \param OPT when non-NULL, the search for visible declarations will
4619/// also walk the protocols in the qualified interfaces of \p OPT.
4620///
4621/// \returns a new \c TypoExpr that will later be replaced in the AST with an
4622/// Expr representing the result of performing typo correction, or nullptr if
4623/// typo correction is not possible. If nullptr is returned, no diagnostics will
4624/// be emitted and it is the responsibility of the caller to emit any that are
4625/// needed.
4626TypoExpr *Sema::CorrectTypoDelayed(
4627 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4628 Scope *S, CXXScopeSpec *SS,
4629 std::unique_ptr<CorrectionCandidateCallback> CCC,
Kaelyn Takata8363f042014-10-27 18:07:42 +00004630 TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,
Kaelyn Takata6c759512014-10-27 18:07:37 +00004631 DeclContext *MemberContext, bool EnteringContext,
4632 const ObjCObjectPointerType *OPT) {
4633 assert(CCC && "CorrectTypoDelayed requires a CorrectionCandidateCallback");
4634
4635 TypoCorrection Empty;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004636 auto Consumer = makeTypoCorrectionConsumer(
4637 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004638 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Kaelyn Takata6c759512014-10-27 18:07:37 +00004639
4640 if (!Consumer || Consumer->empty())
4641 return nullptr;
4642
4643 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4644 // is not more that about a third of the length of the typo's identifier.
4645 unsigned ED = Consumer->getBestEditDistance(true);
4646 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4647 if (ED > 0 && Typo->getName().size() / ED < 3)
4648 return nullptr;
4649
4650 ExprEvalContexts.back().NumTypos++;
Kaelyn Takata8363f042014-10-27 18:07:42 +00004651 return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC));
Kaelyn Takata6c759512014-10-27 18:07:37 +00004652}
4653
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004654void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4655 if (!CDecl) return;
4656
4657 if (isKeyword())
4658 CorrectionDecls.clear();
4659
Kaelyn Uhrainf60b55a2012-11-19 18:49:53 +00004660 CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004661
4662 if (!CorrectionName)
4663 CorrectionName = CDecl->getDeclName();
4664}
4665
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004666std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4667 if (CorrectionNameSpec) {
4668 std::string tmpBuffer;
4669 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4670 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikied4da8722013-05-14 21:04:00 +00004671 PrefixOStream << CorrectionName;
Benjamin Kramer73faad62012-04-14 08:26:28 +00004672 return PrefixOStream.str();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004673 }
4674
4675 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00004676}
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004677
Nico Weberb58e51c2014-11-19 05:21:39 +00004678bool CorrectionCandidateCallback::ValidateCandidate(
4679 const TypoCorrection &candidate) {
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004680 if (!candidate.isResolved())
4681 return true;
4682
4683 if (candidate.isKeyword())
4684 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4685 WantRemainingKeywords || WantObjCSuper;
4686
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004687 bool HasNonType = false;
4688 bool HasStaticMethod = false;
4689 bool HasNonStaticMethod = false;
4690 for (Decl *D : candidate) {
4691 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
4692 D = FTD->getTemplatedDecl();
4693 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4694 if (Method->isStatic())
4695 HasStaticMethod = true;
4696 else
4697 HasNonStaticMethod = true;
4698 }
4699 if (!isa<TypeDecl>(D))
4700 HasNonType = true;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004701 }
4702
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004703 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
4704 !candidate.getCorrectionSpecifier())
4705 return false;
4706
4707 return WantTypeSpecifiers || HasNonType;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004708}
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004709
4710FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004711 bool HasExplicitTemplateArgs,
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004712 MemberExpr *ME)
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004713 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004714 CurContext(SemaRef.CurContext), MemberFn(ME) {
Kaelyn Takatab04846b2014-07-28 18:14:02 +00004715 WantTypeSpecifiers = false;
4716 WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus && NumArgs == 1;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004717 WantRemainingKeywords = false;
4718}
4719
4720bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4721 if (!candidate.getCorrectionDecl())
4722 return candidate.isKeyword();
4723
Aaron Ballman1e606f42014-07-15 22:03:49 +00004724 for (auto *C : candidate) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004725 FunctionDecl *FD = nullptr;
Aaron Ballman1e606f42014-07-15 22:03:49 +00004726 NamedDecl *ND = C->getUnderlyingDecl();
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004727 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4728 FD = FTD->getTemplatedDecl();
4729 if (!HasExplicitTemplateArgs && !FD) {
4730 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4731 // If the Decl is neither a function nor a template function,
4732 // determine if it is a pointer or reference to a function. If so,
4733 // check against the number of arguments expected for the pointee.
4734 QualType ValType = cast<ValueDecl>(ND)->getType();
4735 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4736 ValType = ValType->getPointeeType();
4737 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
Alp Toker9cacbab2014-01-20 20:26:09 +00004738 if (FPT->getNumParams() == NumArgs)
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004739 return true;
4740 }
4741 }
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004742
4743 // Skip the current candidate if it is not a FunctionDecl or does not accept
4744 // the current number of arguments.
4745 if (!FD || !(FD->getNumParams() >= NumArgs &&
4746 FD->getMinRequiredArguments() <= NumArgs))
4747 continue;
4748
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004749 // If the current candidate is a non-static C++ method, skip the candidate
4750 // unless the method being corrected--or the current DeclContext, if the
4751 // function being corrected is not a method--is a method in the same class
4752 // or a descendent class of the candidate's parent class.
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004753 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004754 if (MemberFn || !MD->isStatic()) {
4755 CXXMethodDecl *CurMD =
4756 MemberFn
4757 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
4758 : dyn_cast_or_null<CXXMethodDecl>(CurContext);
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004759 CXXRecordDecl *CurRD =
Craig Topperc3ec1492014-05-26 06:22:03 +00004760 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004761 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
4762 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
4763 continue;
4764 }
4765 }
4766 return true;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004767 }
4768 return false;
4769}
Richard Smithf9b15102013-08-17 00:46:16 +00004770
4771void Sema::diagnoseTypo(const TypoCorrection &Correction,
4772 const PartialDiagnostic &TypoDiag,
4773 bool ErrorRecovery) {
4774 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
4775 ErrorRecovery);
4776}
4777
Richard Smithe156254d2013-08-20 20:35:18 +00004778/// Find which declaration we should import to provide the definition of
4779/// the given declaration.
Richard Smith42413142015-05-15 20:05:43 +00004780static NamedDecl *getDefinitionToImport(NamedDecl *D) {
4781 if (VarDecl *VD = dyn_cast<VarDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004782 return VD->getDefinition();
4783 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Richard Smith42413142015-05-15 20:05:43 +00004784 return FD->isDefined(FD) ? const_cast<FunctionDecl*>(FD) : nullptr;
4785 if (TagDecl *TD = dyn_cast<TagDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004786 return TD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00004787 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004788 return ID->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00004789 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004790 return PD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00004791 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004792 return getDefinitionToImport(TD->getTemplatedDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004793 return nullptr;
Richard Smithe156254d2013-08-20 20:35:18 +00004794}
4795
Richard Smithf2b1eb92015-06-15 20:15:48 +00004796void Sema::diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
4797 bool NeedDefinition, bool Recover) {
4798 assert(!isVisible(Decl) && "missing import for non-hidden decl?");
4799
4800 // Suggest importing a module providing the definition of this entity, if
4801 // possible.
4802 NamedDecl *Def = getDefinitionToImport(Decl);
4803 if (!Def)
4804 Def = Decl;
4805
4806 // FIXME: Add a Fix-It that imports the corresponding module or includes
4807 // the header.
4808 Module *Owner = getOwningModule(Decl);
4809 assert(Owner && "definition of hidden declaration is not in a module");
4810
Richard Smith35c1df52015-06-17 20:16:32 +00004811 llvm::SmallVector<Module*, 8> OwningModules;
4812 OwningModules.push_back(Owner);
Richard Smithf2b1eb92015-06-15 20:15:48 +00004813 auto Merged = Context.getModulesWithMergedDefinition(Decl);
Richard Smith35c1df52015-06-17 20:16:32 +00004814 OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end());
4815
4816 diagnoseMissingImport(Loc, Decl, Decl->getLocation(), OwningModules,
4817 NeedDefinition ? MissingImportKind::Definition
4818 : MissingImportKind::Declaration,
4819 Recover);
4820}
4821
4822void Sema::diagnoseMissingImport(SourceLocation UseLoc, NamedDecl *Decl,
4823 SourceLocation DeclLoc,
4824 ArrayRef<Module *> Modules,
4825 MissingImportKind MIK, bool Recover) {
4826 assert(!Modules.empty());
4827
4828 if (Modules.size() > 1) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00004829 std::string ModuleList;
Richard Smithf2b1eb92015-06-15 20:15:48 +00004830 unsigned N = 0;
Richard Smith35c1df52015-06-17 20:16:32 +00004831 for (Module *M : Modules) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00004832 ModuleList += "\n ";
Richard Smith35c1df52015-06-17 20:16:32 +00004833 if (++N == 5 && N != Modules.size()) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00004834 ModuleList += "[...]";
4835 break;
4836 }
4837 ModuleList += M->getFullModuleName();
4838 }
4839
Richard Smith35c1df52015-06-17 20:16:32 +00004840 Diag(UseLoc, diag::err_module_unimported_use_multiple)
4841 << (int)MIK << Decl << ModuleList;
Richard Smithf2b1eb92015-06-15 20:15:48 +00004842 } else {
Richard Smith35c1df52015-06-17 20:16:32 +00004843 Diag(UseLoc, diag::err_module_unimported_use)
4844 << (int)MIK << Decl << Modules[0]->getFullModuleName();
Richard Smithf2b1eb92015-06-15 20:15:48 +00004845 }
Richard Smith35c1df52015-06-17 20:16:32 +00004846
4847 unsigned DiagID;
4848 switch (MIK) {
4849 case MissingImportKind::Declaration:
4850 DiagID = diag::note_previous_declaration;
4851 break;
4852 case MissingImportKind::Definition:
4853 DiagID = diag::note_previous_definition;
4854 break;
4855 case MissingImportKind::DefaultArgument:
4856 DiagID = diag::note_default_argument_declared_here;
4857 break;
4858 }
4859 Diag(DeclLoc, DiagID);
Richard Smithf2b1eb92015-06-15 20:15:48 +00004860
4861 // Try to recover by implicitly importing this module.
4862 if (Recover)
Richard Smith35c1df52015-06-17 20:16:32 +00004863 createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
Richard Smithf2b1eb92015-06-15 20:15:48 +00004864}
4865
Richard Smithf9b15102013-08-17 00:46:16 +00004866/// \brief Diagnose a successfully-corrected typo. Separated from the correction
4867/// itself to allow external validation of the result, etc.
4868///
4869/// \param Correction The result of performing typo correction.
4870/// \param TypoDiag The diagnostic to produce. This will have the corrected
4871/// string added to it (and usually also a fixit).
4872/// \param PrevNote A note to use when indicating the location of the entity to
4873/// which we are correcting. Will have the correction string added to it.
4874/// \param ErrorRecovery If \c true (the default), the caller is going to
4875/// recover from the typo as if the corrected string had been typed.
4876/// In this case, \c PDiag must be an error, and we will attach a fixit
4877/// to it.
4878void Sema::diagnoseTypo(const TypoCorrection &Correction,
4879 const PartialDiagnostic &TypoDiag,
4880 const PartialDiagnostic &PrevNote,
4881 bool ErrorRecovery) {
4882 std::string CorrectedStr = Correction.getAsString(getLangOpts());
4883 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
4884 FixItHint FixTypo = FixItHint::CreateReplacement(
4885 Correction.getCorrectionRange(), CorrectedStr);
4886
Richard Smithe156254d2013-08-20 20:35:18 +00004887 // Maybe we're just missing a module import.
4888 if (Correction.requiresImport()) {
4889 NamedDecl *Decl = Correction.getCorrectionDecl();
4890 assert(Decl && "import required but no declaration to import");
4891
Richard Smithf2b1eb92015-06-15 20:15:48 +00004892 diagnoseMissingImport(Correction.getCorrectionRange().getBegin(), Decl,
4893 /*NeedDefinition*/ false, ErrorRecovery);
Richard Smithe156254d2013-08-20 20:35:18 +00004894 return;
4895 }
4896
Richard Smithf9b15102013-08-17 00:46:16 +00004897 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
4898 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
4899
4900 NamedDecl *ChosenDecl =
Craig Topperc3ec1492014-05-26 06:22:03 +00004901 Correction.isKeyword() ? nullptr : Correction.getCorrectionDecl();
Richard Smithf9b15102013-08-17 00:46:16 +00004902 if (PrevNote.getDiagID() && ChosenDecl)
4903 Diag(ChosenDecl->getLocation(), PrevNote)
4904 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
4905}
Kaelyn Takata6c759512014-10-27 18:07:37 +00004906
Kaelyn Takata8363f042014-10-27 18:07:42 +00004907TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
4908 TypoDiagnosticGenerator TDG,
4909 TypoRecoveryCallback TRC) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00004910 assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
4911 auto TE = new (Context) TypoExpr(Context.DependentTy);
4912 auto &State = DelayedTypos[TE];
4913 State.Consumer = std::move(TCC);
4914 State.DiagHandler = std::move(TDG);
Kaelyn Takata8363f042014-10-27 18:07:42 +00004915 State.RecoveryHandler = std::move(TRC);
Kaelyn Takata6c759512014-10-27 18:07:37 +00004916 return TE;
4917}
4918
4919const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
4920 auto Entry = DelayedTypos.find(TE);
4921 assert(Entry != DelayedTypos.end() &&
4922 "Failed to get the state for a TypoExpr!");
4923 return Entry->second;
4924}
4925
4926void Sema::clearDelayedTypo(TypoExpr *TE) {
4927 DelayedTypos.erase(TE);
4928}