blob: a020dcf14d698dd62ab9e4ecb7012013f7bb7ba8 [file] [log] [blame]
Nick Lewycky4b81fc872015-10-18 20:32:12 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
Douglas Gregor34074322009-01-14 22:20:51 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
Hans Wennborgdcfba332015-10-06 23:40:43 +000014
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
Douglas Gregor960b5bc2009-01-15 00:26:24 +000016#include "clang/AST/ASTContext.h"
Richard Smithd9ba2242015-05-07 03:54:19 +000017#include "clang/AST/ASTMutationListener.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000019#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
Nick Lewyckyc3921482012-04-03 21:44:08 +000021#include "clang/AST/DeclLookups.h"
Douglas Gregor34074322009-01-14 22:20:51 +000022#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000023#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000024#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000025#include "clang/AST/ExprCXX.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Douglas Gregor34074322009-01-14 22:20:51 +000027#include "clang/Basic/LangOptions.h"
Richard Smith42413142015-05-15 20:05:43 +000028#include "clang/Lex/HeaderSearch.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000029#include "clang/Lex/ModuleLoader.h"
Richard Smith4caa4492015-05-15 02:34:32 +000030#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/ExternalSemaSource.h"
33#include "clang/Sema/Overload.h"
34#include "clang/Sema/Scope.h"
35#include "clang/Sema/ScopeInfo.h"
36#include "clang/Sema/Sema.h"
37#include "clang/Sema/SemaInternal.h"
38#include "clang/Sema/TemplateDeduction.h"
39#include "clang/Sema/TypoCorrection.h"
Douglas Gregor34074322009-01-14 22:20:51 +000040#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "llvm/ADT/SetVector.h"
Douglas Gregore254f902009-02-04 00:32:51 +000042#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0afa7f62010-10-14 20:34:08 +000043#include "llvm/ADT/StringMap.h"
Chris Lattner83cfc7c2011-07-18 01:54:02 +000044#include "llvm/ADT/TinyPtrVector.h"
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +000045#include "llvm/ADT/edit_distance.h"
John McCall6538c932009-10-10 05:48:19 +000046#include "llvm/Support/ErrorHandling.h"
Nick Lewycky13668f22012-04-03 20:26:45 +000047#include <algorithm>
48#include <iterator>
Douglas Gregor0afa7f62010-10-14 20:34:08 +000049#include <limits>
Douglas Gregor2d435302009-12-30 17:04:44 +000050#include <list>
Douglas Gregorc2fa1692011-06-28 16:20:02 +000051#include <map>
Nick Lewycky13668f22012-04-03 20:26:45 +000052#include <set>
53#include <utility>
54#include <vector>
Douglas Gregor34074322009-01-14 22:20:51 +000055
56using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000057using namespace sema;
Douglas Gregor34074322009-01-14 22:20:51 +000058
John McCallf6c8a4e2009-11-10 07:01:13 +000059namespace {
60 class UnqualUsingEntry {
61 const DeclContext *Nominated;
62 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000063
John McCallf6c8a4e2009-11-10 07:01:13 +000064 public:
65 UnqualUsingEntry(const DeclContext *Nominated,
66 const DeclContext *CommonAncestor)
67 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
68 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000069
John McCallf6c8a4e2009-11-10 07:01:13 +000070 const DeclContext *getCommonAncestor() const {
71 return CommonAncestor;
72 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000073
John McCallf6c8a4e2009-11-10 07:01:13 +000074 const DeclContext *getNominatedNamespace() const {
75 return Nominated;
76 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000077
John McCallf6c8a4e2009-11-10 07:01:13 +000078 // Sort by the pointer value of the common ancestor.
79 struct Comparator {
80 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
81 return L.getCommonAncestor() < R.getCommonAncestor();
82 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000083
John McCallf6c8a4e2009-11-10 07:01:13 +000084 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
85 return E.getCommonAncestor() < DC;
86 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000087
John McCallf6c8a4e2009-11-10 07:01:13 +000088 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
89 return DC < E.getCommonAncestor();
90 }
91 };
92 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000093
John McCallf6c8a4e2009-11-10 07:01:13 +000094 /// A collection of using directives, as used by C++ unqualified
95 /// lookup.
96 class UnqualUsingDirectiveSet {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000097 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000098
John McCallf6c8a4e2009-11-10 07:01:13 +000099 ListTy list;
100 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000101
John McCallf6c8a4e2009-11-10 07:01:13 +0000102 public:
103 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +0000104
John McCallf6c8a4e2009-11-10 07:01:13 +0000105 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000106 // C++ [namespace.udir]p1:
John McCallf6c8a4e2009-11-10 07:01:13 +0000107 // During unqualified name lookup, the names appear as if they
108 // were declared in the nearest enclosing namespace which contains
109 // both the using-directive and the nominated namespace.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000110 DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
John McCallf6c8a4e2009-11-10 07:01:13 +0000111 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +0000112
John McCallf6c8a4e2009-11-10 07:01:13 +0000113 for (; S; S = S->getParent()) {
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000114 // C++ [namespace.udir]p1:
115 // A using-directive shall not appear in class scope, but may
116 // appear in namespace scope or in block scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000117 DeclContext *Ctx = S->getEntity();
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000118 if (Ctx && Ctx->isFileContext()) {
119 visit(Ctx, Ctx);
120 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
Aaron Ballman5df6aa42014-03-17 17:03:37 +0000121 for (auto *I : S->using_directives())
122 visit(I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000123 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000124 }
125 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000126
127 // Visits a context and collect all of its using directives
128 // recursively. Treats all using directives as if they were
129 // declared in the context.
130 //
131 // A given context is only every visited once, so it is important
132 // that contexts be visited from the inside out in order to get
133 // the effective DCs right.
134 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
David Blaikie82e95a32014-11-19 07:49:47 +0000135 if (!visited.insert(DC).second)
John McCallf6c8a4e2009-11-10 07:01:13 +0000136 return;
137
138 addUsingDirectives(DC, EffectiveDC);
139 }
140
141 // Visits a using directive and collects all of its using
142 // directives recursively. Treats all using directives as if they
143 // were declared in the effective DC.
144 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
145 DeclContext *NS = UD->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +0000146 if (!visited.insert(NS).second)
John McCallf6c8a4e2009-11-10 07:01:13 +0000147 return;
148
149 addUsingDirective(UD, EffectiveDC);
150 addUsingDirectives(NS, EffectiveDC);
151 }
152
153 // Adds all the using directives in a context (and those nominated
154 // by its using directives, transitively) as if they appeared in
155 // the given effective context.
156 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Nick Lewycky4b81fc872015-10-18 20:32:12 +0000157 SmallVector<DeclContext*, 4> queue;
John McCallf6c8a4e2009-11-10 07:01:13 +0000158 while (true) {
Aaron Ballman804a7fb2014-03-17 17:14:12 +0000159 for (auto UD : DC->using_directives()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000160 DeclContext *NS = UD->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +0000161 if (visited.insert(NS).second) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000162 addUsingDirective(UD, EffectiveDC);
163 queue.push_back(NS);
164 }
165 }
166
167 if (queue.empty())
168 return;
169
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000170 DC = queue.pop_back_val();
John McCallf6c8a4e2009-11-10 07:01:13 +0000171 }
172 }
173
174 // Add a using directive as if it had been declared in the given
175 // context. This helps implement C++ [namespace.udir]p3:
176 // The using-directive is transitive: if a scope contains a
177 // using-directive that nominates a second namespace that itself
178 // contains using-directives, the effect is as if the
179 // using-directives from the second namespace also appeared in
180 // the first.
181 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
182 // Find the common ancestor between the effective context and
183 // the nominated namespace.
184 DeclContext *Common = UD->getNominatedNamespace();
185 while (!Common->Encloses(EffectiveDC))
186 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000187 Common = Common->getPrimaryContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000188
John McCallf6c8a4e2009-11-10 07:01:13 +0000189 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
190 }
191
192 void done() {
193 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
194 }
195
John McCallf6c8a4e2009-11-10 07:01:13 +0000196 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000197
John McCallf6c8a4e2009-11-10 07:01:13 +0000198 const_iterator begin() const { return list.begin(); }
199 const_iterator end() const { return list.end(); }
200
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000201 llvm::iterator_range<const_iterator>
John McCallf6c8a4e2009-11-10 07:01:13 +0000202 getNamespacesFor(DeclContext *DC) const {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000203 return llvm::make_range(std::equal_range(begin(), end(),
204 DC->getPrimaryContext(),
205 UnqualUsingEntry::Comparator()));
John McCallf6c8a4e2009-11-10 07:01:13 +0000206 }
207 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000208} // end anonymous namespace
Douglas Gregor889ceb72009-02-03 19:21:40 +0000209
Douglas Gregor889ceb72009-02-03 19:21:40 +0000210// Retrieve the set of identifier namespaces that correspond to a
211// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000212static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
213 bool CPlusPlus,
214 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000215 unsigned IDNS = 0;
216 switch (NameKind) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +0000217 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000218 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000219 case Sema::LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +0000220 case Sema::LookupLocalFriendName:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000221 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000222 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000223 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000224 if (Redeclaration)
225 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCallea305ed2009-12-18 10:40:03 +0000226 }
Richard Smith541b38b2013-09-20 01:15:31 +0000227 if (Redeclaration)
228 IDNS |= Decl::IDNS_LocalExtern;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000229 break;
230
John McCallb9467b62010-04-24 01:30:58 +0000231 case Sema::LookupOperatorName:
232 // Operator lookup is its own crazy thing; it is not the same
233 // as (e.g.) looking up an operator name for redeclaration.
234 assert(!Redeclaration && "cannot do redeclaration operator lookup");
235 IDNS = Decl::IDNS_NonMemberOperator;
236 break;
237
Douglas Gregor889ceb72009-02-03 19:21:40 +0000238 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000239 if (CPlusPlus) {
240 IDNS = Decl::IDNS_Type;
241
242 // When looking for a redeclaration of a tag name, we add:
243 // 1) TagFriend to find undeclared friend decls
244 // 2) Namespace because they can't "overload" with tag decls.
245 // 3) Tag because it includes class templates, which can't
246 // "overload" with tag decls.
247 if (Redeclaration)
248 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
249 } else {
250 IDNS = Decl::IDNS_Tag;
251 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000252 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000253
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000254 case Sema::LookupLabel:
255 IDNS = Decl::IDNS_Label;
256 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000257
Douglas Gregor889ceb72009-02-03 19:21:40 +0000258 case Sema::LookupMemberName:
259 IDNS = Decl::IDNS_Member;
260 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000261 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000262 break;
263
264 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000265 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
266 break;
267
Douglas Gregor889ceb72009-02-03 19:21:40 +0000268 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000269 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000270 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000271
John McCall84d87672009-12-10 09:41:52 +0000272 case Sema::LookupUsingDeclName:
Richard Smith83e78f52014-04-11 01:03:38 +0000273 assert(Redeclaration && "should only be used for redecl lookup");
274 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |
275 Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend |
276 Decl::IDNS_LocalExtern;
John McCall84d87672009-12-10 09:41:52 +0000277 break;
278
Douglas Gregor79947a22009-04-24 00:11:27 +0000279 case Sema::LookupObjCProtocolName:
280 IDNS = Decl::IDNS_ObjCProtocol;
281 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000282
Douglas Gregor39982192010-08-15 06:18:01 +0000283 case Sema::LookupAnyName:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000284 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor39982192010-08-15 06:18:01 +0000285 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
286 | Decl::IDNS_Type;
287 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000288 }
289 return IDNS;
290}
291
John McCallea305ed2009-12-18 10:40:03 +0000292void LookupResult::configure() {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000293 IDNS = getIDNS(LookupKind, getSema().getLangOpts().CPlusPlus,
John McCallea305ed2009-12-18 10:40:03 +0000294 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000295
Richard Smithbdd14642014-02-04 01:14:30 +0000296 // If we're looking for one of the allocation or deallocation
297 // operators, make sure that the implicitly-declared new and delete
298 // operators can be found.
299 switch (NameInfo.getName().getCXXOverloadedOperator()) {
300 case OO_New:
301 case OO_Delete:
302 case OO_Array_New:
303 case OO_Array_Delete:
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000304 getSema().DeclareGlobalNewDelete();
Richard Smithbdd14642014-02-04 01:14:30 +0000305 break;
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000306
Richard Smithbdd14642014-02-04 01:14:30 +0000307 default:
308 break;
309 }
Douglas Gregor15197662013-04-03 23:06:26 +0000310
Richard Smithbdd14642014-02-04 01:14:30 +0000311 // Compiler builtins are always visible, regardless of where they end
312 // up being declared.
313 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
314 if (unsigned BuiltinID = Id->getBuiltinID()) {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000315 if (!getSema().Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
Richard Smithbdd14642014-02-04 01:14:30 +0000316 AllowHidden = true;
Douglas Gregor15197662013-04-03 23:06:26 +0000317 }
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000318 }
John McCallea305ed2009-12-18 10:40:03 +0000319}
320
Alp Tokerc1086762013-12-07 13:51:35 +0000321bool LookupResult::sanity() const {
Richard Smithf97ad222014-04-01 18:33:50 +0000322 // This function is never called by NDEBUG builds.
John McCall19c1bfd2010-08-25 05:32:35 +0000323 assert(ResultKind != NotFound || Decls.size() == 0);
324 assert(ResultKind != Found || Decls.size() == 1);
325 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
326 (Decls.size() == 1 &&
327 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
328 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
329 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000330 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
331 Ambiguity == AmbiguousBaseSubobjectTypes)));
Craig Topperc3ec1492014-05-26 06:22:03 +0000332 assert((Paths != nullptr) == (ResultKind == Ambiguous &&
333 (Ambiguity == AmbiguousBaseSubobjectTypes ||
334 Ambiguity == AmbiguousBaseSubobjects)));
Alp Tokerc1086762013-12-07 13:51:35 +0000335 return true;
John McCall19c1bfd2010-08-25 05:32:35 +0000336}
John McCall19c1bfd2010-08-25 05:32:35 +0000337
John McCall9f3059a2009-10-09 21:13:30 +0000338// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000339void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000340 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000341}
342
Richard Smith3876cc82013-10-30 01:02:04 +0000343/// Get a representative context for a declaration such that two declarations
344/// will have the same context if they were found within the same scope.
Benjamin Kramerfc58b042013-11-01 11:50:55 +0000345static DeclContext *getContextForScopeMatching(Decl *D) {
Richard Smith3876cc82013-10-30 01:02:04 +0000346 // For function-local declarations, use that function as the context. This
347 // doesn't account for scopes within the function; the caller must deal with
348 // those.
349 DeclContext *DC = D->getLexicalDeclContext();
350 if (DC->isFunctionOrMethod())
351 return DC;
352
353 // Otherwise, look at the semantic context of the declaration. The
354 // declaration must have been found there.
355 return D->getDeclContext()->getRedeclContext();
356}
357
Richard Smith826711d2015-07-29 23:38:25 +0000358/// \brief Determine whether \p D is a better lookup result than \p Existing,
359/// given that they declare the same entity.
Richard Smithcd31b852015-08-22 21:37:34 +0000360static bool isPreferredLookupResult(Sema &S, Sema::LookupNameKind Kind,
Richard Smith826711d2015-07-29 23:38:25 +0000361 NamedDecl *D, NamedDecl *Existing) {
362 // When looking up redeclarations of a using declaration, prefer a using
363 // shadow declaration over any other declaration of the same entity.
364 if (Kind == Sema::LookupUsingDeclName && isa<UsingShadowDecl>(D) &&
365 !isa<UsingShadowDecl>(Existing))
366 return true;
367
368 auto *DUnderlying = D->getUnderlyingDecl();
369 auto *EUnderlying = Existing->getUnderlyingDecl();
370
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;
Richard Smith2dbe4042015-11-04 19:26:32 +0000466 bool HasTag = false, HasFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000467 bool HasFunctionTemplate = false, HasUnresolved = false;
Richard Smith2dbe4042015-11-04 19:26:32 +0000468 NamedDecl *HasNonFunction = nullptr;
469
470 llvm::SmallVector<NamedDecl*, 4> EquivalentNonFunctions;
John McCall9f3059a2009-10-09 21:13:30 +0000471
472 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000473
John McCall9f3059a2009-10-09 21:13:30 +0000474 unsigned I = 0;
475 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000476 NamedDecl *D = Decls[I]->getUnderlyingDecl();
477 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000478
Argyrios Kyrtzidis1fcd7fd2013-02-22 06:58:37 +0000479 // Ignore an invalid declaration unless it's the only one left.
Richard Smith5cd86f82015-11-03 03:13:11 +0000480 if (D->isInvalidDecl() && !(I == 0 && N == 1)) {
Argyrios Kyrtzidis1fcd7fd2013-02-22 06:58:37 +0000481 Decls[I] = Decls[--N];
482 continue;
483 }
484
Richard Smith826711d2015-07-29 23:38:25 +0000485 llvm::Optional<unsigned> ExistingI;
486
Douglas Gregor13e65872010-08-11 14:45:53 +0000487 // Redeclarations of types via typedef can occur both within a scope
488 // and, through using declarations and directives, across scopes. There is
489 // no ambiguity if they all refer to the same type, so unique based on the
490 // canonical type.
491 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
Richard Smith826711d2015-07-29 23:38:25 +0000492 // FIXME: Why are nested type declarations treated differently?
Douglas Gregor13e65872010-08-11 14:45:53 +0000493 if (!TD->getDeclContext()->isRecord()) {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000494 QualType T = getSema().Context.getTypeDeclType(TD);
Richard Smith826711d2015-07-29 23:38:25 +0000495 auto UniqueResult = UniqueTypes.insert(
496 std::make_pair(getSema().Context.getCanonicalType(T), I));
497 if (!UniqueResult.second) {
498 // The type is not unique.
499 ExistingI = UniqueResult.first->second;
Douglas Gregor13e65872010-08-11 14:45:53 +0000500 }
501 }
502 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000503
Richard Smith826711d2015-07-29 23:38:25 +0000504 // For non-type declarations, check for a prior lookup result naming this
505 // canonical declaration.
506 if (!ExistingI) {
507 auto UniqueResult = Unique.insert(std::make_pair(D, I));
508 if (!UniqueResult.second) {
509 // We've seen this entity before.
510 ExistingI = UniqueResult.first->second;
Richard Smitha534a312015-07-21 23:54:07 +0000511 }
Richard Smith826711d2015-07-29 23:38:25 +0000512 }
513
514 if (ExistingI) {
515 // This is not a unique lookup result. Pick one of the results and
516 // discard the other.
Richard Smithcd31b852015-08-22 21:37:34 +0000517 if (isPreferredLookupResult(getSema(), getLookupKind(), Decls[I],
Richard Smith826711d2015-07-29 23:38:25 +0000518 Decls[*ExistingI]))
519 Decls[*ExistingI] = Decls[I];
520 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000521 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000522 }
523
Douglas Gregor13e65872010-08-11 14:45:53 +0000524 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000525
Douglas Gregor13e65872010-08-11 14:45:53 +0000526 if (isa<UnresolvedUsingValueDecl>(D)) {
527 HasUnresolved = true;
528 } else if (isa<TagDecl>(D)) {
529 if (HasTag)
530 Ambiguous = true;
531 UniqueTagIndex = I;
532 HasTag = true;
533 } else if (isa<FunctionTemplateDecl>(D)) {
534 HasFunction = true;
535 HasFunctionTemplate = true;
536 } else if (isa<FunctionDecl>(D)) {
537 HasFunction = true;
538 } else {
Richard Smith2dbe4042015-11-04 19:26:32 +0000539 if (HasNonFunction) {
540 // If we're about to create an ambiguity between two declarations that
541 // are equivalent, but one is an internal linkage declaration from one
542 // module and the other is an internal linkage declaration from another
543 // module, just skip it.
544 if (getSema().isEquivalentInternalLinkageDeclaration(HasNonFunction,
545 D)) {
546 EquivalentNonFunctions.push_back(D);
547 Decls[I] = Decls[--N];
548 continue;
549 }
550
Douglas Gregor13e65872010-08-11 14:45:53 +0000551 Ambiguous = true;
Richard Smith2dbe4042015-11-04 19:26:32 +0000552 }
553 HasNonFunction = D;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000554 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000555 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000556 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000557
John McCall9f3059a2009-10-09 21:13:30 +0000558 // C++ [basic.scope.hiding]p2:
559 // A class name or enumeration name can be hidden by the name of
560 // an object, function, or enumerator declared in the same
561 // scope. If a class or enumeration name and an object, function,
562 // or enumerator are declared in the same scope (in any order)
563 // with the same name, the class or enumeration name is hidden
564 // wherever the object, function, or enumerator name is visible.
565 // But it's still an error if there are distinct tag types found,
566 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000567 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000568 (HasFunction || HasNonFunction || HasUnresolved)) {
Richard Smith3876cc82013-10-30 01:02:04 +0000569 if (getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
570 getContextForScopeMatching(Decls[UniqueTagIndex ? 0 : N - 1])))
Douglas Gregore63d0872010-10-23 16:06:17 +0000571 Decls[UniqueTagIndex] = Decls[--N];
572 else
573 Ambiguous = true;
574 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000575
Richard Smith2dbe4042015-11-04 19:26:32 +0000576 // FIXME: This diagnostic should really be delayed until we're done with
577 // the lookup result, in case the ambiguity is resolved by the caller.
578 if (!EquivalentNonFunctions.empty() && !Ambiguous)
579 getSema().diagnoseEquivalentInternalLinkageDeclarations(
580 getNameLoc(), HasNonFunction, EquivalentNonFunctions);
581
John McCall9f3059a2009-10-09 21:13:30 +0000582 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000583
John McCall80053822009-12-03 00:58:24 +0000584 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000585 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000586
John McCall9f3059a2009-10-09 21:13:30 +0000587 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000588 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000589 else if (HasUnresolved)
590 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000591 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000592 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000593 else
John McCall27b18f82009-11-17 02:14:36 +0000594 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000595}
596
John McCall5cebab12009-11-18 07:57:50 +0000597void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000598 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000599 for (I = P.begin(), E = P.end(); I != E; ++I)
David Blaikieff7d47a2012-12-19 00:45:41 +0000600 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
601 DE = I->Decls.end(); DI != DE; ++DI)
John McCall9f3059a2009-10-09 21:13:30 +0000602 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000603}
604
John McCall5cebab12009-11-18 07:57:50 +0000605void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000606 Paths = new CXXBasePaths;
607 Paths->swap(P);
608 addDeclsFromBasePaths(*Paths);
609 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000610 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000611}
612
John McCall5cebab12009-11-18 07:57:50 +0000613void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000614 Paths = new CXXBasePaths;
615 Paths->swap(P);
616 addDeclsFromBasePaths(*Paths);
617 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000618 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000619}
620
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000621void LookupResult::print(raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000622 Out << Decls.size() << " result(s)";
623 if (isAmbiguous()) Out << ", ambiguous";
624 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000625
John McCall9f3059a2009-10-09 21:13:30 +0000626 for (iterator I = begin(), E = end(); I != E; ++I) {
627 Out << "\n";
628 (*I)->print(Out, 2);
629 }
630}
631
Douglas Gregord3a59182010-02-12 05:48:04 +0000632/// \brief Lookup a builtin function, when name lookup would otherwise
633/// fail.
634static bool LookupBuiltin(Sema &S, LookupResult &R) {
635 Sema::LookupNameKind NameKind = R.getLookupKind();
636
637 // If we didn't find a use of this identifier, and if the identifier
638 // corresponds to a compiler builtin, create the decl object for the builtin
639 // now, injecting it into translation unit scope, and return it.
640 if (NameKind == Sema::LookupOrdinaryName ||
641 NameKind == Sema::LookupRedeclarationWithLinkage) {
642 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
643 if (II) {
Nico Webere1687c52013-06-20 21:44:55 +0000644 if (S.getLangOpts().CPlusPlus11 && S.getLangOpts().GNUMode &&
645 II == S.getFloat128Identifier()) {
646 // libstdc++4.7's type_traits expects type __float128 to exist, so
647 // insert a dummy type to make that header build in gnu++11 mode.
648 R.addDecl(S.getASTContext().getFloat128StubType());
649 return true;
650 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000651 if (S.getLangOpts().CPlusPlus && NameKind == Sema::LookupOrdinaryName &&
652 II == S.getASTContext().getMakeIntegerSeqName()) {
653 R.addDecl(S.getASTContext().getMakeIntegerSeqDecl());
654 return true;
655 }
Nico Webere1687c52013-06-20 21:44:55 +0000656
Douglas Gregord3a59182010-02-12 05:48:04 +0000657 // If this is a builtin on this (or all) targets, create the decl.
658 if (unsigned BuiltinID = II->getBuiltinID()) {
659 // In C++, we don't have any predefined library functions like
660 // 'malloc'. Instead, we'll just error.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000661 if (S.getLangOpts().CPlusPlus &&
Douglas Gregord3a59182010-02-12 05:48:04 +0000662 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
663 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000664
665 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
666 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000667 R.isForRedeclaration(),
668 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000669 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000670 return true;
671 }
Douglas Gregord3a59182010-02-12 05:48:04 +0000672 }
673 }
674 }
675
676 return false;
677}
678
Douglas Gregor7454c562010-07-02 20:37:36 +0000679/// \brief Determine whether we can declare a special member function within
680/// the class at this point.
Richard Smith7d125a12012-11-27 21:20:31 +0000681static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +0000682 // We need to have a definition for the class.
683 if (!Class->getDefinition() || Class->isDependentContext())
684 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000685
Douglas Gregor7454c562010-07-02 20:37:36 +0000686 // We can't be in the middle of defining the class.
Richard Smith7d125a12012-11-27 21:20:31 +0000687 return !Class->isBeingDefined();
Douglas Gregor7454c562010-07-02 20:37:36 +0000688}
689
690void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smith7d125a12012-11-27 21:20:31 +0000691 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregora6d69502010-07-02 23:41:54 +0000692 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000693
694 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000695 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000696 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000697
Douglas Gregora6d69502010-07-02 23:41:54 +0000698 // If the copy constructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000699 if (Class->needsImplicitCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +0000700 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000701
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000702 // If the copy assignment operator has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000703 if (Class->needsImplicitCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000704 DeclareImplicitCopyAssignment(Class);
705
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000706 if (getLangOpts().CPlusPlus11) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000707 // If the move constructor has not yet been declared, do so now.
708 if (Class->needsImplicitMoveConstructor())
709 DeclareImplicitMoveConstructor(Class); // might not actually do it
710
711 // If the move assignment operator has not yet been declared, do so now.
712 if (Class->needsImplicitMoveAssignment())
713 DeclareImplicitMoveAssignment(Class); // might not actually do it
714 }
715
Douglas Gregor7454c562010-07-02 20:37:36 +0000716 // If the destructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000717 if (Class->needsImplicitDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000718 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000719}
720
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000721/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000722/// special member function.
723static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
724 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000725 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000726 case DeclarationName::CXXDestructorName:
727 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000728
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000729 case DeclarationName::CXXOperatorName:
730 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000731
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000732 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000733 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000734 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000735
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000736 return false;
737}
738
739/// \brief If there are any implicit member functions with the given name
740/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000741static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000742 DeclarationName Name,
743 const DeclContext *DC) {
744 if (!DC)
745 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000746
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000747 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000748 case DeclarationName::CXXConstructorName:
749 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith7d125a12012-11-27 21:20:31 +0000750 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000751 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000752 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000753 S.DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +0000754 if (Record->needsImplicitCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000755 S.DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000756 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000757 Record->needsImplicitMoveConstructor())
758 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000759 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000760 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000761
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000762 case DeclarationName::CXXDestructorName:
763 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith2be35f52012-12-01 02:35:44 +0000764 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smith7d125a12012-11-27 21:20:31 +0000765 CanDeclareSpecialMemberFunction(Record))
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000766 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000767 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000768
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000769 case DeclarationName::CXXOperatorName:
770 if (Name.getCXXOverloadedOperator() != OO_Equal)
771 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000772
Sebastian Redl22653ba2011-08-30 19:58:05 +0000773 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smith7d125a12012-11-27 21:20:31 +0000774 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000775 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smith2be35f52012-12-01 02:35:44 +0000776 if (Record->needsImplicitCopyAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000777 S.DeclareImplicitCopyAssignment(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000778 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000779 Record->needsImplicitMoveAssignment())
780 S.DeclareImplicitMoveAssignment(Class);
781 }
782 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000783 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000784
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000785 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000786 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000787 }
788}
Douglas Gregor7454c562010-07-02 20:37:36 +0000789
John McCall9f3059a2009-10-09 21:13:30 +0000790// Adds all qualifying matches for a name within a decl context to the
791// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000792static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000793 bool Found = false;
794
Douglas Gregor7454c562010-07-02 20:37:36 +0000795 // Lazily declare C++ special member functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000796 if (S.getLangOpts().CPlusPlus)
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000797 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000798
Douglas Gregor7454c562010-07-02 20:37:36 +0000799 // Perform lookup into this declaration context.
Richard Smithcf4bdde2015-02-21 02:45:19 +0000800 DeclContext::lookup_result DR = DC->lookup(R.getLookupName());
801 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E;
David Blaikieff7d47a2012-12-19 00:45:41 +0000802 ++I) {
John McCall401982f2010-01-20 21:53:11 +0000803 NamedDecl *D = *I;
Douglas Gregor4a814562011-12-14 16:03:29 +0000804 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000805 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000806 Found = true;
807 }
808 }
John McCall9f3059a2009-10-09 21:13:30 +0000809
Douglas Gregord3a59182010-02-12 05:48:04 +0000810 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
811 return true;
812
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000813 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000814 != DeclarationName::CXXConversionFunctionName ||
815 R.getLookupName().getCXXNameType()->isDependentType() ||
816 !isa<CXXRecordDecl>(DC))
817 return Found;
818
819 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000820 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000821 // name lookup. Instead, any conversion function templates visible in the
822 // context of the use are considered. [...]
823 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000824 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000825 return Found;
826
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +0000827 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
828 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruth3a693b72010-01-31 11:44:02 +0000829 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
830 if (!ConvTemplate)
831 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000832
Chandler Carruth3a693b72010-01-31 11:44:02 +0000833 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000834 // add the conversion function template. When we deduce template
835 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000836 // type of the new declaration with the type of the function template.
837 if (R.isForRedeclaration()) {
838 R.addDecl(ConvTemplate);
839 Found = true;
840 continue;
841 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000842
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000843 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000844 // [...] For each such operator, if argument deduction succeeds
845 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000846 // name lookup.
847 //
848 // When referencing a conversion function for any purpose other than
849 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000850 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000851 // specialization into the result set. We do this to avoid forcing all
852 // callers to perform special deduction for conversion functions.
Craig Toppere6706e42012-09-19 02:26:47 +0000853 TemplateDeductionInfo Info(R.getNameLoc());
Craig Topperc3ec1492014-05-26 06:22:03 +0000854 FunctionDecl *Specialization = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000855
856 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000857 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
858 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000859
Chandler Carruth3a693b72010-01-31 11:44:02 +0000860 // Compute the type of the function that we would expect the conversion
861 // function to have, if it were to match the name given.
862 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000863 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
Reid Kleckner78af0702013-08-27 23:08:25 +0000864 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
Richard Smith8acb4282014-07-31 21:57:55 +0000865 EPI.ExceptionSpec = EST_None;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000866 QualType ExpectedType
867 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000868 None, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000869
Chandler Carruth3a693b72010-01-31 11:44:02 +0000870 // Perform template argument deduction against the type that we would
871 // expect the function to have.
Craig Topperc3ec1492014-05-26 06:22:03 +0000872 if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
Chandler Carruth3a693b72010-01-31 11:44:02 +0000873 Specialization, Info)
874 == Sema::TDK_Success) {
875 R.addDecl(Specialization);
876 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000877 }
878 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000879
John McCall9f3059a2009-10-09 21:13:30 +0000880 return Found;
881}
882
John McCallf6c8a4e2009-11-10 07:01:13 +0000883// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000884static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000885CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000886 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000887
888 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
889
John McCallf6c8a4e2009-11-10 07:01:13 +0000890 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000891 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000892
John McCallf6c8a4e2009-11-10 07:01:13 +0000893 // Perform direct name lookup into the namespaces nominated by the
894 // using directives whose common ancestor is this namespace.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000895 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
896 if (LookupDirect(S, R, UUE.getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000897 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000898
899 R.resolveKind();
900
901 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000902}
903
904static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000905 if (DeclContext *Ctx = S->getEntity())
Douglas Gregor700792c2009-02-05 19:25:20 +0000906 return Ctx->isFileContext();
907 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000908}
Douglas Gregored8f2882009-01-30 01:04:22 +0000909
Douglas Gregor66230062010-03-15 14:33:29 +0000910// Find the next outer declaration context from this scope. This
911// routine actually returns the semantic outer context, which may
912// differ from the lexical context (encoded directly in the Scope
913// stack) when we are parsing a member of a class template. In this
914// case, the second element of the pair will be true, to indicate that
915// name lookup should continue searching in this semantic context when
916// it leaves the current template parameter scope.
917static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000918 DeclContext *DC = S->getEntity();
Craig Topperc3ec1492014-05-26 06:22:03 +0000919 DeclContext *Lexical = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000920 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000921 OuterS = OuterS->getParent()) {
922 if (OuterS->getEntity()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000923 Lexical = OuterS->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +0000924 break;
925 }
926 }
927
928 // C++ [temp.local]p8:
929 // In the definition of a member of a class template that appears
930 // outside of the namespace containing the class template
931 // definition, the name of a template-parameter hides the name of
932 // a member of this namespace.
933 //
934 // Example:
935 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000936 // namespace N {
937 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000938 //
939 // template<class T> class B {
940 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000941 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000942 // }
943 //
944 // template<class C> void N::B<C>::f(C) {
945 // C b; // C is the template parameter, not N::C
946 // }
947 //
948 // In this example, the lexical context we return is the
949 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000950 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000951 !S->getParent()->isTemplateParamScope())
952 return std::make_pair(Lexical, false);
953
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000954 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000955 // For the example, this is the scope for the template parameters of
956 // template<class C>.
957 Scope *OutermostTemplateScope = S->getParent();
958 while (OutermostTemplateScope->getParent() &&
959 OutermostTemplateScope->getParent()->isTemplateParamScope())
960 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000961
Douglas Gregor66230062010-03-15 14:33:29 +0000962 // Find the namespace context in which the original scope occurs. In
963 // the example, this is namespace N.
964 DeclContext *Semantic = DC;
965 while (!Semantic->isFileContext())
966 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000967
Douglas Gregor66230062010-03-15 14:33:29 +0000968 // Find the declaration context just outside of the template
969 // parameter scope. This is the context in which the template is
970 // being lexically declaration (a namespace context). In the
971 // example, this is the global scope.
972 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
973 Lexical->Encloses(Semantic))
974 return std::make_pair(Semantic, true);
975
976 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000977}
978
Richard Smith541b38b2013-09-20 01:15:31 +0000979namespace {
980/// An RAII object to specify that we want to find block scope extern
981/// declarations.
982struct FindLocalExternScope {
983 FindLocalExternScope(LookupResult &R)
984 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
985 Decl::IDNS_LocalExtern) {
986 R.setFindLocalExtern(R.getIdentifierNamespace() & Decl::IDNS_Ordinary);
987 }
988 void restore() {
989 R.setFindLocalExtern(OldFindLocalExtern);
990 }
991 ~FindLocalExternScope() {
992 restore();
993 }
994 LookupResult &R;
995 bool OldFindLocalExtern;
996};
Hans Wennborgdcfba332015-10-06 23:40:43 +0000997} // end anonymous namespace
Richard Smith541b38b2013-09-20 01:15:31 +0000998
John McCall27b18f82009-11-17 02:14:36 +0000999bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001000 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +00001001
1002 DeclarationName Name = R.getLookupName();
Richard Smith1c34fb72013-08-13 18:18:50 +00001003 Sema::LookupNameKind NameKind = R.getLookupKind();
John McCall27b18f82009-11-17 02:14:36 +00001004
Douglas Gregor330b9cf2010-07-02 21:50:04 +00001005 // If this is the name of an implicitly-declared special member function,
1006 // go through the scope stack to implicitly declare
1007 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
1008 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +00001009 if (DeclContext *DC = PreS->getEntity())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00001010 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
1011 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001012
Douglas Gregor330b9cf2010-07-02 21:50:04 +00001013 // Implicitly declare member functions with the name we're looking for, if in
1014 // fact we are in a scope where it matters.
1015
Douglas Gregor889ceb72009-02-03 19:21:40 +00001016 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +00001017 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +00001018 I = IdResolver.begin(Name),
1019 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001020
Douglas Gregor889ceb72009-02-03 19:21:40 +00001021 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001022 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +00001023 // ...During unqualified name lookup (3.4.1), the names appear as if
1024 // they were declared in the nearest enclosing namespace which contains
1025 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +00001026 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +00001027 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +00001028 //
1029 // For example:
1030 // namespace A { int i; }
1031 // void foo() {
1032 // int i;
1033 // {
1034 // using namespace A;
1035 // ++i; // finds local 'i', A::i appears at global scope
1036 // }
1037 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +00001038 //
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001039 UnqualUsingDirectiveSet UDirs;
1040 bool VisitedUsingDirectives = false;
Richard Smith1c34fb72013-08-13 18:18:50 +00001041 bool LeftStartingScope = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00001042 DeclContext *OutsideOfTemplateParamDC = nullptr;
Richard Smith541b38b2013-09-20 01:15:31 +00001043
1044 // When performing a scope lookup, we want to find local extern decls.
1045 FindLocalExternScope FindLocals(R);
1046
Douglas Gregor700792c2009-02-05 19:25:20 +00001047 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00001048 DeclContext *Ctx = S->getEntity();
Douglas Gregor3e51e172010-05-20 20:58:56 +00001049
Douglas Gregor889ceb72009-02-03 19:21:40 +00001050 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +00001051 bool Found = false;
John McCall48871652010-08-21 09:40:31 +00001052 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001053 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Richard Smith1c34fb72013-08-13 18:18:50 +00001054 if (NameKind == LookupRedeclarationWithLinkage) {
1055 // Determine whether this (or a previous) declaration is
1056 // out-of-scope.
1057 if (!LeftStartingScope && !Initial->isDeclScope(*I))
1058 LeftStartingScope = true;
1059
1060 // If we found something outside of our starting scope that
Richard Smith9a00bbf2013-10-16 21:12:00 +00001061 // does not have linkage, skip it. If it's a template parameter,
1062 // we still find it, so we can diagnose the invalid redeclaration.
1063 if (LeftStartingScope && !((*I)->hasLinkage()) &&
1064 !(*I)->isTemplateParameter()) {
Richard Smith1c34fb72013-08-13 18:18:50 +00001065 R.setShadowed();
1066 continue;
1067 }
1068 }
1069
John McCall9f3059a2009-10-09 21:13:30 +00001070 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +00001071 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001072 }
1073 }
John McCall9f3059a2009-10-09 21:13:30 +00001074 if (Found) {
1075 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +00001076 if (S->isClassScope())
1077 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
1078 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +00001079 return true;
1080 }
1081
Richard Smith1c34fb72013-08-13 18:18:50 +00001082 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
Richard Smith114394f2013-08-09 04:35:01 +00001083 // C++11 [class.friend]p11:
1084 // If a friend declaration appears in a local class and the name
1085 // specified is an unqualified name, a prior declaration is
1086 // looked up without considering scopes that are outside the
1087 // innermost enclosing non-class scope.
1088 return false;
1089 }
1090
Douglas Gregor66230062010-03-15 14:33:29 +00001091 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1092 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1093 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001094 // found nothing, so look into the contexts between the
Douglas Gregor66230062010-03-15 14:33:29 +00001095 // lexical and semantic declaration contexts returned by
1096 // findOuterContext(). This implements the name lookup behavior
1097 // of C++ [temp.local]p8.
1098 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +00001099 OutsideOfTemplateParamDC = nullptr;
Douglas Gregor66230062010-03-15 14:33:29 +00001100 }
1101
1102 if (Ctx) {
1103 DeclContext *OuterCtx;
1104 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001105 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregor66230062010-03-15 14:33:29 +00001106 if (SearchAfterTemplateScope)
1107 OutsideOfTemplateParamDC = OuterCtx;
1108
Douglas Gregorea166062010-03-15 15:26:48 +00001109 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +00001110 // We do not directly look into transparent contexts, since
1111 // those entities will be found in the nearest enclosing
1112 // non-transparent context.
1113 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +00001114 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +00001115
1116 // We do not look directly into function or method contexts,
1117 // since all of the local variables and parameters of the
1118 // function/method are present within the Scope.
1119 if (Ctx->isFunctionOrMethod()) {
1120 // If we have an Objective-C instance method, look for ivars
1121 // in the corresponding interface.
1122 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
1123 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1124 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1125 ObjCInterfaceDecl *ClassDeclared;
1126 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001127 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +00001128 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001129 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1130 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +00001131 R.resolveKind();
1132 return true;
1133 }
1134 }
1135 }
1136 }
1137
1138 continue;
1139 }
1140
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001141 // If this is a file context, we need to perform unqualified name
1142 // lookup considering using directives.
1143 if (Ctx->isFileContext()) {
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001144 // If we haven't handled using directives yet, do so now.
1145 if (!VisitedUsingDirectives) {
1146 // Add using directives from this context up to the top level.
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001147 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1148 if (UCtx->isTransparentContext())
1149 continue;
1150
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001151 UDirs.visit(UCtx, UCtx);
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001152 }
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001153
1154 // Find the innermost file scope, so we can add using directives
1155 // from local scopes.
1156 Scope *InnermostFileScope = S;
1157 while (InnermostFileScope &&
1158 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1159 InnermostFileScope = InnermostFileScope->getParent();
1160 UDirs.visitScopeChain(Initial, InnermostFileScope);
1161
1162 UDirs.done();
1163
1164 VisitedUsingDirectives = true;
1165 }
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001166
1167 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1168 R.resolveKind();
1169 return true;
1170 }
1171
1172 continue;
1173 }
1174
Douglas Gregor7f737c02009-09-10 16:57:35 +00001175 // Perform qualified name lookup into this context.
1176 // FIXME: In some cases, we know that every name that could be found by
1177 // this qualified name lookup will also be on the identifier chain. For
1178 // example, inside a class without any base classes, we never need to
1179 // perform qualified lookup because all of the members are on top of the
1180 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001181 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +00001182 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +00001183 }
Douglas Gregor700792c2009-02-05 19:25:20 +00001184 }
Douglas Gregored8f2882009-01-30 01:04:22 +00001185 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001186
John McCallf6c8a4e2009-11-10 07:01:13 +00001187 // Stop if we ran out of scopes.
1188 // FIXME: This really, really shouldn't be happening.
1189 if (!S) return false;
1190
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001191 // If we are looking for members, no need to look into global/namespace scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00001192 if (NameKind == LookupMemberName)
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001193 return false;
1194
Douglas Gregor700792c2009-02-05 19:25:20 +00001195 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +00001196 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +00001197 //
Mike Stump87c57ac2009-05-16 07:39:55 +00001198 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1199 // don't build it for each lookup!
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001200 if (!VisitedUsingDirectives) {
1201 UDirs.visitScopeChain(Initial, S);
1202 UDirs.done();
1203 }
Richard Smith541b38b2013-09-20 01:15:31 +00001204
1205 // If we're not performing redeclaration lookup, do not look for local
1206 // extern declarations outside of a function scope.
1207 if (!R.isForRedeclaration())
1208 FindLocals.restore();
1209
Douglas Gregor700792c2009-02-05 19:25:20 +00001210 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +00001211 // Unqualified name lookup in C++ requires looking into scopes
1212 // that aren't strictly lexical, and therefore we walk through the
1213 // context as well as walking through the scopes.
1214 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001215 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +00001216 bool Found = false;
John McCall48871652010-08-21 09:40:31 +00001217 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001218 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001219 // We found something. Look for anything else in our scope
1220 // with this same name and in an acceptable identifier
1221 // namespace, so that we can construct an overload set if we
1222 // need to.
John McCall9f3059a2009-10-09 21:13:30 +00001223 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +00001224 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001225 }
1226 }
1227
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001228 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +00001229 R.resolveKind();
1230 return true;
1231 }
1232
Ted Kremenekc37877d2013-10-08 17:08:03 +00001233 DeclContext *Ctx = S->getEntity();
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001234 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1235 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1236 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001237 // found nothing, so look into the contexts between the
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001238 // lexical and semantic declaration contexts returned by
1239 // findOuterContext(). This implements the name lookup behavior
1240 // of C++ [temp.local]p8.
1241 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +00001242 OutsideOfTemplateParamDC = nullptr;
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001243 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001244
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001245 if (Ctx) {
1246 DeclContext *OuterCtx;
1247 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001248 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001249 if (SearchAfterTemplateScope)
1250 OutsideOfTemplateParamDC = OuterCtx;
1251
1252 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1253 // We do not directly look into transparent contexts, since
1254 // those entities will be found in the nearest enclosing
1255 // non-transparent context.
1256 if (Ctx->isTransparentContext())
1257 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001258
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001259 // If we have a context, and it's not a context stashed in the
1260 // template parameter scope for an out-of-line definition, also
1261 // look into that context.
1262 if (!(Found && S && S->isTemplateParamScope())) {
1263 assert(Ctx->isFileContext() &&
1264 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001265
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001266 // Look into context considering using-directives.
1267 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1268 Found = true;
1269 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001270
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001271 if (Found) {
1272 R.resolveKind();
1273 return true;
1274 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001275
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001276 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1277 return false;
1278 }
1279 }
1280
Douglas Gregor3ce74932010-02-05 07:07:10 +00001281 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001282 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001283 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001284
John McCall9f3059a2009-10-09 21:13:30 +00001285 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001286}
1287
Richard Smith0e5d7b82013-07-25 23:08:39 +00001288/// \brief Find the declaration that a class temploid member specialization was
1289/// instantiated from, or the member itself if it is an explicit specialization.
1290static Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) {
1291 return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom();
1292}
1293
Richard Smith42413142015-05-15 20:05:43 +00001294Module *Sema::getOwningModule(Decl *Entity) {
1295 // If it's imported, grab its owning module.
1296 Module *M = Entity->getImportedOwningModule();
1297 if (M || !isa<NamedDecl>(Entity) || !cast<NamedDecl>(Entity)->isHidden())
1298 return M;
1299 assert(!Entity->isFromASTFile() &&
1300 "hidden entity from AST file has no owning module");
1301
Richard Smith87bb5692015-06-09 00:35:49 +00001302 if (!getLangOpts().ModulesLocalVisibility) {
1303 // If we're not tracking visibility locally, the only way a declaration
1304 // can be hidden and local is if it's hidden because it's parent is (for
1305 // instance, maybe this is a lazily-declared special member of an imported
1306 // class).
1307 auto *Parent = cast<NamedDecl>(Entity->getDeclContext());
1308 assert(Parent->isHidden() && "unexpectedly hidden decl");
1309 return getOwningModule(Parent);
1310 }
1311
Richard Smith42413142015-05-15 20:05:43 +00001312 // It's local and hidden; grab or compute its owning module.
1313 M = Entity->getLocalOwningModule();
1314 if (M)
1315 return M;
1316
1317 if (auto *Containing =
1318 PP.getModuleContainingLocation(Entity->getLocation())) {
1319 M = Containing;
1320 } else if (Entity->isInvalidDecl() || Entity->getLocation().isInvalid()) {
1321 // Don't bother tracking visibility for invalid declarations with broken
1322 // locations.
1323 cast<NamedDecl>(Entity)->setHidden(false);
1324 } else {
1325 // We need to assign a module to an entity that exists outside of any
1326 // module, so that we can hide it from modules that we textually enter.
1327 // Invent a fake module for all such entities.
1328 if (!CachedFakeTopLevelModule) {
1329 CachedFakeTopLevelModule =
1330 PP.getHeaderSearchInfo().getModuleMap().findOrCreateModule(
1331 "<top-level>", nullptr, false, false).first;
1332
1333 auto &SrcMgr = PP.getSourceManager();
1334 SourceLocation StartLoc =
1335 SrcMgr.getLocForStartOfFile(SrcMgr.getMainFileID());
1336 auto &TopLevel =
1337 VisibleModulesStack.empty() ? VisibleModules : VisibleModulesStack[0];
1338 TopLevel.setVisible(CachedFakeTopLevelModule, StartLoc);
1339 }
1340
1341 M = CachedFakeTopLevelModule;
1342 }
1343
1344 if (M)
1345 Entity->setLocalOwningModule(M);
1346 return M;
1347}
1348
Richard Smithd9ba2242015-05-07 03:54:19 +00001349void Sema::makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc) {
Richard Smith87bb5692015-06-09 00:35:49 +00001350 if (auto *M = PP.getModuleContainingLocation(Loc))
1351 Context.mergeDefinitionIntoModule(ND, M);
1352 else
1353 // We're not building a module; just make the definition visible.
1354 ND->setHidden(false);
Richard Smith63e09bf2015-06-17 20:39:41 +00001355
1356 // If ND is a template declaration, make the template parameters
1357 // visible too. They're not (necessarily) within a mergeable DeclContext.
1358 if (auto *TD = dyn_cast<TemplateDecl>(ND))
1359 for (auto *Param : *TD->getTemplateParameters())
1360 makeMergedDefinitionVisible(Param, Loc);
Richard Smithd9ba2242015-05-07 03:54:19 +00001361}
1362
Richard Smith0e5d7b82013-07-25 23:08:39 +00001363/// \brief Find the module in which the given declaration was defined.
Richard Smith42413142015-05-15 20:05:43 +00001364static Module *getDefiningModule(Sema &S, Decl *Entity) {
Richard Smith0e5d7b82013-07-25 23:08:39 +00001365 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1366 // If this function was instantiated from a template, the defining module is
1367 // the module containing the pattern.
1368 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1369 Entity = Pattern;
1370 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
Reid Klecknere7367d62014-10-14 20:28:40 +00001371 if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
1372 Entity = Pattern;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001373 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1374 if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo())
1375 Entity = getInstantiatedFrom(ED, MSInfo);
1376 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1377 // FIXME: Map from variable template specializations back to the template.
1378 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo())
1379 Entity = getInstantiatedFrom(VD, MSInfo);
1380 }
1381
1382 // Walk up to the containing context. That might also have been instantiated
1383 // from a template.
1384 DeclContext *Context = Entity->getDeclContext();
1385 if (Context->isFileContext())
Richard Smith42413142015-05-15 20:05:43 +00001386 return S.getOwningModule(Entity);
1387 return getDefiningModule(S, cast<Decl>(Context));
Richard Smith0e5d7b82013-07-25 23:08:39 +00001388}
1389
1390llvm::DenseSet<Module*> &Sema::getLookupModules() {
1391 unsigned N = ActiveTemplateInstantiations.size();
1392 for (unsigned I = ActiveTemplateInstantiationLookupModules.size();
1393 I != N; ++I) {
Richard Smith42413142015-05-15 20:05:43 +00001394 Module *M =
1395 getDefiningModule(*this, ActiveTemplateInstantiations[I].Entity);
Richard Smith0e5d7b82013-07-25 23:08:39 +00001396 if (M && !LookupModulesCache.insert(M).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00001397 M = nullptr;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001398 ActiveTemplateInstantiationLookupModules.push_back(M);
1399 }
1400 return LookupModulesCache;
1401}
1402
Richard Smith42413142015-05-15 20:05:43 +00001403bool Sema::hasVisibleMergedDefinition(NamedDecl *Def) {
1404 for (Module *Merged : Context.getModulesWithMergedDefinition(Def))
1405 if (isModuleVisible(Merged))
1406 return true;
1407 return false;
1408}
1409
Richard Smithe7bd6de2015-06-10 20:30:23 +00001410template<typename ParmDecl>
Richard Smith35c1df52015-06-17 20:16:32 +00001411static bool
1412hasVisibleDefaultArgument(Sema &S, const ParmDecl *D,
1413 llvm::SmallVectorImpl<Module *> *Modules) {
Richard Smithe7bd6de2015-06-10 20:30:23 +00001414 if (!D->hasDefaultArgument())
1415 return false;
1416
1417 while (D) {
1418 auto &DefaultArg = D->getDefaultArgStorage();
1419 if (!DefaultArg.isInherited() && S.isVisible(D))
1420 return true;
1421
Richard Smith63e09bf2015-06-17 20:39:41 +00001422 if (!DefaultArg.isInherited() && Modules) {
1423 auto *NonConstD = const_cast<ParmDecl*>(D);
1424 Modules->push_back(S.getOwningModule(NonConstD));
1425 const auto &Merged = S.Context.getModulesWithMergedDefinition(NonConstD);
1426 Modules->insert(Modules->end(), Merged.begin(), Merged.end());
1427 }
Richard Smith35c1df52015-06-17 20:16:32 +00001428
Richard Smithe7bd6de2015-06-10 20:30:23 +00001429 // If there was a previous default argument, maybe its parameter is visible.
1430 D = DefaultArg.getInheritedFrom();
1431 }
1432 return false;
1433}
1434
Richard Smith35c1df52015-06-17 20:16:32 +00001435bool Sema::hasVisibleDefaultArgument(const NamedDecl *D,
1436 llvm::SmallVectorImpl<Module *> *Modules) {
Richard Smithe7bd6de2015-06-10 20:30:23 +00001437 if (auto *P = dyn_cast<TemplateTypeParmDecl>(D))
Richard Smith35c1df52015-06-17 20:16:32 +00001438 return ::hasVisibleDefaultArgument(*this, P, Modules);
Richard Smithe7bd6de2015-06-10 20:30:23 +00001439 if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))
Richard Smith35c1df52015-06-17 20:16:32 +00001440 return ::hasVisibleDefaultArgument(*this, P, Modules);
1441 return ::hasVisibleDefaultArgument(*this, cast<TemplateTemplateParmDecl>(D),
1442 Modules);
Richard Smithe7bd6de2015-06-10 20:30:23 +00001443}
1444
Richard Smith0e5d7b82013-07-25 23:08:39 +00001445/// \brief Determine whether a declaration is visible to name lookup.
1446///
1447/// This routine determines whether the declaration D is visible in the current
1448/// lookup context, taking into account the current template instantiation
1449/// stack. During template instantiation, a declaration is visible if it is
1450/// visible from a module containing any entity on the template instantiation
1451/// path (by instantiating a template, you allow it to see the declarations that
1452/// your module can see, including those later on in your module).
1453bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001454 assert(D->isHidden() && "should not call this: not in slow case");
Richard Smith5196a172015-08-24 03:38:11 +00001455 Module *DeclModule = nullptr;
1456
1457 if (SemaRef.getLangOpts().ModulesLocalVisibility) {
1458 DeclModule = SemaRef.getOwningModule(D);
1459 if (!DeclModule) {
1460 // getOwningModule() may have decided the declaration should not be hidden.
1461 assert(!D->isHidden() && "hidden decl not from a module");
Richard Smith42413142015-05-15 20:05:43 +00001462 return true;
Richard Smith5196a172015-08-24 03:38:11 +00001463 }
1464
1465 // If the owning module is visible, and the decl is not module private,
1466 // then the decl is visible too. (Module private is ignored within the same
1467 // top-level module.)
1468 if ((!D->isFromASTFile() || !D->isModulePrivate()) &&
1469 (SemaRef.isModuleVisible(DeclModule) ||
1470 SemaRef.hasVisibleMergedDefinition(D)))
Richard Smith42413142015-05-15 20:05:43 +00001471 return true;
1472 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001473
Richard Smithbe3980b2015-03-27 00:41:57 +00001474 // If this declaration is not at namespace scope nor module-private,
1475 // then it is visible if its lexical parent has a visible definition.
1476 DeclContext *DC = D->getLexicalDeclContext();
1477 if (!D->isModulePrivate() &&
1478 DC && !DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) {
Richard Smithc7d48d12015-05-20 17:50:35 +00001479 // For a parameter, check whether our current template declaration's
1480 // lexical context is visible, not whether there's some other visible
1481 // definition of it, because parameters aren't "within" the definition.
1482 if ((D->isTemplateParameter() || isa<ParmVarDecl>(D))
1483 ? isVisible(SemaRef, cast<NamedDecl>(DC))
1484 : SemaRef.hasVisibleDefinition(cast<NamedDecl>(DC))) {
Richard Smith42413142015-05-15 20:05:43 +00001485 if (SemaRef.ActiveTemplateInstantiations.empty() &&
1486 // FIXME: Do something better in this case.
1487 !SemaRef.getLangOpts().ModulesLocalVisibility) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001488 // Cache the fact that this declaration is implicitly visible because
1489 // its parent has a visible definition.
1490 D->setHidden(false);
1491 }
1492 return true;
1493 }
1494 return false;
1495 }
1496
Richard Smith0e5d7b82013-07-25 23:08:39 +00001497 // Find the extra places where we need to look.
1498 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
1499 if (LookupModules.empty())
1500 return false;
1501
Richard Smith5196a172015-08-24 03:38:11 +00001502 if (!DeclModule) {
1503 DeclModule = SemaRef.getOwningModule(D);
1504 assert(DeclModule && "hidden decl not from a module");
1505 }
1506
Richard Smith0e5d7b82013-07-25 23:08:39 +00001507 // If our lookup set contains the decl's module, it's visible.
1508 if (LookupModules.count(DeclModule))
1509 return true;
1510
1511 // If the declaration isn't exported, it's not visible in any other module.
1512 if (D->isModulePrivate())
1513 return false;
1514
1515 // Check whether DeclModule is transitively exported to an import of
1516 // the lookup set.
1517 for (llvm::DenseSet<Module *>::iterator I = LookupModules.begin(),
1518 E = LookupModules.end();
1519 I != E; ++I)
1520 if ((*I)->isModuleVisible(DeclModule))
1521 return true;
1522 return false;
1523}
1524
Richard Smith42413142015-05-15 20:05:43 +00001525bool Sema::isVisibleSlow(const NamedDecl *D) {
1526 return LookupResult::isVisible(*this, const_cast<NamedDecl*>(D));
1527}
1528
Douglas Gregor4a814562011-12-14 16:03:29 +00001529/// \brief Retrieve the visible declaration corresponding to D, if any.
1530///
1531/// This routine determines whether the declaration D is visible in the current
1532/// module, with the current imports. If not, it checks whether any
1533/// redeclaration of D is visible, and if so, returns that declaration.
Richard Smith0e5d7b82013-07-25 23:08:39 +00001534///
Douglas Gregor4a814562011-12-14 16:03:29 +00001535/// \returns D, or a visible previous declaration of D, whichever is more recent
1536/// and visible. If no declaration of D is visible, returns null.
Richard Smithe156254d2013-08-20 20:35:18 +00001537static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
1538 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
Richard Smith0e5d7b82013-07-25 23:08:39 +00001539
Aaron Ballman86c93902014-03-06 23:45:36 +00001540 for (auto RD : D->redecls()) {
1541 if (auto ND = dyn_cast<NamedDecl>(RD)) {
Richard Smithe8292b12015-02-10 03:28:10 +00001542 // FIXME: This is wrong in the case where the previous declaration is not
1543 // visible in the same scope as D. This needs to be done much more
1544 // carefully.
Richard Smithe156254d2013-08-20 20:35:18 +00001545 if (LookupResult::isVisible(SemaRef, ND))
Douglas Gregor54079202012-01-06 22:05:37 +00001546 return ND;
1547 }
Douglas Gregor4a814562011-12-14 16:03:29 +00001548 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001549
Craig Topperc3ec1492014-05-26 06:22:03 +00001550 return nullptr;
Douglas Gregor4a814562011-12-14 16:03:29 +00001551}
1552
Richard Smithe156254d2013-08-20 20:35:18 +00001553NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +00001554 return findAcceptableDecl(getSema(), D);
Richard Smithe156254d2013-08-20 20:35:18 +00001555}
1556
Douglas Gregor34074322009-01-14 22:20:51 +00001557/// @brief Perform unqualified name lookup starting from a given
1558/// scope.
1559///
1560/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1561/// used to find names within the current scope. For example, 'x' in
1562/// @code
1563/// int x;
1564/// int f() {
1565/// return x; // unqualified name look finds 'x' in the global scope
1566/// }
1567/// @endcode
1568///
1569/// Different lookup criteria can find different names. For example, a
1570/// particular scope can have both a struct and a function of the same
1571/// name, and each can be found by certain lookup criteria. For more
1572/// information about lookup criteria, see the documentation for the
1573/// class LookupCriteria.
1574///
1575/// @param S The scope from which unqualified name lookup will
1576/// begin. If the lookup criteria permits, name lookup may also search
1577/// in the parent scopes.
1578///
James Dennett91738ff2012-06-22 10:32:46 +00001579/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1580/// look up and the lookup kind), and is updated with the results of lookup
1581/// including zero or more declarations and possibly additional information
1582/// used to diagnose ambiguities.
Douglas Gregor34074322009-01-14 22:20:51 +00001583///
James Dennett91738ff2012-06-22 10:32:46 +00001584/// @returns \c true if lookup succeeded and false otherwise.
John McCall27b18f82009-11-17 02:14:36 +00001585bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1586 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001587 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001588
John McCall27b18f82009-11-17 02:14:36 +00001589 LookupNameKind NameKind = R.getLookupKind();
1590
David Blaikiebbafb8a2012-03-11 07:00:24 +00001591 if (!getLangOpts().CPlusPlus) {
Douglas Gregor34074322009-01-14 22:20:51 +00001592 // Unqualified name lookup in C/Objective-C is purely lexical, so
1593 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001594 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001595 // Find the nearest non-transparent declaration scope.
1596 while (!(S->getFlags() & Scope::DeclScope) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001597 (S->getEntity() && S->getEntity()->isTransparentContext()))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001598 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001599 }
1600
Richard Smith541b38b2013-09-20 01:15:31 +00001601 // When performing a scope lookup, we want to find local extern decls.
1602 FindLocalExternScope FindLocals(R);
1603
Douglas Gregor34074322009-01-14 22:20:51 +00001604 // Scan up the scope chain looking for a decl that matches this
1605 // identifier that is in the appropriate namespace. This search
1606 // should not take long, as shadowing of names is uncommon, and
1607 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001608 bool LeftStartingScope = false;
1609
Douglas Gregored8f2882009-01-30 01:04:22 +00001610 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001611 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001612 I != IEnd; ++I)
Richard Smith0e5d7b82013-07-25 23:08:39 +00001613 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001614 if (NameKind == LookupRedeclarationWithLinkage) {
1615 // Determine whether this (or a previous) declaration is
1616 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001617 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001618 LeftStartingScope = true;
1619
1620 // If we found something outside of our starting scope that
1621 // does not have linkage, skip it.
Richard Smith1c34fb72013-08-13 18:18:50 +00001622 if (LeftStartingScope && !((*I)->hasLinkage())) {
1623 R.setShadowed();
Douglas Gregoreddf4332009-02-24 20:03:32 +00001624 continue;
Richard Smith1c34fb72013-08-13 18:18:50 +00001625 }
Douglas Gregoreddf4332009-02-24 20:03:32 +00001626 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001627 else if (NameKind == LookupObjCImplicitSelfParam &&
1628 !isa<ImplicitParamDecl>(*I))
1629 continue;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001630
Douglas Gregor4a814562011-12-14 16:03:29 +00001631 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001632
Douglas Gregorb59643b2012-01-03 23:26:26 +00001633 // Check whether there are any other declarations with the same name
1634 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001635 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001636 // Find the scope in which this declaration was declared (if it
1637 // actually exists in a Scope).
1638 while (S && !S->isDeclScope(D))
1639 S = S->getParent();
1640
1641 // If the scope containing the declaration is the translation unit,
1642 // then we'll need to perform our checks based on the matching
1643 // DeclContexts rather than matching scopes.
1644 if (S && isNamespaceOrTranslationUnitScope(S))
Craig Topperc3ec1492014-05-26 06:22:03 +00001645 S = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001646
1647 // Compute the DeclContext, if we need it.
Craig Topperc3ec1492014-05-26 06:22:03 +00001648 DeclContext *DC = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001649 if (!S)
1650 DC = (*I)->getDeclContext()->getRedeclContext();
1651
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001652 IdentifierResolver::iterator LastI = I;
1653 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001654 if (S) {
1655 // Match based on scope.
1656 if (!S->isDeclScope(*LastI))
1657 break;
1658 } else {
1659 // Match based on DeclContext.
1660 DeclContext *LastDC
1661 = (*LastI)->getDeclContext()->getRedeclContext();
1662 if (!LastDC->Equals(DC))
1663 break;
1664 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001665
1666 // If the declaration is in the right namespace and visible, add it.
1667 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1668 R.addDecl(LastD);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001669 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001670
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001671 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001672 }
Richard Smith541b38b2013-09-20 01:15:31 +00001673
John McCall9f3059a2009-10-09 21:13:30 +00001674 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001675 }
Douglas Gregor34074322009-01-14 22:20:51 +00001676 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001677 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001678 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001679 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001680 }
1681
1682 // If we didn't find a use of this identifier, and if the identifier
1683 // corresponds to a compiler builtin, create the decl object for the builtin
1684 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001685 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1686 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001687
Axel Naumann016538a2011-02-24 16:47:47 +00001688 // If we didn't find a use of this identifier, the ExternalSource
1689 // may be able to handle the situation.
1690 // Note: some lookup failures are expected!
1691 // See e.g. R.isForRedeclaration().
1692 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001693}
1694
John McCall6538c932009-10-10 05:48:19 +00001695/// @brief Perform qualified name lookup in the namespaces nominated by
1696/// using directives by the given context.
1697///
1698/// C++98 [namespace.qual]p2:
James Dennett51a8d8b2012-06-19 21:05:49 +00001699/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6538c932009-10-10 05:48:19 +00001700/// (where X is the global namespace), let S be the set of all
1701/// declarations of m in X and in the transitive closure of all
1702/// namespaces nominated by using-directives in X and its used
1703/// namespaces, except that using-directives are ignored in any
1704/// namespace, including X, directly containing one or more
1705/// declarations of m. No namespace is searched more than once in
1706/// the lookup of a name. If S is the empty set, the program is
1707/// ill-formed. Otherwise, if S has exactly one member, or if the
1708/// context of the reference is a using-declaration
1709/// (namespace.udecl), S is the required set of declarations of
1710/// m. Otherwise if the use of m is not one that allows a unique
1711/// declaration to be chosen from S, the program is ill-formed.
James Dennett51a8d8b2012-06-19 21:05:49 +00001712///
John McCall6538c932009-10-10 05:48:19 +00001713/// C++98 [namespace.qual]p5:
1714/// During the lookup of a qualified namespace member name, if the
1715/// lookup finds more than one declaration of the member, and if one
1716/// declaration introduces a class name or enumeration name and the
1717/// other declarations either introduce the same object, the same
1718/// enumerator or a set of functions, the non-type name hides the
1719/// class or enumeration name if and only if the declarations are
1720/// from the same namespace; otherwise (the declarations are from
1721/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001722static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001723 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001724 assert(StartDC->isFileContext() && "start context is not a file context");
1725
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001726 DeclContext::udir_range UsingDirectives = StartDC->using_directives();
1727 if (UsingDirectives.begin() == UsingDirectives.end()) return false;
John McCall6538c932009-10-10 05:48:19 +00001728
1729 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001730 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001731 Visited.insert(StartDC);
1732
1733 // We have not yet looked into these namespaces, much less added
1734 // their "using-children" to the queue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001735 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001736
1737 // We have already looked into the initial namespace; seed the queue
1738 // with its using-children.
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001739 for (auto *I : UsingDirectives) {
1740 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +00001741 if (Visited.insert(ND).second)
John McCall6538c932009-10-10 05:48:19 +00001742 Queue.push_back(ND);
1743 }
1744
1745 // The easiest way to implement the restriction in [namespace.qual]p5
1746 // is to check whether any of the individual results found a tag
1747 // and, if so, to declare an ambiguity if the final result is not
1748 // a tag.
1749 bool FoundTag = false;
1750 bool FoundNonTag = false;
1751
John McCall5cebab12009-11-18 07:57:50 +00001752 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001753
1754 bool Found = false;
1755 while (!Queue.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001756 NamespaceDecl *ND = Queue.pop_back_val();
John McCall6538c932009-10-10 05:48:19 +00001757
1758 // We go through some convolutions here to avoid copying results
1759 // between LookupResults.
1760 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001761 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001762 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001763
1764 if (FoundDirect) {
1765 // First do any local hiding.
1766 DirectR.resolveKind();
1767
1768 // If the local result is a tag, remember that.
1769 if (DirectR.isSingleTagDecl())
1770 FoundTag = true;
1771 else
1772 FoundNonTag = true;
1773
1774 // Append the local results to the total results if necessary.
1775 if (UseLocal) {
1776 R.addAllDecls(LocalR);
1777 LocalR.clear();
1778 }
1779 }
1780
1781 // If we find names in this namespace, ignore its using directives.
1782 if (FoundDirect) {
1783 Found = true;
1784 continue;
1785 }
1786
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001787 for (auto I : ND->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00001788 NamespaceDecl *Nom = I->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +00001789 if (Visited.insert(Nom).second)
John McCall6538c932009-10-10 05:48:19 +00001790 Queue.push_back(Nom);
1791 }
1792 }
1793
1794 if (Found) {
1795 if (FoundTag && FoundNonTag)
1796 R.setAmbiguousQualifiedTagHiding();
1797 else
1798 R.resolveKind();
1799 }
1800
1801 return Found;
1802}
1803
Douglas Gregor39982192010-08-15 06:18:01 +00001804/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001805static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00001806 CXXBasePath &Path, DeclarationName Name) {
Douglas Gregor39982192010-08-15 06:18:01 +00001807 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001808
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00001809 Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00001810 return !Path.Decls.empty();
Douglas Gregor39982192010-08-15 06:18:01 +00001811}
1812
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001813/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001814/// static members, nested types, and enumerators.
1815template<typename InputIterator>
1816static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1817 Decl *D = (*First)->getUnderlyingDecl();
1818 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1819 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001820
Douglas Gregorc0d24902010-10-22 22:08:47 +00001821 if (isa<CXXMethodDecl>(D)) {
1822 // Determine whether all of the methods are static.
1823 bool AllMethodsAreStatic = true;
1824 for(; First != Last; ++First) {
1825 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001826
Douglas Gregorc0d24902010-10-22 22:08:47 +00001827 if (!isa<CXXMethodDecl>(D)) {
1828 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1829 break;
1830 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001831
Douglas Gregorc0d24902010-10-22 22:08:47 +00001832 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1833 AllMethodsAreStatic = false;
1834 break;
1835 }
1836 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001837
Douglas Gregorc0d24902010-10-22 22:08:47 +00001838 if (AllMethodsAreStatic)
1839 return true;
1840 }
1841
1842 return false;
1843}
1844
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001845/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001846///
1847/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1848/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001849/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001850///
1851/// Different lookup criteria can find different names. For example, a
1852/// particular scope can have both a struct and a function of the same
1853/// name, and each can be found by certain lookup criteria. For more
1854/// information about lookup criteria, see the documentation for the
1855/// class LookupCriteria.
1856///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001857/// \param R captures both the lookup criteria and any lookup results found.
1858///
1859/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001860/// search. If the lookup criteria permits, name lookup may also search
1861/// in the parent contexts or (for C++ classes) base classes.
1862///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001863/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001864/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001865///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001866/// \returns true if lookup succeeded, false if it failed.
1867bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1868 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001869 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001870
John McCall27b18f82009-11-17 02:14:36 +00001871 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001872 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001873
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001874 // Make sure that the declaration context is complete.
1875 assert((!isa<TagDecl>(LookupCtx) ||
1876 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00001877 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith7d137e32012-03-23 03:33:32 +00001878 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001879 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001880
Douglas Gregor34074322009-01-14 22:20:51 +00001881 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001882 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001883 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001884 if (isa<CXXRecordDecl>(LookupCtx))
1885 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001886 return true;
1887 }
Douglas Gregor34074322009-01-14 22:20:51 +00001888
John McCall6538c932009-10-10 05:48:19 +00001889 // Don't descend into implied contexts for redeclarations.
1890 // C++98 [namespace.qual]p6:
1891 // In a declaration for a namespace member in which the
1892 // declarator-id is a qualified-id, given that the qualified-id
1893 // for the namespace member has the form
1894 // nested-name-specifier unqualified-id
1895 // the unqualified-id shall name a member of the namespace
1896 // designated by the nested-name-specifier.
1897 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001898 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001899 return false;
1900
John McCall27b18f82009-11-17 02:14:36 +00001901 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001902 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001903 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001904
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001905 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001906 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001907 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001908 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001909 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001910
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001911 // If we're performing qualified name lookup into a dependent class,
1912 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001913 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001914 // template instantiation time (at which point all bases will be available)
1915 // or we have to fail.
1916 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1917 LookupRec->hasAnyDependentBases()) {
1918 R.setNotFoundInCurrentInstantiation();
1919 return false;
1920 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001921
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001922 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001923 CXXBasePaths Paths;
1924 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001925
1926 // Look for this member in our base classes
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00001927 bool (*BaseCallback)(const CXXBaseSpecifier *Specifier, CXXBasePath &Path,
1928 DeclarationName Name) = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00001929 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001930 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001931 case LookupOrdinaryName:
1932 case LookupMemberName:
1933 case LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +00001934 case LookupLocalFriendName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001935 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1936 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001937
Douglas Gregor36d1b142009-10-06 17:59:45 +00001938 case LookupTagName:
1939 BaseCallback = &CXXRecordDecl::FindTagMember;
1940 break;
John McCall84d87672009-12-10 09:41:52 +00001941
Douglas Gregor39982192010-08-15 06:18:01 +00001942 case LookupAnyName:
1943 BaseCallback = &LookupAnyMember;
1944 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001945
John McCall84d87672009-12-10 09:41:52 +00001946 case LookupUsingDeclName:
1947 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001948
Douglas Gregor36d1b142009-10-06 17:59:45 +00001949 case LookupOperatorName:
1950 case LookupNamespaceName:
1951 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001952 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001953 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001954 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001955
Douglas Gregor36d1b142009-10-06 17:59:45 +00001956 case LookupNestedNameSpecifierName:
1957 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1958 break;
1959 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001960
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00001961 DeclarationName Name = R.getLookupName();
1962 if (!LookupRec->lookupInBases(
1963 [=](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
1964 return BaseCallback(Specifier, Path, Name);
1965 },
1966 Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001967 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001968
John McCall553c0792010-01-23 00:46:32 +00001969 R.setNamingClass(LookupRec);
1970
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001971 // C++ [class.member.lookup]p2:
1972 // [...] If the resulting set of declarations are not all from
1973 // sub-objects of the same type, or the set has a nonstatic member
1974 // and includes members from distinct sub-objects, there is an
1975 // ambiguity and the program is ill-formed. Otherwise that set is
1976 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001977 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001978 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001979 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001980
Douglas Gregor36d1b142009-10-06 17:59:45 +00001981 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001982 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001983 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001984
John McCall401982f2010-01-20 21:53:11 +00001985 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1986 // across all paths.
1987 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001988
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001989 // Determine whether we're looking at a distinct sub-object or not.
1990 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001991 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001992 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1993 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001994 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001995 }
1996
Douglas Gregorc0d24902010-10-22 22:08:47 +00001997 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001998 != Context.getCanonicalType(PathElement.Base->getType())) {
1999 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00002000 // different types. If the declaration sets aren't the same, this
Nikola Smiljanic1c125682014-07-09 05:42:35 +00002001 // lookup is ambiguous.
David Blaikieff7d47a2012-12-19 00:45:41 +00002002 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00002003 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikieff7d47a2012-12-19 00:45:41 +00002004 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
2005 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002006
David Blaikieff7d47a2012-12-19 00:45:41 +00002007 while (FirstD != FirstPath->Decls.end() &&
2008 CurrentD != Path->Decls.end()) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00002009 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
2010 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
2011 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002012
Douglas Gregorc0d24902010-10-22 22:08:47 +00002013 ++FirstD;
2014 ++CurrentD;
2015 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002016
David Blaikieff7d47a2012-12-19 00:45:41 +00002017 if (FirstD == FirstPath->Decls.end() &&
2018 CurrentD == Path->Decls.end())
Douglas Gregorc0d24902010-10-22 22:08:47 +00002019 continue;
2020 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002021
John McCall9f3059a2009-10-09 21:13:30 +00002022 R.setAmbiguousBaseSubobjectTypes(Paths);
2023 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002024 }
2025
Douglas Gregorc0d24902010-10-22 22:08:47 +00002026 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002027 // We have a different subobject of the same type.
2028
2029 // C++ [class.member.lookup]p5:
2030 // A static member, a nested type or an enumerator defined in
2031 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00002032 // has more than one base class subobject of type T.
David Blaikieff7d47a2012-12-19 00:45:41 +00002033 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002034 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002035
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002036 // We have found a nonstatic member name in multiple, distinct
2037 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00002038 R.setAmbiguousBaseSubobjects(Paths);
2039 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002040 }
2041 }
2042
2043 // Lookup in a base class succeeded; return these results.
2044
Aaron Ballman1e606f42014-07-15 22:03:49 +00002045 for (auto *D : Paths.front().Decls) {
John McCall553c0792010-01-23 00:46:32 +00002046 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
2047 D->getAccess());
2048 R.addDecl(D, AS);
2049 }
John McCall9f3059a2009-10-09 21:13:30 +00002050 R.resolveKind();
2051 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00002052}
2053
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00002054/// \brief Performs qualified name lookup or special type of lookup for
2055/// "__super::" scope specifier.
2056///
2057/// This routine is a convenience overload meant to be called from contexts
2058/// that need to perform a qualified name lookup with an optional C++ scope
2059/// specifier that might require special kind of lookup.
2060///
2061/// \param R captures both the lookup criteria and any lookup results found.
2062///
2063/// \param LookupCtx The context in which qualified name lookup will
2064/// search.
2065///
2066/// \param SS An optional C++ scope-specifier.
2067///
2068/// \returns true if lookup succeeded, false if it failed.
2069bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2070 CXXScopeSpec &SS) {
2071 auto *NNS = SS.getScopeRep();
2072 if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
2073 return LookupInSuper(R, NNS->getAsRecordDecl());
2074 else
2075
2076 return LookupQualifiedName(R, LookupCtx);
2077}
2078
Douglas Gregor34074322009-01-14 22:20:51 +00002079/// @brief Performs name lookup for a name that was parsed in the
2080/// source code, and may contain a C++ scope specifier.
2081///
2082/// This routine is a convenience routine meant to be called from
2083/// contexts that receive a name and an optional C++ scope specifier
2084/// (e.g., "N::M::x"). It will then perform either qualified or
2085/// unqualified name lookup (with LookupQualifiedName or LookupName,
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002086/// respectively) on the given name and return those results. It will
2087/// perform a special type of lookup for "__super::" scope specifier.
Douglas Gregor34074322009-01-14 22:20:51 +00002088///
2089/// @param S The scope from which unqualified name lookup will
2090/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00002091///
Douglas Gregore861bac2009-08-25 22:51:20 +00002092/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00002093///
Douglas Gregore861bac2009-08-25 22:51:20 +00002094/// @param EnteringContext Indicates whether we are going to enter the
2095/// context of the scope-specifier SS (if present).
2096///
John McCall9f3059a2009-10-09 21:13:30 +00002097/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002098bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00002099 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00002100 if (SS && SS->isInvalid()) {
2101 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002102 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00002103 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00002104 }
Mike Stump11289f42009-09-09 15:08:12 +00002105
Douglas Gregore861bac2009-08-25 22:51:20 +00002106 if (SS && SS->isSet()) {
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002107 NestedNameSpecifier *NNS = SS->getScopeRep();
2108 if (NNS->getKind() == NestedNameSpecifier::Super)
2109 return LookupInSuper(R, NNS->getAsRecordDecl());
2110
Douglas Gregore861bac2009-08-25 22:51:20 +00002111 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00002112 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00002113 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00002114 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00002115 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002116
John McCall27b18f82009-11-17 02:14:36 +00002117 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00002118 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00002119 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002120
Douglas Gregore861bac2009-08-25 22:51:20 +00002121 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00002122 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00002123 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00002124 R.setNotFoundInCurrentInstantiation();
2125 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00002126 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00002127 }
2128
Mike Stump11289f42009-09-09 15:08:12 +00002129 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00002130 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00002131}
2132
Nikola Smiljanic67860242014-09-26 00:28:20 +00002133/// \brief Perform qualified name lookup into all base classes of the given
2134/// class.
2135///
2136/// \param R captures both the lookup criteria and any lookup results found.
2137///
2138/// \param Class The context in which qualified name lookup will
2139/// search. Name lookup will search in all base classes merging the results.
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002140///
2141/// @returns True if any decls were found (but possibly ambiguous)
2142bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
John McCallf4a1b772015-09-09 23:04:17 +00002143 // The access-control rules we use here are essentially the rules for
2144 // doing a lookup in Class that just magically skipped the direct
2145 // members of Class itself. That is, the naming class is Class, and the
2146 // access includes the access of the base.
Nikola Smiljanic67860242014-09-26 00:28:20 +00002147 for (const auto &BaseSpec : Class->bases()) {
2148 CXXRecordDecl *RD = cast<CXXRecordDecl>(
2149 BaseSpec.getType()->castAs<RecordType>()->getDecl());
2150 LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
2151 Result.setBaseObjectType(Context.getRecordType(Class));
2152 LookupQualifiedName(Result, RD);
John McCallf4a1b772015-09-09 23:04:17 +00002153
2154 // Copy the lookup results into the target, merging the base's access into
2155 // the path access.
2156 for (auto I = Result.begin(), E = Result.end(); I != E; ++I) {
2157 R.addDecl(I.getDecl(),
2158 CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(),
2159 I.getAccess()));
2160 }
2161
2162 Result.suppressDiagnostics();
Nikola Smiljanic67860242014-09-26 00:28:20 +00002163 }
2164
2165 R.resolveKind();
John McCallf4a1b772015-09-09 23:04:17 +00002166 R.setNamingClass(Class);
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002167
2168 return !R.empty();
Nikola Smiljanic67860242014-09-26 00:28:20 +00002169}
Douglas Gregor889ceb72009-02-03 19:21:40 +00002170
James Dennett41725122012-06-22 10:16:05 +00002171/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002172/// from name lookup.
2173///
James Dennett41725122012-06-22 10:16:05 +00002174/// \param Result The result of the ambiguous lookup to be diagnosed.
Serge Pavlov99292092013-08-29 07:23:24 +00002175void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002176 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
2177
John McCall27b18f82009-11-17 02:14:36 +00002178 DeclarationName Name = Result.getLookupName();
2179 SourceLocation NameLoc = Result.getNameLoc();
2180 SourceRange LookupRange = Result.getContextRange();
2181
John McCall6538c932009-10-10 05:48:19 +00002182 switch (Result.getAmbiguityKind()) {
2183 case LookupResult::AmbiguousBaseSubobjects: {
2184 CXXBasePaths *Paths = Result.getBasePaths();
2185 QualType SubobjectType = Paths->front().back().Base->getType();
2186 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
2187 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
2188 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002189
David Blaikieff7d47a2012-12-19 00:45:41 +00002190 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6538c932009-10-10 05:48:19 +00002191 while (isa<CXXMethodDecl>(*Found) &&
2192 cast<CXXMethodDecl>(*Found)->isStatic())
2193 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002194
John McCall6538c932009-10-10 05:48:19 +00002195 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
Serge Pavlov99292092013-08-29 07:23:24 +00002196 break;
John McCall6538c932009-10-10 05:48:19 +00002197 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00002198
John McCall6538c932009-10-10 05:48:19 +00002199 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00002200 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
2201 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002202
John McCall6538c932009-10-10 05:48:19 +00002203 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002204 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00002205 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
2206 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002207 Path != PathEnd; ++Path) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002208 Decl *D = Path->Decls.front();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002209 if (DeclsPrinted.insert(D).second)
2210 Diag(D->getLocation(), diag::note_ambiguous_member_found);
2211 }
Serge Pavlov99292092013-08-29 07:23:24 +00002212 break;
Douglas Gregor1c846b02009-01-16 00:38:09 +00002213 }
2214
John McCall6538c932009-10-10 05:48:19 +00002215 case LookupResult::AmbiguousTagHiding: {
2216 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00002217
Nick Lewycky4b81fc872015-10-18 20:32:12 +00002218 llvm::SmallPtrSet<NamedDecl*, 8> TagDecls;
John McCall6538c932009-10-10 05:48:19 +00002219
Aaron Ballman1e606f42014-07-15 22:03:49 +00002220 for (auto *D : Result)
2221 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
John McCall6538c932009-10-10 05:48:19 +00002222 TagDecls.insert(TD);
2223 Diag(TD->getLocation(), diag::note_hidden_tag);
2224 }
2225
Aaron Ballman1e606f42014-07-15 22:03:49 +00002226 for (auto *D : Result)
2227 if (!isa<TagDecl>(D))
2228 Diag(D->getLocation(), diag::note_hiding_object);
John McCall6538c932009-10-10 05:48:19 +00002229
2230 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00002231 LookupResult::Filter F = Result.makeFilter();
2232 while (F.hasNext()) {
2233 if (TagDecls.count(F.next()))
2234 F.erase();
2235 }
2236 F.done();
Serge Pavlov99292092013-08-29 07:23:24 +00002237 break;
John McCall6538c932009-10-10 05:48:19 +00002238 }
2239
2240 case LookupResult::AmbiguousReference: {
2241 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002242
Aaron Ballman1e606f42014-07-15 22:03:49 +00002243 for (auto *D : Result)
2244 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
Serge Pavlov99292092013-08-29 07:23:24 +00002245 break;
John McCall6538c932009-10-10 05:48:19 +00002246 }
Serge Pavlov99292092013-08-29 07:23:24 +00002247 }
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002248}
Douglas Gregore254f902009-02-04 00:32:51 +00002249
John McCallf24d7bb2010-05-28 18:45:08 +00002250namespace {
2251 struct AssociatedLookup {
John McCall7d8b0412012-08-24 20:38:34 +00002252 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallf24d7bb2010-05-28 18:45:08 +00002253 Sema::AssociatedNamespaceSet &Namespaces,
2254 Sema::AssociatedClassSet &Classes)
John McCall7d8b0412012-08-24 20:38:34 +00002255 : S(S), Namespaces(Namespaces), Classes(Classes),
2256 InstantiationLoc(InstantiationLoc) {
John McCallf24d7bb2010-05-28 18:45:08 +00002257 }
2258
2259 Sema &S;
2260 Sema::AssociatedNamespaceSet &Namespaces;
2261 Sema::AssociatedClassSet &Classes;
John McCall7d8b0412012-08-24 20:38:34 +00002262 SourceLocation InstantiationLoc;
John McCallf24d7bb2010-05-28 18:45:08 +00002263 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002264} // end anonymous namespace
John McCallf24d7bb2010-05-28 18:45:08 +00002265
Mike Stump11289f42009-09-09 15:08:12 +00002266static void
John McCallf24d7bb2010-05-28 18:45:08 +00002267addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00002268
Douglas Gregor8b895222010-04-30 07:08:38 +00002269static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
2270 DeclContext *Ctx) {
2271 // Add the associated namespace for this class.
2272
2273 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
2274 // be a locally scoped record.
2275
Sebastian Redlbd595762010-08-31 20:53:31 +00002276 // We skip out of inline namespaces. The innermost non-inline namespace
2277 // contains all names of all its nested inline namespaces anyway, so we can
2278 // replace the entire inline namespace tree with its root.
2279 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
2280 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00002281 Ctx = Ctx->getParent();
2282
John McCallc7e8e792009-08-07 22:18:02 +00002283 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00002284 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00002285}
Douglas Gregor197e5f72009-07-08 07:51:57 +00002286
Mike Stump11289f42009-09-09 15:08:12 +00002287// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00002288// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00002289static void
John McCallf24d7bb2010-05-28 18:45:08 +00002290addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2291 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002292 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00002293 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00002294 switch (Arg.getKind()) {
2295 case TemplateArgument::Null:
2296 break;
Mike Stump11289f42009-09-09 15:08:12 +00002297
Douglas Gregor197e5f72009-07-08 07:51:57 +00002298 case TemplateArgument::Type:
2299 // [...] the namespaces and classes associated with the types of the
2300 // template arguments provided for template type parameters (excluding
2301 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00002302 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00002303 break;
Mike Stump11289f42009-09-09 15:08:12 +00002304
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002305 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002306 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00002307 // [...] the namespaces in which any template template arguments are
2308 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00002309 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002310 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00002311 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002312 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002313 DeclContext *Ctx = ClassTemplate->getDeclContext();
2314 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002315 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002316 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002317 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002318 }
2319 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002320 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002321
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002322 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00002323 case TemplateArgument::Integral:
2324 case TemplateArgument::Expression:
Eli Friedmanb826a002012-09-26 02:36:12 +00002325 case TemplateArgument::NullPtr:
Mike Stump11289f42009-09-09 15:08:12 +00002326 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00002327 // associated namespaces. ]
2328 break;
Mike Stump11289f42009-09-09 15:08:12 +00002329
Douglas Gregor197e5f72009-07-08 07:51:57 +00002330 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00002331 for (const auto &P : Arg.pack_elements())
2332 addAssociatedClassesAndNamespaces(Result, P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002333 break;
2334 }
2335}
2336
Douglas Gregore254f902009-02-04 00:32:51 +00002337// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00002338// argument-dependent lookup with an argument of class type
2339// (C++ [basic.lookup.koenig]p2).
2340static void
John McCallf24d7bb2010-05-28 18:45:08 +00002341addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2342 CXXRecordDecl *Class) {
2343
2344 // Just silently ignore anything whose name is __va_list_tag.
2345 if (Class->getDeclName() == Result.S.VAListTagName)
2346 return;
2347
Douglas Gregore254f902009-02-04 00:32:51 +00002348 // C++ [basic.lookup.koenig]p2:
2349 // [...]
2350 // -- If T is a class type (including unions), its associated
2351 // classes are: the class itself; the class of which it is a
2352 // member, if any; and its direct and indirect base
2353 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00002354 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00002355
2356 // Add the class of which it is a member, if any.
2357 DeclContext *Ctx = Class->getDeclContext();
2358 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002359 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +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 Gregore254f902009-02-04 00:32:51 +00002363 // Add the class itself. If we've already seen this class, we don't
2364 // need to visit base classes.
Richard Smith594461f2014-03-14 22:07:27 +00002365 //
2366 // FIXME: That's not correct, we may have added this class only because it
2367 // was the enclosing class of another class, and in that case we won't have
2368 // added its base classes yet.
David Blaikie82e95a32014-11-19 07:49:47 +00002369 if (!Result.Classes.insert(Class).second)
Douglas Gregore254f902009-02-04 00:32:51 +00002370 return;
2371
Mike Stump11289f42009-09-09 15:08:12 +00002372 // -- If T is a template-id, its associated namespaces and classes are
2373 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002374 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00002375 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00002376 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00002377 // namespaces in which any template template arguments are defined; and
2378 // the classes in which any member templates used as template template
2379 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00002380 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00002381 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00002382 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2383 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2384 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002385 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002386 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002387 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002388
Douglas Gregor197e5f72009-07-08 07:51:57 +00002389 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2390 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00002391 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002392 }
Mike Stump11289f42009-09-09 15:08:12 +00002393
John McCall67da35c2010-02-04 22:26:26 +00002394 // Only recurse into base classes for complete types.
Richard Smith594461f2014-03-14 22:07:27 +00002395 if (!Class->hasDefinition())
2396 return;
John McCall67da35c2010-02-04 22:26:26 +00002397
Douglas Gregore254f902009-02-04 00:32:51 +00002398 // Add direct and indirect base classes along with their associated
2399 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002400 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00002401 Bases.push_back(Class);
2402 while (!Bases.empty()) {
2403 // Pop this class off the stack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002404 Class = Bases.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002405
2406 // Visit the base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +00002407 for (const auto &Base : Class->bases()) {
2408 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00002409 // In dependent contexts, we do ADL twice, and the first time around,
2410 // the base type might be a dependent TemplateSpecializationType, or a
2411 // TemplateTypeParmType. If that happens, simply ignore it.
2412 // FIXME: If we want to support export, we probably need to add the
2413 // namespace of the template in a TemplateSpecializationType, or even
2414 // the classes and namespaces of known non-dependent arguments.
2415 if (!BaseType)
2416 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002417 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
David Blaikie82e95a32014-11-19 07:49:47 +00002418 if (Result.Classes.insert(BaseDecl).second) {
Douglas Gregore254f902009-02-04 00:32:51 +00002419 // Find the associated namespace for this base class.
2420 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00002421 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00002422
2423 // Make sure we visit the bases of this base class.
2424 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2425 Bases.push_back(BaseDecl);
2426 }
2427 }
2428 }
2429}
2430
2431// \brief Add the associated classes and namespaces for
2432// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00002433// (C++ [basic.lookup.koenig]p2).
2434static void
John McCallf24d7bb2010-05-28 18:45:08 +00002435addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00002436 // C++ [basic.lookup.koenig]p2:
2437 //
2438 // For each argument type T in the function call, there is a set
2439 // of zero or more associated namespaces and a set of zero or more
2440 // associated classes to be considered. The sets of namespaces and
2441 // classes is determined entirely by the types of the function
2442 // arguments (and the namespace of any template template
2443 // argument). Typedef names and using-declarations used to specify
2444 // the types do not contribute to this set. The sets of namespaces
2445 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00002446
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002447 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00002448 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2449
Douglas Gregore254f902009-02-04 00:32:51 +00002450 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00002451 switch (T->getTypeClass()) {
2452
2453#define TYPE(Class, Base)
2454#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2455#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2456#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2457#define ABSTRACT_TYPE(Class, Base)
2458#include "clang/AST/TypeNodes.def"
2459 // T is canonical. We can also ignore dependent types because
2460 // we don't need to do ADL at the definition point, but if we
2461 // wanted to implement template export (or if we find some other
2462 // use for associated classes and namespaces...) this would be
2463 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00002464 break;
Douglas Gregore254f902009-02-04 00:32:51 +00002465
John McCall0af3d3b2010-05-28 06:08:54 +00002466 // -- If T is a pointer to U or an array of U, its associated
2467 // namespaces and classes are those associated with U.
2468 case Type::Pointer:
2469 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2470 continue;
2471 case Type::ConstantArray:
2472 case Type::IncompleteArray:
2473 case Type::VariableArray:
2474 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2475 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002476
John McCall0af3d3b2010-05-28 06:08:54 +00002477 // -- If T is a fundamental type, its associated sets of
2478 // namespaces and classes are both empty.
2479 case Type::Builtin:
2480 break;
2481
2482 // -- If T is a class type (including unions), its associated
2483 // classes are: the class itself; the class of which it is a
2484 // member, if any; and its direct and indirect base
2485 // classes. Its associated namespaces are the namespaces in
2486 // which its associated classes are defined.
2487 case Type::Record: {
Richard Smith594461f2014-03-14 22:07:27 +00002488 Result.S.RequireCompleteType(Result.InstantiationLoc, QualType(T, 0),
2489 /*no diagnostic*/ 0);
John McCall0af3d3b2010-05-28 06:08:54 +00002490 CXXRecordDecl *Class
2491 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002492 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00002493 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00002494 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00002495
John McCall0af3d3b2010-05-28 06:08:54 +00002496 // -- If T is an enumeration type, its associated namespace is
2497 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002498 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00002499 // it has no associated class.
2500 case Type::Enum: {
2501 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002502
John McCall0af3d3b2010-05-28 06:08:54 +00002503 DeclContext *Ctx = Enum->getDeclContext();
2504 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002505 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002506
John McCall0af3d3b2010-05-28 06:08:54 +00002507 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002508 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00002509
John McCall0af3d3b2010-05-28 06:08:54 +00002510 break;
2511 }
2512
2513 // -- If T is a function type, its associated namespaces and
2514 // classes are those associated with the function parameter
2515 // types and those associated with the return type.
2516 case Type::FunctionProto: {
2517 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002518 for (const auto &Arg : Proto->param_types())
2519 Queue.push_back(Arg.getTypePtr());
John McCall0af3d3b2010-05-28 06:08:54 +00002520 // fallthrough
2521 }
2522 case Type::FunctionNoProto: {
2523 const FunctionType *FnType = cast<FunctionType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00002524 T = FnType->getReturnType().getTypePtr();
John McCall0af3d3b2010-05-28 06:08:54 +00002525 continue;
2526 }
2527
2528 // -- If T is a pointer to a member function of a class X, its
2529 // associated namespaces and classes are those associated
2530 // with the function parameter types and return type,
2531 // together with those associated with X.
2532 //
2533 // -- If T is a pointer to a data member of class X, its
2534 // associated namespaces and classes are those associated
2535 // with the member type together with those associated with
2536 // X.
2537 case Type::MemberPointer: {
2538 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2539
2540 // Queue up the class type into which this points.
2541 Queue.push_back(MemberPtr->getClass());
2542
2543 // And directly continue with the pointee type.
2544 T = MemberPtr->getPointeeType().getTypePtr();
2545 continue;
2546 }
2547
2548 // As an extension, treat this like a normal pointer.
2549 case Type::BlockPointer:
2550 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2551 continue;
2552
2553 // References aren't covered by the standard, but that's such an
2554 // obvious defect that we cover them anyway.
2555 case Type::LValueReference:
2556 case Type::RValueReference:
2557 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2558 continue;
2559
2560 // These are fundamental types.
2561 case Type::Vector:
2562 case Type::ExtVector:
2563 case Type::Complex:
2564 break;
2565
Richard Smith27d807c2013-04-30 13:56:41 +00002566 // Non-deduced auto types only get here for error cases.
2567 case Type::Auto:
2568 break;
2569
Douglas Gregor8e936662011-04-12 01:02:45 +00002570 // If T is an Objective-C object or interface type, or a pointer to an
2571 // object or interface type, the associated namespace is the global
2572 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002573 case Type::ObjCObject:
2574 case Type::ObjCInterface:
2575 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002576 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002577 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002578
2579 // Atomic types are just wrappers; use the associations of the
2580 // contained type.
2581 case Type::Atomic:
2582 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2583 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002584 }
2585
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002586 if (Queue.empty())
2587 break;
2588 T = Queue.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002589 }
Douglas Gregore254f902009-02-04 00:32:51 +00002590}
2591
2592/// \brief Find the associated classes and namespaces for
2593/// argument-dependent lookup for a call with the given set of
2594/// arguments.
2595///
2596/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002597/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002598/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00002599void Sema::FindAssociatedClassesAndNamespaces(
2600 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2601 AssociatedNamespaceSet &AssociatedNamespaces,
2602 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002603 AssociatedNamespaces.clear();
2604 AssociatedClasses.clear();
2605
John McCall7d8b0412012-08-24 20:38:34 +00002606 AssociatedLookup Result(*this, InstantiationLoc,
2607 AssociatedNamespaces, AssociatedClasses);
John McCallf24d7bb2010-05-28 18:45:08 +00002608
Douglas Gregore254f902009-02-04 00:32:51 +00002609 // C++ [basic.lookup.koenig]p2:
2610 // For each argument type T in the function call, there is a set
2611 // of zero or more associated namespaces and a set of zero or more
2612 // associated classes to be considered. The sets of namespaces and
2613 // classes is determined entirely by the types of the function
2614 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002615 // argument).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002616 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregore254f902009-02-04 00:32:51 +00002617 Expr *Arg = Args[ArgIdx];
2618
2619 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002620 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002621 continue;
2622 }
2623
2624 // [...] In addition, if the argument is the name or address of a
2625 // set of overloaded functions and/or function templates, its
2626 // associated classes and namespaces are the union of those
2627 // associated with each of the members of the set: the namespace
2628 // in which the function or function template is defined and the
2629 // classes and namespaces associated with its (non-dependent)
2630 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002631 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002632 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002633 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002634 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002635
John McCallf24d7bb2010-05-28 18:45:08 +00002636 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2637 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002638
Aaron Ballman1e606f42014-07-15 22:03:49 +00002639 for (const auto *D : ULE->decls()) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002640 // Look through any using declarations to find the underlying function.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002641 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
Douglas Gregore254f902009-02-04 00:32:51 +00002642
2643 // Add the classes and namespaces associated with the parameter
2644 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002645 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002646 }
2647 }
2648}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002649
John McCall5cebab12009-11-18 07:57:50 +00002650NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002651 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002652 LookupNameKind NameKind,
2653 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002654 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002655 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002656 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002657}
2658
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002659/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002660ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002661 SourceLocation IdLoc,
2662 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002663 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002664 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002665 return cast_or_null<ObjCProtocolDecl>(D);
2666}
2667
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002668void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002669 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002670 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002671 // C++ [over.match.oper]p3:
2672 // -- The set of non-member candidates is the result of the
2673 // unqualified lookup of operator@ in the context of the
2674 // expression according to the usual rules for name lookup in
2675 // unqualified function calls (3.4.2) except that all member
Richard Smith100b24a2014-04-17 01:52:14 +00002676 // functions are ignored.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002677 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002678 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2679 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002680
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002681 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
Richard Smith100b24a2014-04-17 01:52:14 +00002682 Functions.append(Operators.begin(), Operators.end());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002683}
2684
Alexis Hunt1da39282011-06-24 02:11:39 +00002685Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002686 CXXSpecialMember SM,
2687 bool ConstArg,
2688 bool VolatileArg,
2689 bool RValueThis,
2690 bool ConstThis,
2691 bool VolatileThis) {
Richard Smith7d125a12012-11-27 21:20:31 +00002692 assert(CanDeclareSpecialMemberFunction(RD) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002693 "doing special member lookup into record that isn't fully complete");
Richard Smith7d125a12012-11-27 21:20:31 +00002694 RD = RD->getDefinition();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002695 if (RValueThis || ConstThis || VolatileThis)
2696 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2697 "constructors and destructors always have unqualified lvalue this");
2698 if (ConstArg || VolatileArg)
2699 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2700 "parameter-less special members can't have qualified arguments");
2701
2702 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002703 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002704 ID.AddInteger(SM);
2705 ID.AddInteger(ConstArg);
2706 ID.AddInteger(VolatileArg);
2707 ID.AddInteger(RValueThis);
2708 ID.AddInteger(ConstThis);
2709 ID.AddInteger(VolatileThis);
2710
2711 void *InsertPoint;
2712 SpecialMemberOverloadResult *Result =
2713 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2714
2715 // This was already cached
2716 if (Result)
2717 return Result;
2718
Alexis Huntba8e18d2011-06-07 00:11:58 +00002719 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2720 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002721 SpecialMemberCache.InsertNode(Result, InsertPoint);
2722
2723 if (SM == CXXDestructor) {
Richard Smith2be35f52012-12-01 02:35:44 +00002724 if (RD->needsImplicitDestructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002725 DeclareImplicitDestructor(RD);
2726 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002727 assert(DD && "record without a destructor");
2728 Result->setMethod(DD);
Richard Smith852265f2012-03-30 20:53:28 +00002729 Result->setKind(DD->isDeleted() ?
2730 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith83c478d2012-04-20 18:46:14 +00002731 SpecialMemberOverloadResult::Success);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002732 return Result;
2733 }
2734
Alexis Hunteef8ee02011-06-10 03:50:41 +00002735 // Prepare for overload resolution. Here we construct a synthetic argument
2736 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002737 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002738 DeclarationName Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002739 Expr *Arg = nullptr;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002740 unsigned NumArgs;
2741
Richard Smith83c478d2012-04-20 18:46:14 +00002742 QualType ArgType = CanTy;
2743 ExprValueKind VK = VK_LValue;
2744
Alexis Hunteef8ee02011-06-10 03:50:41 +00002745 if (SM == CXXDefaultConstructor) {
2746 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2747 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002748 if (RD->needsImplicitDefaultConstructor())
2749 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002750 } else {
2751 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2752 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smith2be35f52012-12-01 02:35:44 +00002753 if (RD->needsImplicitCopyConstructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002754 DeclareImplicitCopyConstructor(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002755 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002756 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002757 } else {
2758 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smith2be35f52012-12-01 02:35:44 +00002759 if (RD->needsImplicitCopyAssignment())
Alexis Hunt1da39282011-06-24 02:11:39 +00002760 DeclareImplicitCopyAssignment(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002761 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002762 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002763 }
2764
Alexis Hunteef8ee02011-06-10 03:50:41 +00002765 if (ConstArg)
2766 ArgType.addConst();
2767 if (VolatileArg)
2768 ArgType.addVolatile();
2769
2770 // This isn't /really/ specified by the standard, but it's implied
2771 // we should be working from an RValue in the case of move to ensure
2772 // that we prefer to bind to rvalue references, and an LValue in the
2773 // case of copy to ensure we don't bind to rvalue references.
2774 // Possibly an XValue is actually correct in the case of move, but
2775 // there is no semantic difference for class types in this restricted
2776 // case.
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002777 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002778 VK = VK_LValue;
2779 else
2780 VK = VK_RValue;
Richard Smith83c478d2012-04-20 18:46:14 +00002781 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00002782
Richard Smith83c478d2012-04-20 18:46:14 +00002783 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2784
2785 if (SM != CXXDefaultConstructor) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002786 NumArgs = 1;
Richard Smith83c478d2012-04-20 18:46:14 +00002787 Arg = &FakeArg;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002788 }
2789
2790 // Create the object argument
2791 QualType ThisTy = CanTy;
2792 if (ConstThis)
2793 ThisTy.addConst();
2794 if (VolatileThis)
2795 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002796 Expr::Classification Classification =
Richard Smith83c478d2012-04-20 18:46:14 +00002797 OpaqueValueExpr(SourceLocation(), ThisTy,
2798 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002799
2800 // Now we perform lookup on the name we computed earlier and do overload
2801 // resolution. Lookup is only performed directly into the class since there
2802 // will always be a (possibly implicit) declaration to shadow any others.
Richard Smith100b24a2014-04-17 01:52:14 +00002803 OverloadCandidateSet OCS(RD->getLocation(), OverloadCandidateSet::CSK_Normal);
David Blaikieff7d47a2012-12-19 00:45:41 +00002804 DeclContext::lookup_result R = RD->lookup(Name);
Richard Smith8c37ab52015-02-11 01:48:47 +00002805
2806 if (R.empty()) {
2807 // We might have no default constructor because we have a lambda's closure
2808 // type, rather than because there's some other declared constructor.
2809 // Every class has a copy/move constructor, copy/move assignment, and
2810 // destructor.
2811 assert(SM == CXXDefaultConstructor &&
2812 "lookup for a constructor or assignment operator was empty");
2813 Result->setMethod(nullptr);
2814 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
2815 return Result;
2816 }
Chandler Carruth7deaae72013-08-18 07:20:52 +00002817
2818 // Copy the candidates as our processing of them may load new declarations
2819 // from an external source and invalidate lookup_result.
2820 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2821
Aaron Ballman1e606f42014-07-15 22:03:49 +00002822 for (auto *Cand : Candidates) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002823 if (Cand->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002824 continue;
2825
Alexis Hunt1da39282011-06-24 02:11:39 +00002826 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2827 // FIXME: [namespace.udecl]p15 says that we should only consider a
2828 // using declaration here if it does not match a declaration in the
2829 // derived class. We do not implement this correctly in other cases
2830 // either.
2831 Cand = U->getTargetDecl();
2832
2833 if (Cand->isInvalidDecl())
2834 continue;
2835 }
2836
2837 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002838 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Alexis Hunt1da39282011-06-24 02:11:39 +00002839 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002840 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2841 OCS, true);
Alexis Hunt080709f2011-06-23 00:26:20 +00002842 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002843 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2844 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt2949f022011-06-22 02:58:46 +00002845 } else if (FunctionTemplateDecl *Tmpl =
Alexis Hunt1da39282011-06-24 02:11:39 +00002846 dyn_cast<FunctionTemplateDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002847 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2848 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Craig Topperc3ec1492014-05-26 06:22:03 +00002849 RD, nullptr, ThisTy, Classification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002850 llvm::makeArrayRef(&Arg, NumArgs),
Alexis Hunt080709f2011-06-23 00:26:20 +00002851 OCS, true);
2852 else
2853 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Craig Topperc3ec1492014-05-26 06:22:03 +00002854 nullptr, llvm::makeArrayRef(&Arg, NumArgs),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002855 OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002856 } else {
2857 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002858 }
2859 }
2860
2861 OverloadCandidateSet::iterator Best;
2862 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2863 case OR_Success:
2864 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith83c478d2012-04-20 18:46:14 +00002865 Result->setKind(SpecialMemberOverloadResult::Success);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002866 break;
2867
2868 case OR_Deleted:
2869 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith852265f2012-03-30 20:53:28 +00002870 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002871 break;
2872
2873 case OR_Ambiguous:
Craig Topperc3ec1492014-05-26 06:22:03 +00002874 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00002875 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2876 break;
2877
Alexis Hunteef8ee02011-06-10 03:50:41 +00002878 case OR_No_Viable_Function:
Craig Topperc3ec1492014-05-26 06:22:03 +00002879 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00002880 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002881 break;
2882 }
2883
2884 return Result;
2885}
2886
2887/// \brief Look up the default constructor for the given class.
2888CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002889 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002890 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2891 false, false);
2892
2893 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002894}
2895
Alexis Hunt491ec602011-06-21 23:42:56 +00002896/// \brief Look up the copying constructor for the given class.
2897CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith83c478d2012-04-20 18:46:14 +00002898 unsigned Quals) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002899 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2900 "non-const, non-volatile qualifiers for copy ctor arg");
2901 SpecialMemberOverloadResult *Result =
2902 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2903 Quals & Qualifiers::Volatile, false, false, false);
2904
Alexis Hunt899bd442011-06-10 04:44:37 +00002905 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2906}
2907
Sebastian Redl22653ba2011-08-30 19:58:05 +00002908/// \brief Look up the moving constructor for the given class.
Richard Smith1c6461e2012-07-18 03:36:00 +00002909CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2910 unsigned Quals) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002911 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002912 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2913 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002914
2915 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2916}
2917
Douglas Gregor52b72822010-07-02 23:12:18 +00002918/// \brief Look up the constructors for the given class.
2919DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002920 // If the implicit constructors have not yet been declared, do so now.
Richard Smith7d125a12012-11-27 21:20:31 +00002921 if (CanDeclareSpecialMemberFunction(Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00002922 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002923 DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +00002924 if (Class->needsImplicitCopyConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002925 DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002926 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002927 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00002928 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002929
Douglas Gregor52b72822010-07-02 23:12:18 +00002930 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2931 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2932 return Class->lookup(Name);
2933}
2934
Alexis Hunt491ec602011-06-21 23:42:56 +00002935/// \brief Look up the copying assignment operator for the given class.
2936CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2937 unsigned Quals, bool RValueThis,
Richard Smith83c478d2012-04-20 18:46:14 +00002938 unsigned ThisQuals) {
Alexis Hunt491ec602011-06-21 23:42:56 +00002939 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2940 "non-const, non-volatile qualifiers for copy assignment arg");
2941 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2942 "non-const, non-volatile qualifiers for copy assignment this");
2943 SpecialMemberOverloadResult *Result =
2944 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2945 Quals & Qualifiers::Volatile, RValueThis,
2946 ThisQuals & Qualifiers::Const,
2947 ThisQuals & Qualifiers::Volatile);
2948
Alexis Hunt491ec602011-06-21 23:42:56 +00002949 return Result->getMethod();
2950}
2951
Sebastian Redl22653ba2011-08-30 19:58:05 +00002952/// \brief Look up the moving assignment operator for the given class.
2953CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith1c6461e2012-07-18 03:36:00 +00002954 unsigned Quals,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002955 bool RValueThis,
2956 unsigned ThisQuals) {
2957 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2958 "non-const, non-volatile qualifiers for copy assignment this");
2959 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002960 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2961 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002962 ThisQuals & Qualifiers::Const,
2963 ThisQuals & Qualifiers::Volatile);
2964
2965 return Result->getMethod();
2966}
2967
Douglas Gregore71edda2010-07-01 22:47:18 +00002968/// \brief Look for the destructor of the given class.
2969///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00002970/// During semantic analysis, this routine should be used in lieu of
2971/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00002972///
2973/// \returns The destructor for this class.
2974CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002975 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2976 false, false, false,
2977 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00002978}
2979
Richard Smithbcc22fc2012-03-09 08:00:36 +00002980/// LookupLiteralOperator - Determine which literal operator should be used for
2981/// a user-defined literal, per C++11 [lex.ext].
2982///
2983/// Normal overload resolution is not used to select which literal operator to
2984/// call for a user-defined literal. Look up the provided literal operator name,
2985/// and filter the results to the appropriate set for the given argument types.
2986Sema::LiteralOperatorLookupResult
2987Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2988 ArrayRef<QualType> ArgTys,
Richard Smithb8b41d32013-10-07 19:57:58 +00002989 bool AllowRaw, bool AllowTemplate,
2990 bool AllowStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002991 LookupName(R, S);
2992 assert(R.getResultKind() != LookupResult::Ambiguous &&
2993 "literal operator lookup can't be ambiguous");
2994
2995 // Filter the lookup results appropriately.
2996 LookupResult::Filter F = R.makeFilter();
2997
Richard Smithbcc22fc2012-03-09 08:00:36 +00002998 bool FoundRaw = false;
Richard Smithb8b41d32013-10-07 19:57:58 +00002999 bool FoundTemplate = false;
3000 bool FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003001 bool FoundExactMatch = false;
3002
3003 while (F.hasNext()) {
3004 Decl *D = F.next();
3005 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
3006 D = USD->getTargetDecl();
3007
Douglas Gregorc1970572013-04-10 05:18:00 +00003008 // If the declaration we found is invalid, skip it.
3009 if (D->isInvalidDecl()) {
3010 F.erase();
3011 continue;
3012 }
3013
Richard Smithb8b41d32013-10-07 19:57:58 +00003014 bool IsRaw = false;
3015 bool IsTemplate = false;
3016 bool IsStringTemplate = false;
3017 bool IsExactMatch = false;
3018
Richard Smithbcc22fc2012-03-09 08:00:36 +00003019 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3020 if (FD->getNumParams() == 1 &&
3021 FD->getParamDecl(0)->getType()->getAs<PointerType>())
3022 IsRaw = true;
Richard Smith550de452013-01-15 07:12:59 +00003023 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003024 IsExactMatch = true;
3025 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
3026 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
3027 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
3028 IsExactMatch = false;
3029 break;
3030 }
3031 }
3032 }
3033 }
Richard Smithb8b41d32013-10-07 19:57:58 +00003034 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
3035 TemplateParameterList *Params = FD->getTemplateParameters();
3036 if (Params->size() == 1)
3037 IsTemplate = true;
3038 else
3039 IsStringTemplate = true;
3040 }
Richard Smithbcc22fc2012-03-09 08:00:36 +00003041
3042 if (IsExactMatch) {
3043 FoundExactMatch = true;
Richard Smithb8b41d32013-10-07 19:57:58 +00003044 AllowRaw = false;
3045 AllowTemplate = false;
3046 AllowStringTemplate = false;
3047 if (FoundRaw || FoundTemplate || FoundStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003048 // Go through again and remove the raw and template decls we've
3049 // already found.
3050 F.restart();
Richard Smithb8b41d32013-10-07 19:57:58 +00003051 FoundRaw = FoundTemplate = FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003052 }
Richard Smithb8b41d32013-10-07 19:57:58 +00003053 } else if (AllowRaw && IsRaw) {
3054 FoundRaw = true;
3055 } else if (AllowTemplate && IsTemplate) {
3056 FoundTemplate = true;
3057 } else if (AllowStringTemplate && IsStringTemplate) {
3058 FoundStringTemplate = true;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003059 } else {
3060 F.erase();
3061 }
3062 }
3063
3064 F.done();
3065
3066 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
3067 // parameter type, that is used in preference to a raw literal operator
3068 // or literal operator template.
3069 if (FoundExactMatch)
3070 return LOLR_Cooked;
3071
3072 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
3073 // operator template, but not both.
3074 if (FoundRaw && FoundTemplate) {
3075 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
Alp Tokera2794f92014-01-22 07:29:52 +00003076 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3077 NoteOverloadCandidate((*I)->getUnderlyingDecl()->getAsFunction());
Richard Smithbcc22fc2012-03-09 08:00:36 +00003078 return LOLR_Error;
3079 }
3080
3081 if (FoundRaw)
3082 return LOLR_Raw;
3083
3084 if (FoundTemplate)
3085 return LOLR_Template;
3086
Richard Smithb8b41d32013-10-07 19:57:58 +00003087 if (FoundStringTemplate)
3088 return LOLR_StringTemplate;
3089
Richard Smithbcc22fc2012-03-09 08:00:36 +00003090 // Didn't find anything we could use.
3091 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
3092 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
Richard Smithb8b41d32013-10-07 19:57:58 +00003093 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
3094 << (AllowTemplate || AllowStringTemplate);
Richard Smithbcc22fc2012-03-09 08:00:36 +00003095 return LOLR_Error;
3096}
3097
John McCall8fe68082010-01-26 07:16:45 +00003098void ADLResult::insert(NamedDecl *New) {
3099 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
3100
3101 // If we haven't yet seen a decl for this key, or the last decl
3102 // was exactly this one, we're done.
Craig Topperc3ec1492014-05-26 06:22:03 +00003103 if (Old == nullptr || Old == New) {
John McCall8fe68082010-01-26 07:16:45 +00003104 Old = New;
3105 return;
3106 }
3107
3108 // Otherwise, decide which is a more recent redeclaration.
Alp Tokera2794f92014-01-22 07:29:52 +00003109 FunctionDecl *OldFD = Old->getAsFunction();
3110 FunctionDecl *NewFD = New->getAsFunction();
John McCall8fe68082010-01-26 07:16:45 +00003111
3112 FunctionDecl *Cursor = NewFD;
3113 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00003114 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00003115
3116 // If we got to the end without finding OldFD, OldFD is the newer
3117 // declaration; leave things as they are.
3118 if (!Cursor) return;
3119
3120 // If we do find OldFD, then NewFD is newer.
3121 if (Cursor == OldFD) break;
3122
3123 // Otherwise, keep looking.
3124 }
3125
3126 Old = New;
3127}
3128
Richard Smith100b24a2014-04-17 01:52:14 +00003129void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3130 ArrayRef<Expr *> Args, ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003131 // Find all of the associated namespaces and classes based on the
3132 // arguments we have.
3133 AssociatedNamespaceSet AssociatedNamespaces;
3134 AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00003135 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCallc7e8e792009-08-07 22:18:02 +00003136 AssociatedNamespaces,
3137 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003138
3139 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003140 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3141 // and let Y be the lookup set produced by argument dependent
3142 // lookup (defined as follows). If X contains [...] then Y is
3143 // empty. Otherwise Y is the set of declarations found in the
3144 // namespaces associated with the argument types as described
3145 // below. The set of declarations found by the lookup of the name
3146 // is the union of X and Y.
3147 //
3148 // Here, we compute Y and add its members to the overloaded
3149 // candidate set.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003150 for (auto *NS : AssociatedNamespaces) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003151 // When considering an associated namespace, the lookup is the
3152 // same as the lookup performed when the associated namespace is
3153 // used as a qualifier (3.4.3.2) except that:
3154 //
3155 // -- Any using-directives in the associated namespace are
3156 // ignored.
3157 //
John McCallc7e8e792009-08-07 22:18:02 +00003158 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003159 // associated classes are visible within their respective
3160 // namespaces even if they are not visible during an ordinary
3161 // lookup (11.4).
Aaron Ballman1e606f42014-07-15 22:03:49 +00003162 DeclContext::lookup_result R = NS->lookup(Name);
3163 for (auto *D : R) {
John McCallaa74a0c2009-08-28 07:59:38 +00003164 // If the only declaration here is an ordinary friend, consider
3165 // it only if it was declared in an associated classes.
Richard Smith541b38b2013-09-20 01:15:31 +00003166 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) {
3167 // If it's neither ordinarily visible nor a friend, we can't find it.
3168 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0)
3169 continue;
3170
Richard Smith64017682013-07-17 23:53:16 +00003171 bool DeclaredInAssociatedClass = false;
3172 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
3173 DeclContext *LexDC = DI->getLexicalDeclContext();
3174 if (isa<CXXRecordDecl>(LexDC) &&
3175 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) {
3176 DeclaredInAssociatedClass = true;
3177 break;
3178 }
3179 }
3180 if (!DeclaredInAssociatedClass)
John McCalld1e9d832009-08-11 06:59:38 +00003181 continue;
3182 }
Mike Stump11289f42009-09-09 15:08:12 +00003183
John McCall91f61fc2010-01-26 06:04:06 +00003184 if (isa<UsingShadowDecl>(D))
3185 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00003186
Richard Smith100b24a2014-04-17 01:52:14 +00003187 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D))
John McCall8fe68082010-01-26 07:16:45 +00003188 continue;
3189
Richard Smitha1431072015-06-12 01:32:13 +00003190 if (!isVisible(D) && !(D = findAcceptableDecl(*this, D)))
3191 continue;
3192
John McCall8fe68082010-01-26 07:16:45 +00003193 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00003194 }
3195 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003196}
Douglas Gregor2d435302009-12-30 17:04:44 +00003197
3198//----------------------------------------------------------------------------
3199// Search for all visible declarations.
3200//----------------------------------------------------------------------------
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00003201VisibleDeclConsumer::~VisibleDeclConsumer() { }
Douglas Gregor2d435302009-12-30 17:04:44 +00003202
Richard Smithe156254d2013-08-20 20:35:18 +00003203bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
3204
Douglas Gregor2d435302009-12-30 17:04:44 +00003205namespace {
3206
3207class ShadowContextRAII;
3208
3209class VisibleDeclsRecord {
3210public:
3211 /// \brief An entry in the shadow map, which is optimized to store a
3212 /// single declaration (the common case) but can also store a list
3213 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00003214 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00003215
3216private:
3217 /// \brief A mapping from declaration names to the declarations that have
3218 /// this name within a particular scope.
3219 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
3220
3221 /// \brief A list of shadow maps, which is used to model name hiding.
3222 std::list<ShadowMap> ShadowMaps;
3223
3224 /// \brief The declaration contexts we have already visited.
3225 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
3226
3227 friend class ShadowContextRAII;
3228
3229public:
3230 /// \brief Determine whether we have already visited this context
3231 /// (and, if not, note that we are going to visit that context now).
3232 bool visitedContext(DeclContext *Ctx) {
David Blaikie82e95a32014-11-19 07:49:47 +00003233 return !VisitedContexts.insert(Ctx).second;
Douglas Gregor2d435302009-12-30 17:04:44 +00003234 }
3235
Douglas Gregor39982192010-08-15 06:18:01 +00003236 bool alreadyVisitedContext(DeclContext *Ctx) {
3237 return VisitedContexts.count(Ctx);
3238 }
3239
Douglas Gregor2d435302009-12-30 17:04:44 +00003240 /// \brief Determine whether the given declaration is hidden in the
3241 /// current scope.
3242 ///
3243 /// \returns the declaration that hides the given declaration, or
3244 /// NULL if no such declaration exists.
3245 NamedDecl *checkHidden(NamedDecl *ND);
3246
3247 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00003248 void add(NamedDecl *ND) {
3249 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
3250 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003251};
3252
3253/// \brief RAII object that records when we've entered a shadow context.
3254class ShadowContextRAII {
3255 VisibleDeclsRecord &Visible;
3256
3257 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
3258
3259public:
3260 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
Benjamin Kramer3204b152015-05-29 19:42:19 +00003261 Visible.ShadowMaps.emplace_back();
Douglas Gregor2d435302009-12-30 17:04:44 +00003262 }
3263
3264 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00003265 Visible.ShadowMaps.pop_back();
3266 }
3267};
3268
3269} // end anonymous namespace
3270
Douglas Gregor2d435302009-12-30 17:04:44 +00003271NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00003272 // Look through using declarations.
3273 ND = ND->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003274
Douglas Gregor2d435302009-12-30 17:04:44 +00003275 unsigned IDNS = ND->getIdentifierNamespace();
3276 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
3277 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3278 SM != SMEnd; ++SM) {
3279 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
3280 if (Pos == SM->end())
3281 continue;
3282
Aaron Ballman1e606f42014-07-15 22:03:49 +00003283 for (auto *D : Pos->second) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003284 // A tag declaration does not hide a non-tag declaration.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003285 if (D->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003286 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00003287 Decl::IDNS_ObjCProtocol)))
3288 continue;
3289
3290 // Protocols are in distinct namespaces from everything else.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003291 if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor2d435302009-12-30 17:04:44 +00003292 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Aaron Ballman1e606f42014-07-15 22:03:49 +00003293 D->getIdentifierNamespace() != IDNS)
Douglas Gregor2d435302009-12-30 17:04:44 +00003294 continue;
3295
Douglas Gregor09bbc652010-01-14 15:47:35 +00003296 // Functions and function templates in the same scope overload
3297 // rather than hide. FIXME: Look for hiding based on function
3298 // signatures!
Aaron Ballman1e606f42014-07-15 22:03:49 +00003299 if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Alp Tokera2794f92014-01-22 07:29:52 +00003300 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00003301 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00003302 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003303
Douglas Gregor2d435302009-12-30 17:04:44 +00003304 // We've found a declaration that hides this one.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003305 return D;
Douglas Gregor2d435302009-12-30 17:04:44 +00003306 }
3307 }
3308
Craig Topperc3ec1492014-05-26 06:22:03 +00003309 return nullptr;
Douglas Gregor2d435302009-12-30 17:04:44 +00003310}
3311
3312static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
3313 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003314 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00003315 VisibleDeclConsumer &Consumer,
3316 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00003317 if (!Ctx)
3318 return;
3319
Douglas Gregor2d435302009-12-30 17:04:44 +00003320 // Make sure we don't visit the same context twice.
3321 if (Visited.visitedContext(Ctx->getPrimaryContext()))
3322 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003323
Richard Smith9e2341d2015-03-23 03:25:59 +00003324 // Outside C++, lookup results for the TU live on identifiers.
3325 if (isa<TranslationUnitDecl>(Ctx) &&
3326 !Result.getSema().getLangOpts().CPlusPlus) {
3327 auto &S = Result.getSema();
3328 auto &Idents = S.Context.Idents;
3329
3330 // Ensure all external identifiers are in the identifier table.
3331 if (IdentifierInfoLookup *External = Idents.getExternalIdentifierLookup()) {
3332 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
3333 for (StringRef Name = Iter->Next(); !Name.empty(); Name = Iter->Next())
3334 Idents.get(Name);
3335 }
3336
3337 // Walk all lookup results in the TU for each identifier.
3338 for (const auto &Ident : Idents) {
3339 for (auto I = S.IdResolver.begin(Ident.getValue()),
3340 E = S.IdResolver.end();
3341 I != E; ++I) {
3342 if (S.IdResolver.isDeclInScope(*I, Ctx)) {
3343 if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
3344 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3345 Visited.add(ND);
3346 }
3347 }
3348 }
3349 }
3350
3351 return;
3352 }
3353
Douglas Gregor7454c562010-07-02 20:37:36 +00003354 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3355 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3356
Douglas Gregor2d435302009-12-30 17:04:44 +00003357 // Enumerate all of the results in this context.
Richard Trieu20abd6b2015-04-15 03:48:48 +00003358 for (DeclContextLookupResult R : Ctx->lookups()) {
Richard Smith9e2341d2015-03-23 03:25:59 +00003359 for (auto *D : R) {
3360 if (auto *ND = Result.getAcceptableDecl(D)) {
3361 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3362 Visited.add(ND);
Douglas Gregora3b23b02010-12-09 21:44:02 +00003363 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003364 }
3365 }
3366
3367 // Traverse using directives for qualified name lookup.
3368 if (QualifiedNameLookup) {
3369 ShadowContextRAII Shadow(Visited);
Aaron Ballman804a7fb2014-03-17 17:14:12 +00003370 for (auto I : Ctx->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00003371 LookupVisibleDecls(I->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003372 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003373 }
3374 }
3375
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003376 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00003377 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00003378 if (!Record->hasDefinition())
3379 return;
3380
Aaron Ballman574705e2014-03-13 15:41:46 +00003381 for (const auto &B : Record->bases()) {
3382 QualType BaseType = B.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003383
Douglas Gregor2d435302009-12-30 17:04:44 +00003384 // Don't look into dependent bases, because name lookup can't look
3385 // there anyway.
3386 if (BaseType->isDependentType())
3387 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003388
Douglas Gregor2d435302009-12-30 17:04:44 +00003389 const RecordType *Record = BaseType->getAs<RecordType>();
3390 if (!Record)
3391 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003392
Douglas Gregor2d435302009-12-30 17:04:44 +00003393 // FIXME: It would be nice to be able to determine whether referencing
3394 // a particular member would be ambiguous. For example, given
3395 //
3396 // struct A { int member; };
3397 // struct B { int member; };
3398 // struct C : A, B { };
3399 //
3400 // void f(C *c) { c->### }
3401 //
3402 // accessing 'member' would result in an ambiguity. However, we
3403 // could be smart enough to qualify the member with the base
3404 // class, e.g.,
3405 //
3406 // c->B::member
3407 //
3408 // or
3409 //
3410 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003411
Douglas Gregor2d435302009-12-30 17:04:44 +00003412 // Find results in this base class (and its bases).
3413 ShadowContextRAII Shadow(Visited);
3414 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003415 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003416 }
3417 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003418
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003419 // Traverse the contexts of Objective-C classes.
3420 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3421 // Traverse categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003422 for (auto *Cat : IFace->visible_categories()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003423 ShadowContextRAII Shadow(Visited);
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003424 LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003425 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003426 }
3427
3428 // Traverse protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003429 for (auto *I : IFace->all_referenced_protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003430 ShadowContextRAII Shadow(Visited);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003431 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003432 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003433 }
3434
3435 // Traverse the superclass.
3436 if (IFace->getSuperClass()) {
3437 ShadowContextRAII Shadow(Visited);
3438 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003439 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003440 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003441
Douglas Gregor0b59e802010-04-19 18:02:19 +00003442 // If there is an implementation, traverse it. We do this to find
3443 // synthesized ivars.
3444 if (IFace->getImplementation()) {
3445 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003446 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky13668f22012-04-03 20:26:45 +00003447 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor0b59e802010-04-19 18:02:19 +00003448 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003449 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003450 for (auto *I : Protocol->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003451 ShadowContextRAII Shadow(Visited);
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003452 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003453 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003454 }
3455 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003456 for (auto *I : Category->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003457 ShadowContextRAII Shadow(Visited);
Aaron Ballman19a41762014-03-14 12:55:57 +00003458 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003459 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003460 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003461
Douglas Gregor0b59e802010-04-19 18:02:19 +00003462 // If there is an implementation, traverse it.
3463 if (Category->getImplementation()) {
3464 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003465 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00003466 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003467 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003468 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003469}
3470
3471static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3472 UnqualUsingDirectiveSet &UDirs,
3473 VisibleDeclConsumer &Consumer,
3474 VisibleDeclsRecord &Visited) {
3475 if (!S)
3476 return;
3477
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003478 if (!S->getEntity() ||
3479 (!S->getParent() &&
Ted Kremenekc37877d2013-10-08 17:08:03 +00003480 !Visited.alreadyVisitedContext(S->getEntity())) ||
3481 (S->getEntity())->isFunctionOrMethod()) {
Richard Smith541b38b2013-09-20 01:15:31 +00003482 FindLocalExternScope FindLocals(Result);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003483 // Walk through the declarations in this Scope.
Aaron Ballman35c54952014-03-17 16:55:25 +00003484 for (auto *D : S->decls()) {
3485 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Douglas Gregor4a814562011-12-14 16:03:29 +00003486 if ((ND = Result.getAcceptableDecl(ND))) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003487 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003488 Visited.add(ND);
3489 }
3490 }
3491 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003492
Douglas Gregor66230062010-03-15 14:33:29 +00003493 // FIXME: C++ [temp.local]p8
Craig Topperc3ec1492014-05-26 06:22:03 +00003494 DeclContext *Entity = nullptr;
Douglas Gregor4f248632010-01-01 17:44:25 +00003495 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003496 // Look into this scope's declaration context, along with any of its
3497 // parent lookup contexts (e.g., enclosing classes), up to the point
3498 // where we hit the context stored in the next outer scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00003499 Entity = S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00003500 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003501
Douglas Gregorea166062010-03-15 15:26:48 +00003502 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00003503 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003504 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3505 if (Method->isInstanceMethod()) {
3506 // For instance methods, look for ivars in the method's interface.
3507 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3508 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003509 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003510 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Richard Smithe156254d2013-08-20 20:35:18 +00003511 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003512 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003513 }
3514
3515 // We've already performed all of the name lookup that we need
3516 // to for Objective-C methods; the next context will be the
3517 // outer scope.
3518 break;
3519 }
3520
Douglas Gregor2d435302009-12-30 17:04:44 +00003521 if (Ctx->isFunctionOrMethod())
3522 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003523
3524 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003525 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003526 }
3527 } else if (!S->getParent()) {
3528 // Look into the translation unit scope. We walk through the translation
3529 // unit's declaration context, because the Scope itself won't have all of
3530 // the declarations if we loaded a precompiled header.
3531 // FIXME: We would like the translation unit's Scope object to point to the
3532 // translation unit, so we don't need this special "if" branch. However,
3533 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003534 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00003535 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003536 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00003537 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003538 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003539 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003540 }
3541
Douglas Gregor2d435302009-12-30 17:04:44 +00003542 if (Entity) {
3543 // Lookup visible declarations in any namespaces found by using
3544 // directives.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003545 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
3546 LookupVisibleDecls(const_cast<DeclContext *>(UUE.getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003547 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003548 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003549 }
3550
3551 // Lookup names in the parent scope.
3552 ShadowContextRAII Shadow(Visited);
3553 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3554}
3555
3556void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003557 VisibleDeclConsumer &Consumer,
3558 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003559 // Determine the set of using directives available during
3560 // unqualified name lookup.
3561 Scope *Initial = S;
3562 UnqualUsingDirectiveSet UDirs;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003563 if (getLangOpts().CPlusPlus) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003564 // Find the first namespace or translation-unit scope.
3565 while (S && !isNamespaceOrTranslationUnitScope(S))
3566 S = S->getParent();
3567
3568 UDirs.visitScopeChain(Initial, S);
3569 }
3570 UDirs.done();
3571
3572 // Look for visible declarations.
3573 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003574 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003575 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003576 if (!IncludeGlobalScope)
3577 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003578 ShadowContextRAII Shadow(Visited);
3579 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3580}
3581
3582void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003583 VisibleDeclConsumer &Consumer,
3584 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003585 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003586 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003587 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003588 if (!IncludeGlobalScope)
3589 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003590 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003591 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003592 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003593}
3594
Chris Lattner43e7f312011-02-18 02:08:43 +00003595/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003596/// If GnuLabelLoc is a valid source location, then this is a definition
3597/// of an __label__ label name, otherwise it is a normal label definition
3598/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003599LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003600 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003601 // Do a lookup to see if we have a label with this name already.
Craig Topperc3ec1492014-05-26 06:22:03 +00003602 NamedDecl *Res = nullptr;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003603
3604 if (GnuLabelLoc.isValid()) {
3605 // Local label definitions always shadow existing labels.
3606 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3607 Scope *S = CurScope;
3608 PushOnScopeChains(Res, S, true);
3609 return cast<LabelDecl>(Res);
3610 }
3611
3612 // Not a GNU local label.
3613 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3614 // If we found a label, check to see if it is in the same context as us.
3615 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003616 if (Res && Res->getDeclContext() != CurContext)
Craig Topperc3ec1492014-05-26 06:22:03 +00003617 Res = nullptr;
3618 if (!Res) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003619 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003620 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3621 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003622 assert(S && "Not in a function?");
3623 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003624 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003625 return cast<LabelDecl>(Res);
3626}
3627
3628//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003629// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003630//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003631
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003632static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3633 TypoCorrection &Candidate) {
3634 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3635 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3636}
3637
3638static void LookupPotentialTypoResult(Sema &SemaRef,
3639 LookupResult &Res,
3640 IdentifierInfo *Name,
3641 Scope *S, CXXScopeSpec *SS,
3642 DeclContext *MemberContext,
3643 bool EnteringContext,
3644 bool isObjCIvarLookup,
3645 bool FindHidden);
3646
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003647/// \brief Check whether the declarations found for a typo correction are
3648/// visible, and if none of them are, convert the correction to an 'import
3649/// a module' correction.
3650static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
3651 if (TC.begin() == TC.end())
3652 return;
3653
3654 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3655
3656 for (/**/; DI != DE; ++DI)
3657 if (!LookupResult::isVisible(SemaRef, *DI))
3658 break;
3659 // Nothing to do if all decls are visible.
3660 if (DI == DE)
3661 return;
3662
3663 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3664 bool AnyVisibleDecls = !NewDecls.empty();
3665
3666 for (/**/; DI != DE; ++DI) {
3667 NamedDecl *VisibleDecl = *DI;
3668 if (!LookupResult::isVisible(SemaRef, *DI))
3669 VisibleDecl = findAcceptableDecl(SemaRef, *DI);
3670
3671 if (VisibleDecl) {
3672 if (!AnyVisibleDecls) {
3673 // Found a visible decl, discard all hidden ones.
3674 AnyVisibleDecls = true;
3675 NewDecls.clear();
3676 }
3677 NewDecls.push_back(VisibleDecl);
3678 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
3679 NewDecls.push_back(*DI);
3680 }
3681
3682 if (NewDecls.empty())
3683 TC = TypoCorrection();
3684 else {
3685 TC.setCorrectionDecls(NewDecls);
3686 TC.setRequiresImport(!AnyVisibleDecls);
3687 }
3688}
3689
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003690// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3691// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3692// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3693static void getNestedNameSpecifierIdentifiers(
3694 NestedNameSpecifier *NNS,
3695 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3696 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3697 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3698 else
3699 Identifiers.clear();
3700
3701 const IdentifierInfo *II = nullptr;
3702
3703 switch (NNS->getKind()) {
3704 case NestedNameSpecifier::Identifier:
3705 II = NNS->getAsIdentifier();
3706 break;
3707
3708 case NestedNameSpecifier::Namespace:
3709 if (NNS->getAsNamespace()->isAnonymousNamespace())
3710 return;
3711 II = NNS->getAsNamespace()->getIdentifier();
3712 break;
3713
3714 case NestedNameSpecifier::NamespaceAlias:
3715 II = NNS->getAsNamespaceAlias()->getIdentifier();
3716 break;
3717
3718 case NestedNameSpecifier::TypeSpecWithTemplate:
3719 case NestedNameSpecifier::TypeSpec:
3720 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3721 break;
3722
3723 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00003724 case NestedNameSpecifier::Super:
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003725 return;
3726 }
3727
3728 if (II)
3729 Identifiers.push_back(II);
3730}
3731
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003732void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003733 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003734 // Don't consider hidden names for typo correction.
3735 if (Hiding)
3736 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003737
Douglas Gregor2d435302009-12-30 17:04:44 +00003738 // Only consider entities with identifiers for names, ignoring
3739 // special names (constructors, overloaded operators, selectors,
3740 // etc.).
3741 IdentifierInfo *Name = ND->getIdentifier();
3742 if (!Name)
3743 return;
3744
Richard Smithe156254d2013-08-20 20:35:18 +00003745 // Only consider visible declarations and declarations from modules with
3746 // names that exactly match.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003747 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo &&
Richard Smithe156254d2013-08-20 20:35:18 +00003748 !findAcceptableDecl(SemaRef, ND))
3749 return;
3750
Douglas Gregor57756ea2010-10-14 22:11:03 +00003751 FoundName(Name->getName());
3752}
3753
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003754void TypoCorrectionConsumer::FoundName(StringRef Name) {
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003755 // Compute the edit distance between the typo and the name of this
3756 // entity, and add the identifier to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003757 addName(Name, nullptr);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003758}
3759
3760void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3761 // Compute the edit distance between the typo and this keyword,
3762 // and add the keyword to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003763 addName(Keyword, nullptr, nullptr, true);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003764}
3765
3766void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
3767 NestedNameSpecifier *NNS, bool isKeyword) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003768 // Use a simple length-based heuristic to determine the minimum possible
3769 // edit distance. If the minimum isn't good enough, bail out early.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003770 StringRef TypoStr = Typo->getName();
3771 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
3772 if (MinED && TypoStr.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00003773 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003774
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003775 // Compute an upper bound on the allowable edit distance, so that the
3776 // edit-distance algorithm can short-circuit.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003777 unsigned UpperBound = (TypoStr.size() + 2) / 3 + 1;
3778 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003779 if (ED >= UpperBound) return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003780
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003781 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003782 if (isKeyword) TC.makeKeyword();
Kaelyn Takata0a313022014-11-20 22:06:26 +00003783 TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003784 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003785}
3786
Kaelyn Takatad2287c32014-10-27 18:07:13 +00003787static const unsigned MaxTypoDistanceResultSets = 5;
3788
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003789void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003790 StringRef TypoStr = Typo->getName();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003791 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003792
3793 // For very short typos, ignore potential corrections that have a different
3794 // base identifier from the typo or which have a normalized edit distance
3795 // longer than the typo itself.
3796 if (TypoStr.size() < 3 &&
3797 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
3798 return;
3799
3800 // If the correction is resolved but is not viable, ignore it.
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003801 if (Correction.isResolved()) {
3802 checkCorrectionVisibility(SemaRef, Correction);
3803 if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
3804 return;
3805 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003806
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003807 TypoResultList &CList =
3808 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003809
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003810 if (!CList.empty() && !CList.back().isResolved())
3811 CList.pop_back();
3812 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3813 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3814 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3815 RI != RIEnd; ++RI) {
3816 // If the Correction refers to a decl already in the result list,
3817 // replace the existing result if the string representation of Correction
3818 // comes before the current result alphabetically, then stop as there is
3819 // nothing more to be done to add Correction to the candidate set.
3820 if (RI->getCorrectionDecl() == NewND) {
3821 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3822 *RI = Correction;
3823 return;
3824 }
3825 }
3826 }
3827 if (CList.empty() || Correction.isResolved())
3828 CList.push_back(Correction);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003829
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003830 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003831 CorrectionResults.erase(std::prev(CorrectionResults.end()));
3832}
3833
3834void TypoCorrectionConsumer::addNamespaces(
3835 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
3836 SearchNamespaces = true;
3837
3838 for (auto KNPair : KnownNamespaces)
3839 Namespaces.addNameSpecifier(KNPair.first);
3840
3841 bool SSIsTemplate = false;
3842 if (NestedNameSpecifier *NNS =
3843 (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
3844 if (const Type *T = NNS->getAsType())
3845 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
3846 }
3847 for (const auto *TI : SemaRef.getASTContext().types()) {
Kaelyn Takata26487022015-10-01 22:38:51 +00003848 if (!TI->isClassType() && isa<TemplateSpecializationType>(TI))
3849 continue;
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003850 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
3851 CD = CD->getCanonicalDecl();
3852 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
3853 !CD->isUnion() && CD->getIdentifier() &&
3854 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
3855 (CD->isBeingDefined() || CD->isCompleteDefinition()))
3856 Namespaces.addNameSpecifier(CD);
3857 }
3858 }
3859}
3860
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003861const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
3862 if (++CurrentTCIndex < ValidatedCorrections.size())
3863 return ValidatedCorrections[CurrentTCIndex];
3864
3865 CurrentTCIndex = ValidatedCorrections.size();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003866 while (!CorrectionResults.empty()) {
3867 auto DI = CorrectionResults.begin();
3868 if (DI->second.empty()) {
3869 CorrectionResults.erase(DI);
3870 continue;
3871 }
3872
3873 auto RI = DI->second.begin();
3874 if (RI->second.empty()) {
3875 DI->second.erase(RI);
3876 performQualifiedLookups();
3877 continue;
3878 }
3879
3880 TypoCorrection TC = RI->second.pop_back_val();
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003881 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003882 ValidatedCorrections.push_back(TC);
3883 return ValidatedCorrections[CurrentTCIndex];
3884 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003885 }
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003886 return ValidatedCorrections[0]; // The empty correction.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003887}
3888
3889bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
3890 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
3891 DeclContext *TempMemberContext = MemberContext;
Kaelyn Takata6c759512014-10-27 18:07:37 +00003892 CXXScopeSpec *TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003893retry_lookup:
3894 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
3895 EnteringContext,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00003896 CorrectionValidator->IsObjCIvarLookup,
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003897 Name == Typo && !Candidate.WillReplaceSpecifier());
3898 switch (Result.getResultKind()) {
3899 case LookupResult::NotFound:
3900 case LookupResult::NotFoundInCurrentInstantiation:
3901 case LookupResult::FoundUnresolvedValue:
3902 if (TempSS) {
3903 // Immediately retry the lookup without the given CXXScopeSpec
3904 TempSS = nullptr;
3905 Candidate.WillReplaceSpecifier(true);
3906 goto retry_lookup;
3907 }
3908 if (TempMemberContext) {
3909 if (SS && !TempSS)
Kaelyn Takata6c759512014-10-27 18:07:37 +00003910 TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003911 TempMemberContext = nullptr;
3912 goto retry_lookup;
3913 }
3914 if (SearchNamespaces)
3915 QualifiedResults.push_back(Candidate);
3916 break;
3917
3918 case LookupResult::Ambiguous:
3919 // We don't deal with ambiguities.
3920 break;
3921
3922 case LookupResult::Found:
3923 case LookupResult::FoundOverloaded:
3924 // Store all of the Decls for overloaded symbols
3925 for (auto *TRD : Result)
3926 Candidate.addCorrectionDecl(TRD);
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003927 checkCorrectionVisibility(SemaRef, Candidate);
Kaelyn Takata89c881b2014-10-27 18:07:29 +00003928 if (!isCandidateViable(*CorrectionValidator, Candidate)) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003929 if (SearchNamespaces)
3930 QualifiedResults.push_back(Candidate);
3931 break;
3932 }
Kaelyn Takata20deb1d2015-01-28 00:46:09 +00003933 Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003934 return true;
3935 }
3936 return false;
3937}
3938
3939void TypoCorrectionConsumer::performQualifiedLookups() {
3940 unsigned TypoLen = Typo->getName().size();
3941 for (auto QR : QualifiedResults) {
3942 for (auto NSI : Namespaces) {
3943 DeclContext *Ctx = NSI.DeclCtx;
3944 const Type *NSType = NSI.NameSpecifier->getAsType();
3945
3946 // If the current NestedNameSpecifier refers to a class and the
3947 // current correction candidate is the name of that class, then skip
3948 // it as it is unlikely a qualified version of the class' constructor
3949 // is an appropriate correction.
Hans Wennborgdcfba332015-10-06 23:40:43 +00003950 if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() :
3951 nullptr) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003952 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
3953 continue;
3954 }
3955
3956 TypoCorrection TC(QR);
3957 TC.ClearCorrectionDecls();
3958 TC.setCorrectionSpecifier(NSI.NameSpecifier);
3959 TC.setQualifierDistance(NSI.EditDistance);
3960 TC.setCallbackDistance(0); // Reset the callback distance
3961
3962 // If the current correction candidate and namespace combination are
3963 // too far away from the original typo based on the normalized edit
3964 // distance, then skip performing a qualified name lookup.
3965 unsigned TmpED = TC.getEditDistance(true);
3966 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
3967 TypoLen / TmpED < 3)
3968 continue;
3969
3970 Result.clear();
3971 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
3972 if (!SemaRef.LookupQualifiedName(Result, Ctx))
3973 continue;
3974
3975 // Any corrections added below will be validated in subsequent
3976 // iterations of the main while() loop over the Consumer's contents.
3977 switch (Result.getResultKind()) {
3978 case LookupResult::Found:
3979 case LookupResult::FoundOverloaded: {
3980 if (SS && SS->isValid()) {
3981 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
3982 std::string OldQualified;
3983 llvm::raw_string_ostream OldOStream(OldQualified);
3984 SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
3985 OldOStream << Typo->getName();
3986 // If correction candidate would be an identical written qualified
3987 // identifer, then the existing CXXScopeSpec probably included a
3988 // typedef that didn't get accounted for properly.
3989 if (OldOStream.str() == NewQualified)
3990 break;
3991 }
3992 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
3993 TRD != TRDEnd; ++TRD) {
3994 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
3995 NSType ? NSType->getAsCXXRecordDecl()
3996 : nullptr,
3997 TRD.getPair()) == Sema::AR_accessible)
3998 TC.addCorrectionDecl(*TRD);
3999 }
Kaelyn Takata0a313022014-11-20 22:06:26 +00004000 if (TC.isResolved()) {
4001 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004002 addCorrection(TC);
Kaelyn Takata0a313022014-11-20 22:06:26 +00004003 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004004 break;
4005 }
4006 case LookupResult::NotFound:
4007 case LookupResult::NotFoundInCurrentInstantiation:
4008 case LookupResult::Ambiguous:
4009 case LookupResult::FoundUnresolvedValue:
4010 break;
4011 }
4012 }
4013 }
4014 QualifiedResults.clear();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004015}
4016
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004017TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
4018 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
Benjamin Kramer15537272015-03-13 16:10:42 +00004019 : Context(Context), CurContextChain(buildContextChain(CurContext)) {
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004020 if (NestedNameSpecifier *NNS =
4021 CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
4022 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
4023 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4024
4025 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
4026 }
4027 // Build the list of identifiers that would be used for an absolute
4028 // (from the global context) NestedNameSpecifier referring to the current
4029 // context.
4030 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
4031 CEnd = CurContextChain.rend();
4032 C != CEnd; ++C) {
4033 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
4034 CurContextIdentifiers.push_back(ND->getIdentifier());
4035 }
4036
4037 // Add the global context as a NestedNameSpecifier
Hans Wennborg66010132014-06-11 21:24:13 +00004038 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
4039 NestedNameSpecifier::GlobalSpecifier(Context), 1};
4040 DistanceMap[1].push_back(SI);
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004041}
4042
Kaelyn Takata7dcc0e62014-06-11 18:07:08 +00004043auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
4044 DeclContext *Start) -> DeclContextList {
Nick Lewycky0d9b3192013-04-08 21:55:21 +00004045 assert(Start && "Building a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004046 DeclContextList Chain;
Craig Topperc3ec1492014-05-26 06:22:03 +00004047 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004048 DC = DC->getLookupParent()) {
4049 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
4050 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
4051 !(ND && ND->isAnonymousNamespace()))
4052 Chain.push_back(DC->getPrimaryContext());
4053 }
4054 return Chain;
4055}
4056
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004057unsigned
4058TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
4059 DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004060 unsigned NumSpecifiers = 0;
4061 for (DeclContextList::reverse_iterator C = DeclChain.rbegin(),
4062 CEnd = DeclChain.rend();
4063 C != CEnd; ++C) {
4064 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) {
4065 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
4066 ++NumSpecifiers;
4067 } else if (RecordDecl *RD = dyn_cast_or_null<RecordDecl>(*C)) {
4068 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
4069 RD->getTypeForDecl());
4070 ++NumSpecifiers;
4071 }
4072 }
4073 return NumSpecifiers;
4074}
4075
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004076void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
4077 DeclContext *Ctx) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004078 NestedNameSpecifier *NNS = nullptr;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004079 unsigned NumSpecifiers = 0;
Kaelyn Takata0fc75192014-06-11 18:06:56 +00004080 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004081 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
4082
4083 // Eliminate common elements from the two DeclContext chains.
4084 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
4085 CEnd = CurContextChain.rend();
4086 C != CEnd && !NamespaceDeclChain.empty() &&
4087 NamespaceDeclChain.back() == *C; ++C) {
4088 NamespaceDeclChain.pop_back();
4089 }
4090
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004091 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004092 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004093
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004094 // Add an explicit leading '::' specifier if needed.
4095 if (NamespaceDeclChain.empty()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004096 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004097 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004098 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004099 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004100 } else if (NamedDecl *ND =
4101 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004102 IdentifierInfo *Name = ND->getIdentifier();
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004103 bool SameNameSpecifier = false;
4104 if (std::find(CurNameSpecifierIdentifiers.begin(),
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004105 CurNameSpecifierIdentifiers.end(),
4106 Name) != CurNameSpecifierIdentifiers.end()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004107 std::string NewNameSpecifier;
4108 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
4109 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
4110 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4111 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4112 SpecifierOStream.flush();
4113 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004114 }
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004115 if (SameNameSpecifier ||
4116 std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
4117 Name) != CurContextIdentifiers.end()) {
4118 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4119 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4120 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004121 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004122 }
4123 }
4124
4125 // If the built NestedNameSpecifier would be replacing an existing
4126 // NestedNameSpecifier, use the number of component identifiers that
4127 // would need to be changed as the edit distance instead of the number
4128 // of components in the built NestedNameSpecifier.
4129 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
4130 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
4131 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4132 NumSpecifiers = llvm::ComputeEditDistance(
Craig Topper8c2a2a02014-08-30 16:55:39 +00004133 llvm::makeArrayRef(CurNameSpecifierIdentifiers),
4134 llvm::makeArrayRef(NewNameSpecifierIdentifiers));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004135 }
4136
Hans Wennborg66010132014-06-11 21:24:13 +00004137 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
4138 DistanceMap[NumSpecifiers].push_back(SI);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004139}
4140
Douglas Gregord507d772010-10-20 03:06:34 +00004141/// \brief Perform name lookup for a possible result for typo correction.
4142static void LookupPotentialTypoResult(Sema &SemaRef,
4143 LookupResult &Res,
4144 IdentifierInfo *Name,
4145 Scope *S, CXXScopeSpec *SS,
4146 DeclContext *MemberContext,
4147 bool EnteringContext,
Richard Smithe156254d2013-08-20 20:35:18 +00004148 bool isObjCIvarLookup,
4149 bool FindHidden) {
Douglas Gregord507d772010-10-20 03:06:34 +00004150 Res.suppressDiagnostics();
4151 Res.clear();
4152 Res.setLookupName(Name);
Richard Smithe156254d2013-08-20 20:35:18 +00004153 Res.setAllowHidden(FindHidden);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004154 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00004155 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004156 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00004157 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
4158 Res.addDecl(Ivar);
4159 Res.resolveKind();
4160 return;
4161 }
4162 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004163
Douglas Gregord507d772010-10-20 03:06:34 +00004164 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
4165 Res.addDecl(Prop);
4166 Res.resolveKind();
4167 return;
4168 }
4169 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004170
Douglas Gregord507d772010-10-20 03:06:34 +00004171 SemaRef.LookupQualifiedName(Res, MemberContext);
4172 return;
4173 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004174
4175 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00004176 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004177
Douglas Gregord507d772010-10-20 03:06:34 +00004178 // Fake ivar lookup; this should really be part of
4179 // LookupParsedName.
4180 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
4181 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004182 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00004183 (Res.isSingleResult() &&
4184 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004185 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00004186 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
4187 Res.addDecl(IV);
4188 Res.resolveKind();
4189 }
4190 }
4191 }
4192}
4193
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004194/// \brief Add keywords to the consumer as possible typo corrections.
4195static void AddKeywordsToConsumer(Sema &SemaRef,
4196 TypoCorrectionConsumer &Consumer,
Richard Smithb3a1df02012-06-08 21:35:42 +00004197 Scope *S, CorrectionCandidateCallback &CCC,
4198 bool AfterNestedNameSpecifier) {
4199 if (AfterNestedNameSpecifier) {
4200 // For 'X::', we know exactly which keywords can appear next.
4201 Consumer.addKeywordResult("template");
4202 if (CCC.WantExpressionKeywords)
4203 Consumer.addKeywordResult("operator");
4204 return;
4205 }
4206
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004207 if (CCC.WantObjCSuper)
4208 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004209
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004210 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004211 // Add type-specifier keywords to the set of results.
Craig Topperd6d31ac2013-07-15 08:24:27 +00004212 static const char *const CTypeSpecs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004213 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00004214 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004215 "_Complex", "_Imaginary",
4216 // storage-specifiers as well
4217 "extern", "inline", "static", "typedef"
4218 };
4219
Craig Toppere5ce8312013-07-15 03:38:40 +00004220 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004221 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
4222 Consumer.addKeywordResult(CTypeSpecs[I]);
4223
David Blaikiebbafb8a2012-03-11 07:00:24 +00004224 if (SemaRef.getLangOpts().C99)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004225 Consumer.addKeywordResult("restrict");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004226 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004227 Consumer.addKeywordResult("bool");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004228 else if (SemaRef.getLangOpts().C99)
Douglas Gregor3b22a882011-07-01 21:27:45 +00004229 Consumer.addKeywordResult("_Bool");
4230
David Blaikiebbafb8a2012-03-11 07:00:24 +00004231 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004232 Consumer.addKeywordResult("class");
4233 Consumer.addKeywordResult("typename");
4234 Consumer.addKeywordResult("wchar_t");
4235
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004236 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004237 Consumer.addKeywordResult("char16_t");
4238 Consumer.addKeywordResult("char32_t");
4239 Consumer.addKeywordResult("constexpr");
4240 Consumer.addKeywordResult("decltype");
4241 Consumer.addKeywordResult("thread_local");
4242 }
4243 }
4244
David Blaikiebbafb8a2012-03-11 07:00:24 +00004245 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004246 Consumer.addKeywordResult("typeof");
Kaelyn Takatab04846b2014-07-28 18:14:02 +00004247 } else if (CCC.WantFunctionLikeCasts) {
4248 static const char *const CastableTypeSpecs[] = {
4249 "char", "double", "float", "int", "long", "short",
4250 "signed", "unsigned", "void"
4251 };
4252 for (auto *kw : CastableTypeSpecs)
4253 Consumer.addKeywordResult(kw);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004254 }
4255
David Blaikiebbafb8a2012-03-11 07:00:24 +00004256 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004257 Consumer.addKeywordResult("const_cast");
4258 Consumer.addKeywordResult("dynamic_cast");
4259 Consumer.addKeywordResult("reinterpret_cast");
4260 Consumer.addKeywordResult("static_cast");
4261 }
4262
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004263 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004264 Consumer.addKeywordResult("sizeof");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004265 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004266 Consumer.addKeywordResult("false");
4267 Consumer.addKeywordResult("true");
4268 }
4269
David Blaikiebbafb8a2012-03-11 07:00:24 +00004270 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topperd6d31ac2013-07-15 08:24:27 +00004271 static const char *const CXXExprs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004272 "delete", "new", "operator", "throw", "typeid"
4273 };
Craig Toppere5ce8312013-07-15 03:38:40 +00004274 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004275 for (unsigned I = 0; I != NumCXXExprs; ++I)
4276 Consumer.addKeywordResult(CXXExprs[I]);
4277
4278 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
4279 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
4280 Consumer.addKeywordResult("this");
4281
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004282 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004283 Consumer.addKeywordResult("alignof");
4284 Consumer.addKeywordResult("nullptr");
4285 }
4286 }
Jordan Rose58d54722012-06-30 21:33:57 +00004287
4288 if (SemaRef.getLangOpts().C11) {
4289 // FIXME: We should not suggest _Alignof if the alignof macro
4290 // is present.
4291 Consumer.addKeywordResult("_Alignof");
4292 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004293 }
4294
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004295 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004296 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
4297 // Statements.
Craig Topperd6d31ac2013-07-15 08:24:27 +00004298 static const char *const CStmts[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004299 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Toppere5ce8312013-07-15 03:38:40 +00004300 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004301 for (unsigned I = 0; I != NumCStmts; ++I)
4302 Consumer.addKeywordResult(CStmts[I]);
4303
David Blaikiebbafb8a2012-03-11 07:00:24 +00004304 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004305 Consumer.addKeywordResult("catch");
4306 Consumer.addKeywordResult("try");
4307 }
4308
4309 if (S && S->getBreakParent())
4310 Consumer.addKeywordResult("break");
4311
4312 if (S && S->getContinueParent())
4313 Consumer.addKeywordResult("continue");
4314
4315 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
4316 Consumer.addKeywordResult("case");
4317 Consumer.addKeywordResult("default");
4318 }
4319 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004320 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004321 Consumer.addKeywordResult("namespace");
4322 Consumer.addKeywordResult("template");
4323 }
4324
4325 if (S && S->isClassScope()) {
4326 Consumer.addKeywordResult("explicit");
4327 Consumer.addKeywordResult("friend");
4328 Consumer.addKeywordResult("mutable");
4329 Consumer.addKeywordResult("private");
4330 Consumer.addKeywordResult("protected");
4331 Consumer.addKeywordResult("public");
4332 Consumer.addKeywordResult("virtual");
4333 }
4334 }
4335
David Blaikiebbafb8a2012-03-11 07:00:24 +00004336 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004337 Consumer.addKeywordResult("using");
4338
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004339 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004340 Consumer.addKeywordResult("static_assert");
4341 }
4342 }
4343}
4344
Kaelyn Takata6c759512014-10-27 18:07:37 +00004345std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
4346 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4347 Scope *S, CXXScopeSpec *SS,
4348 std::unique_ptr<CorrectionCandidateCallback> CCC,
4349 DeclContext *MemberContext, bool EnteringContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004350 const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00004351
4352 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4353 DisableTypoCorrection)
4354 return nullptr;
4355
4356 // In Microsoft mode, don't perform typo correction in a template member
4357 // function dependent context because it interferes with the "lookup into
4358 // dependent bases of class templates" feature.
4359 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
4360 isa<CXXMethodDecl>(CurContext))
4361 return nullptr;
4362
4363 // We only attempt to correct typos for identifiers.
4364 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4365 if (!Typo)
4366 return nullptr;
4367
4368 // If the scope specifier itself was invalid, don't try to correct
4369 // typos.
4370 if (SS && SS->isInvalid())
4371 return nullptr;
4372
4373 // Never try to correct typos during template deduction or
4374 // instantiation.
4375 if (!ActiveTemplateInstantiations.empty())
4376 return nullptr;
4377
4378 // Don't try to correct 'super'.
4379 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4380 return nullptr;
4381
4382 // Abort if typo correction already failed for this specific typo.
4383 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4384 if (locs != TypoCorrectionFailures.end() &&
4385 locs->second.count(TypoName.getLoc()))
4386 return nullptr;
4387
4388 // Don't try to correct the identifier "vector" when in AltiVec mode.
4389 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4390 // remove this workaround.
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00004391 if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector"))
Kaelyn Takata6c759512014-10-27 18:07:37 +00004392 return nullptr;
4393
Nick Lewycky24653262014-12-16 21:39:02 +00004394 // Provide a stop gap for files that are just seriously broken. Trying
4395 // to correct all typos can turn into a HUGE performance penalty, causing
4396 // some files to take minutes to get rejected by the parser.
4397 unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
4398 if (Limit && TyposCorrected >= Limit)
4399 return nullptr;
4400 ++TyposCorrected;
4401
Kaelyn Takata6c759512014-10-27 18:07:37 +00004402 // If we're handling a missing symbol error, using modules, and the
4403 // special search all modules option is used, look for a missing import.
4404 if (ErrorRecovery && getLangOpts().Modules &&
4405 getLangOpts().ModulesSearchAll) {
4406 // The following has the side effect of loading the missing module.
4407 getModuleLoader().lookupMissingImports(Typo->getName(),
4408 TypoName.getLocStart());
4409 }
4410
4411 CorrectionCandidateCallback &CCCRef = *CCC;
4412 auto Consumer = llvm::make_unique<TypoCorrectionConsumer>(
4413 *this, TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
4414 EnteringContext);
4415
Kaelyn Takata6c759512014-10-27 18:07:37 +00004416 // Perform name lookup to find visible, similarly-named entities.
Nick Lewycky24653262014-12-16 21:39:02 +00004417 bool IsUnqualifiedLookup = false;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004418 DeclContext *QualifiedDC = MemberContext;
4419 if (MemberContext) {
4420 LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
4421
4422 // Look in qualified interfaces.
4423 if (OPT) {
4424 for (auto *I : OPT->quals())
4425 LookupVisibleDecls(I, LookupKind, *Consumer);
4426 }
4427 } else if (SS && SS->isSet()) {
4428 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4429 if (!QualifiedDC)
4430 return nullptr;
4431
Kaelyn Takata6c759512014-10-27 18:07:37 +00004432 LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
4433 } else {
4434 IsUnqualifiedLookup = true;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004435 }
4436
4437 // Determine whether we are going to search in the various namespaces for
4438 // corrections.
4439 bool SearchNamespaces
4440 = getLangOpts().CPlusPlus &&
4441 (IsUnqualifiedLookup || (SS && SS->isSet()));
4442
4443 if (IsUnqualifiedLookup || SearchNamespaces) {
4444 // For unqualified lookup, look through all of the names that we have
4445 // seen in this translation unit.
4446 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4447 for (const auto &I : Context.Idents)
4448 Consumer->FoundName(I.getKey());
4449
4450 // Walk through identifiers in external identifier sources.
4451 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4452 if (IdentifierInfoLookup *External
4453 = Context.Idents.getExternalIdentifierLookup()) {
4454 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4455 do {
4456 StringRef Name = Iter->Next();
4457 if (Name.empty())
4458 break;
4459
4460 Consumer->FoundName(Name);
4461 } while (true);
4462 }
4463 }
4464
4465 AddKeywordsToConsumer(*this, *Consumer, S, CCCRef, SS && SS->isNotEmpty());
4466
4467 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4468 // to search those namespaces.
4469 if (SearchNamespaces) {
4470 // Load any externally-known namespaces.
4471 if (ExternalSource && !LoadedExternalKnownNamespaces) {
4472 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
4473 LoadedExternalKnownNamespaces = true;
4474 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4475 for (auto *N : ExternalKnownNamespaces)
4476 KnownNamespaces[N] = true;
4477 }
4478
4479 Consumer->addNamespaces(KnownNamespaces);
4480 }
4481
4482 return Consumer;
4483}
4484
Douglas Gregor2d435302009-12-30 17:04:44 +00004485/// \brief Try to "correct" a typo in the source code by finding
4486/// visible declarations whose names are similar to the name that was
4487/// present in the source code.
4488///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004489/// \param TypoName the \c DeclarationNameInfo structure that contains
4490/// the name that was present in the source code along with its location.
4491///
4492/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00004493///
4494/// \param S the scope in which name lookup occurs.
4495///
4496/// \param SS the nested-name-specifier that precedes the name we're
4497/// looking for, if present.
4498///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004499/// \param CCC A CorrectionCandidateCallback object that provides further
4500/// validation of typo correction candidates. It also provides flags for
4501/// determining the set of keywords permitted.
4502///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00004503/// \param MemberContext if non-NULL, the context in which to look for
4504/// a member access expression.
4505///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004506/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00004507/// the nested-name-specifier SS.
4508///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004509/// \param OPT when non-NULL, the search for visible declarations will
4510/// also walk the protocols in the qualified interfaces of \p OPT.
4511///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004512/// \returns a \c TypoCorrection containing the corrected name if the typo
4513/// along with information such as the \c NamedDecl where the corrected name
4514/// was declared, and any additional \c NestedNameSpecifier needed to access
4515/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
4516TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
4517 Sema::LookupNameKind LookupKind,
4518 Scope *S, CXXScopeSpec *SS,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004519 std::unique_ptr<CorrectionCandidateCallback> CCC,
John Thompson2255f2c2014-04-23 12:57:01 +00004520 CorrectTypoKind Mode,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004521 DeclContext *MemberContext,
4522 bool EnteringContext,
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004523 const ObjCObjectPointerType *OPT,
4524 bool RecordFailure) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004525 assert(CCC && "CorrectTypo requires a CorrectionCandidateCallback");
4526
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004527 // Always let the ExternalSource have the first chance at correction, even
4528 // if we would otherwise have given up.
4529 if (ExternalSource) {
4530 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004531 TypoName, LookupKind, S, SS, *CCC, MemberContext, EnteringContext, OPT))
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004532 return Correction;
4533 }
4534
Kaelyn Takata6c759512014-10-27 18:07:37 +00004535 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4536 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4537 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4538 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
4539 bool ObjCMessageReceiver = CCC->WantObjCSuper && !CCC->WantRemainingKeywords;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004540
Kaelyn Takata6c759512014-10-27 18:07:37 +00004541 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Kaelyn Takata6c759512014-10-27 18:07:37 +00004542 auto Consumer = makeTypoCorrectionConsumer(
4543 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004544 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004545
Kaelyn Takata6c759512014-10-27 18:07:37 +00004546 if (!Consumer)
4547 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004548
Douglas Gregor280e1ee2010-04-14 20:04:41 +00004549 // If we haven't found anything, we're done.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004550 if (Consumer->empty())
Nick Lewycky24653262014-12-16 21:39:02 +00004551 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregor2d435302009-12-30 17:04:44 +00004552
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004553 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4554 // is not more that about a third of the length of the typo's identifier.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004555 unsigned ED = Consumer->getBestEditDistance(true);
4556 unsigned TypoLen = Typo->getName().size();
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004557 if (ED > 0 && TypoLen / ED < 3)
Nick Lewycky24653262014-12-16 21:39:02 +00004558 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004559
Kaelyn Takata6c759512014-10-27 18:07:37 +00004560 TypoCorrection BestTC = Consumer->getNextCorrection();
4561 TypoCorrection SecondBestTC = Consumer->getNextCorrection();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004562 if (!BestTC)
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004563 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004564
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004565 ED = BestTC.getEditDistance();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004566
Kaelyn Takata6c759512014-10-27 18:07:37 +00004567 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004568 // If this was an unqualified lookup and we believe the callback
4569 // object wouldn't have filtered out possible corrections, note
4570 // that no correction was found.
Nick Lewycky24653262014-12-16 21:39:02 +00004571 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004572 }
4573
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004574 // If only a single name remains, return that result.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004575 if (!SecondBestTC ||
4576 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
4577 const TypoCorrection &Result = BestTC;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004578
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00004579 // Don't correct to a keyword that's the same as the typo; the keyword
4580 // wasn't actually in scope.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004581 if (ED == 0 && Result.isKeyword())
4582 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004583
David Blaikie04ea41c2012-10-12 20:00:44 +00004584 TypoCorrection TC = Result;
4585 TC.setCorrectionRange(SS, TypoName);
Kaelyn Takataa95ebc62014-06-17 23:47:29 +00004586 checkCorrectionVisibility(*this, TC);
David Blaikie04ea41c2012-10-12 20:00:44 +00004587 return TC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004588 } else if (SecondBestTC && ObjCMessageReceiver) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004589 // Prefer 'super' when we're completing in a message-receiver
4590 // context.
4591
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004592 if (BestTC.getCorrection().getAsString() != "super") {
4593 if (SecondBestTC.getCorrection().getAsString() == "super")
4594 BestTC = SecondBestTC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004595 else if ((*Consumer)["super"].front().isKeyword())
4596 BestTC = (*Consumer)["super"].front();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004597 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004598 // Don't correct to a keyword that's the same as the typo; the keyword
4599 // wasn't actually in scope.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004600 if (BestTC.getEditDistance() == 0 ||
4601 BestTC.getCorrection().getAsString() != "super")
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004602 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004603
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004604 BestTC.setCorrectionRange(SS, TypoName);
4605 return BestTC;
Douglas Gregoraf9eb592010-10-15 13:35:25 +00004606 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004607
Kaelyn Takata73429fd2014-06-10 21:03:49 +00004608 // Record the failure's location if needed and return an empty correction. If
4609 // this was an unqualified lookup and we believe the callback object did not
4610 // filter out possible corrections, also cache the failure for the typo.
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004611 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004612}
4613
Kaelyn Takata6c759512014-10-27 18:07:37 +00004614/// \brief Try to "correct" a typo in the source code by finding
4615/// visible declarations whose names are similar to the name that was
4616/// present in the source code.
4617///
4618/// \param TypoName the \c DeclarationNameInfo structure that contains
4619/// the name that was present in the source code along with its location.
4620///
4621/// \param LookupKind the name-lookup criteria used to search for the name.
4622///
4623/// \param S the scope in which name lookup occurs.
4624///
4625/// \param SS the nested-name-specifier that precedes the name we're
4626/// looking for, if present.
4627///
4628/// \param CCC A CorrectionCandidateCallback object that provides further
4629/// validation of typo correction candidates. It also provides flags for
4630/// determining the set of keywords permitted.
4631///
4632/// \param TDG A TypoDiagnosticGenerator functor that will be used to print
4633/// diagnostics when the actual typo correction is attempted.
4634///
Kaelyn Takata8363f042014-10-27 18:07:42 +00004635/// \param TRC A TypoRecoveryCallback functor that will be used to build an
4636/// Expr from a typo correction candidate.
4637///
Kaelyn Takata6c759512014-10-27 18:07:37 +00004638/// \param MemberContext if non-NULL, the context in which to look for
4639/// a member access expression.
4640///
4641/// \param EnteringContext whether we're entering the context described by
4642/// the nested-name-specifier SS.
4643///
4644/// \param OPT when non-NULL, the search for visible declarations will
4645/// also walk the protocols in the qualified interfaces of \p OPT.
4646///
4647/// \returns a new \c TypoExpr that will later be replaced in the AST with an
4648/// Expr representing the result of performing typo correction, or nullptr if
4649/// typo correction is not possible. If nullptr is returned, no diagnostics will
4650/// be emitted and it is the responsibility of the caller to emit any that are
4651/// needed.
4652TypoExpr *Sema::CorrectTypoDelayed(
4653 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4654 Scope *S, CXXScopeSpec *SS,
4655 std::unique_ptr<CorrectionCandidateCallback> CCC,
Kaelyn Takata8363f042014-10-27 18:07:42 +00004656 TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,
Kaelyn Takata6c759512014-10-27 18:07:37 +00004657 DeclContext *MemberContext, bool EnteringContext,
4658 const ObjCObjectPointerType *OPT) {
4659 assert(CCC && "CorrectTypoDelayed requires a CorrectionCandidateCallback");
4660
4661 TypoCorrection Empty;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004662 auto Consumer = makeTypoCorrectionConsumer(
4663 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004664 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Kaelyn Takata6c759512014-10-27 18:07:37 +00004665
4666 if (!Consumer || Consumer->empty())
4667 return nullptr;
4668
4669 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4670 // is not more that about a third of the length of the typo's identifier.
4671 unsigned ED = Consumer->getBestEditDistance(true);
4672 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4673 if (ED > 0 && Typo->getName().size() / ED < 3)
4674 return nullptr;
4675
4676 ExprEvalContexts.back().NumTypos++;
Kaelyn Takata8363f042014-10-27 18:07:42 +00004677 return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC));
Kaelyn Takata6c759512014-10-27 18:07:37 +00004678}
4679
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004680void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4681 if (!CDecl) return;
4682
4683 if (isKeyword())
4684 CorrectionDecls.clear();
4685
Kaelyn Uhrainf60b55a2012-11-19 18:49:53 +00004686 CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004687
4688 if (!CorrectionName)
4689 CorrectionName = CDecl->getDeclName();
4690}
4691
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004692std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4693 if (CorrectionNameSpec) {
4694 std::string tmpBuffer;
4695 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4696 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikied4da8722013-05-14 21:04:00 +00004697 PrefixOStream << CorrectionName;
Benjamin Kramer73faad62012-04-14 08:26:28 +00004698 return PrefixOStream.str();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004699 }
4700
4701 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00004702}
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004703
Nico Weberb58e51c2014-11-19 05:21:39 +00004704bool CorrectionCandidateCallback::ValidateCandidate(
4705 const TypoCorrection &candidate) {
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004706 if (!candidate.isResolved())
4707 return true;
4708
4709 if (candidate.isKeyword())
4710 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4711 WantRemainingKeywords || WantObjCSuper;
4712
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004713 bool HasNonType = false;
4714 bool HasStaticMethod = false;
4715 bool HasNonStaticMethod = false;
4716 for (Decl *D : candidate) {
4717 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
4718 D = FTD->getTemplatedDecl();
4719 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4720 if (Method->isStatic())
4721 HasStaticMethod = true;
4722 else
4723 HasNonStaticMethod = true;
4724 }
4725 if (!isa<TypeDecl>(D))
4726 HasNonType = true;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004727 }
4728
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004729 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
4730 !candidate.getCorrectionSpecifier())
4731 return false;
4732
4733 return WantTypeSpecifiers || HasNonType;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004734}
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004735
4736FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004737 bool HasExplicitTemplateArgs,
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004738 MemberExpr *ME)
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004739 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004740 CurContext(SemaRef.CurContext), MemberFn(ME) {
Kaelyn Takatab04846b2014-07-28 18:14:02 +00004741 WantTypeSpecifiers = false;
4742 WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus && NumArgs == 1;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004743 WantRemainingKeywords = false;
4744}
4745
4746bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4747 if (!candidate.getCorrectionDecl())
4748 return candidate.isKeyword();
4749
Aaron Ballman1e606f42014-07-15 22:03:49 +00004750 for (auto *C : candidate) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004751 FunctionDecl *FD = nullptr;
Aaron Ballman1e606f42014-07-15 22:03:49 +00004752 NamedDecl *ND = C->getUnderlyingDecl();
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004753 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4754 FD = FTD->getTemplatedDecl();
4755 if (!HasExplicitTemplateArgs && !FD) {
4756 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4757 // If the Decl is neither a function nor a template function,
4758 // determine if it is a pointer or reference to a function. If so,
4759 // check against the number of arguments expected for the pointee.
4760 QualType ValType = cast<ValueDecl>(ND)->getType();
4761 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4762 ValType = ValType->getPointeeType();
4763 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
Alp Toker9cacbab2014-01-20 20:26:09 +00004764 if (FPT->getNumParams() == NumArgs)
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004765 return true;
4766 }
4767 }
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004768
4769 // Skip the current candidate if it is not a FunctionDecl or does not accept
4770 // the current number of arguments.
4771 if (!FD || !(FD->getNumParams() >= NumArgs &&
4772 FD->getMinRequiredArguments() <= NumArgs))
4773 continue;
4774
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004775 // If the current candidate is a non-static C++ method, skip the candidate
4776 // unless the method being corrected--or the current DeclContext, if the
4777 // function being corrected is not a method--is a method in the same class
4778 // or a descendent class of the candidate's parent class.
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004779 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004780 if (MemberFn || !MD->isStatic()) {
4781 CXXMethodDecl *CurMD =
4782 MemberFn
4783 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
4784 : dyn_cast_or_null<CXXMethodDecl>(CurContext);
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004785 CXXRecordDecl *CurRD =
Craig Topperc3ec1492014-05-26 06:22:03 +00004786 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004787 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
4788 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
4789 continue;
4790 }
4791 }
4792 return true;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004793 }
4794 return false;
4795}
Richard Smithf9b15102013-08-17 00:46:16 +00004796
4797void Sema::diagnoseTypo(const TypoCorrection &Correction,
4798 const PartialDiagnostic &TypoDiag,
4799 bool ErrorRecovery) {
4800 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
4801 ErrorRecovery);
4802}
4803
Richard Smithe156254d2013-08-20 20:35:18 +00004804/// Find which declaration we should import to provide the definition of
4805/// the given declaration.
Richard Smith42413142015-05-15 20:05:43 +00004806static NamedDecl *getDefinitionToImport(NamedDecl *D) {
4807 if (VarDecl *VD = dyn_cast<VarDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004808 return VD->getDefinition();
4809 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Richard Smith42413142015-05-15 20:05:43 +00004810 return FD->isDefined(FD) ? const_cast<FunctionDecl*>(FD) : nullptr;
4811 if (TagDecl *TD = dyn_cast<TagDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004812 return TD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00004813 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004814 return ID->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00004815 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004816 return PD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00004817 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004818 return getDefinitionToImport(TD->getTemplatedDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004819 return nullptr;
Richard Smithe156254d2013-08-20 20:35:18 +00004820}
4821
Richard Smithf2b1eb92015-06-15 20:15:48 +00004822void Sema::diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
4823 bool NeedDefinition, bool Recover) {
4824 assert(!isVisible(Decl) && "missing import for non-hidden decl?");
4825
4826 // Suggest importing a module providing the definition of this entity, if
4827 // possible.
4828 NamedDecl *Def = getDefinitionToImport(Decl);
4829 if (!Def)
4830 Def = Decl;
4831
4832 // FIXME: Add a Fix-It that imports the corresponding module or includes
4833 // the header.
4834 Module *Owner = getOwningModule(Decl);
4835 assert(Owner && "definition of hidden declaration is not in a module");
4836
Richard Smith35c1df52015-06-17 20:16:32 +00004837 llvm::SmallVector<Module*, 8> OwningModules;
4838 OwningModules.push_back(Owner);
Richard Smithf2b1eb92015-06-15 20:15:48 +00004839 auto Merged = Context.getModulesWithMergedDefinition(Decl);
Richard Smith35c1df52015-06-17 20:16:32 +00004840 OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end());
4841
4842 diagnoseMissingImport(Loc, Decl, Decl->getLocation(), OwningModules,
4843 NeedDefinition ? MissingImportKind::Definition
4844 : MissingImportKind::Declaration,
4845 Recover);
4846}
4847
4848void Sema::diagnoseMissingImport(SourceLocation UseLoc, NamedDecl *Decl,
4849 SourceLocation DeclLoc,
4850 ArrayRef<Module *> Modules,
4851 MissingImportKind MIK, bool Recover) {
4852 assert(!Modules.empty());
4853
4854 if (Modules.size() > 1) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00004855 std::string ModuleList;
Richard Smithf2b1eb92015-06-15 20:15:48 +00004856 unsigned N = 0;
Richard Smith35c1df52015-06-17 20:16:32 +00004857 for (Module *M : Modules) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00004858 ModuleList += "\n ";
Richard Smith35c1df52015-06-17 20:16:32 +00004859 if (++N == 5 && N != Modules.size()) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00004860 ModuleList += "[...]";
4861 break;
4862 }
4863 ModuleList += M->getFullModuleName();
4864 }
4865
Richard Smith35c1df52015-06-17 20:16:32 +00004866 Diag(UseLoc, diag::err_module_unimported_use_multiple)
4867 << (int)MIK << Decl << ModuleList;
Richard Smithf2b1eb92015-06-15 20:15:48 +00004868 } else {
Richard Smith35c1df52015-06-17 20:16:32 +00004869 Diag(UseLoc, diag::err_module_unimported_use)
4870 << (int)MIK << Decl << Modules[0]->getFullModuleName();
Richard Smithf2b1eb92015-06-15 20:15:48 +00004871 }
Richard Smith35c1df52015-06-17 20:16:32 +00004872
4873 unsigned DiagID;
4874 switch (MIK) {
4875 case MissingImportKind::Declaration:
4876 DiagID = diag::note_previous_declaration;
4877 break;
4878 case MissingImportKind::Definition:
4879 DiagID = diag::note_previous_definition;
4880 break;
4881 case MissingImportKind::DefaultArgument:
4882 DiagID = diag::note_default_argument_declared_here;
4883 break;
4884 }
4885 Diag(DeclLoc, DiagID);
Richard Smithf2b1eb92015-06-15 20:15:48 +00004886
4887 // Try to recover by implicitly importing this module.
4888 if (Recover)
Richard Smith35c1df52015-06-17 20:16:32 +00004889 createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
Richard Smithf2b1eb92015-06-15 20:15:48 +00004890}
4891
Richard Smithf9b15102013-08-17 00:46:16 +00004892/// \brief Diagnose a successfully-corrected typo. Separated from the correction
4893/// itself to allow external validation of the result, etc.
4894///
4895/// \param Correction The result of performing typo correction.
4896/// \param TypoDiag The diagnostic to produce. This will have the corrected
4897/// string added to it (and usually also a fixit).
4898/// \param PrevNote A note to use when indicating the location of the entity to
4899/// which we are correcting. Will have the correction string added to it.
4900/// \param ErrorRecovery If \c true (the default), the caller is going to
4901/// recover from the typo as if the corrected string had been typed.
4902/// In this case, \c PDiag must be an error, and we will attach a fixit
4903/// to it.
4904void Sema::diagnoseTypo(const TypoCorrection &Correction,
4905 const PartialDiagnostic &TypoDiag,
4906 const PartialDiagnostic &PrevNote,
4907 bool ErrorRecovery) {
4908 std::string CorrectedStr = Correction.getAsString(getLangOpts());
4909 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
4910 FixItHint FixTypo = FixItHint::CreateReplacement(
4911 Correction.getCorrectionRange(), CorrectedStr);
4912
Richard Smithe156254d2013-08-20 20:35:18 +00004913 // Maybe we're just missing a module import.
4914 if (Correction.requiresImport()) {
4915 NamedDecl *Decl = Correction.getCorrectionDecl();
4916 assert(Decl && "import required but no declaration to import");
4917
Richard Smithf2b1eb92015-06-15 20:15:48 +00004918 diagnoseMissingImport(Correction.getCorrectionRange().getBegin(), Decl,
4919 /*NeedDefinition*/ false, ErrorRecovery);
Richard Smithe156254d2013-08-20 20:35:18 +00004920 return;
4921 }
4922
Richard Smithf9b15102013-08-17 00:46:16 +00004923 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
4924 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
4925
4926 NamedDecl *ChosenDecl =
Craig Topperc3ec1492014-05-26 06:22:03 +00004927 Correction.isKeyword() ? nullptr : Correction.getCorrectionDecl();
Richard Smithf9b15102013-08-17 00:46:16 +00004928 if (PrevNote.getDiagID() && ChosenDecl)
4929 Diag(ChosenDecl->getLocation(), PrevNote)
4930 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
4931}
Kaelyn Takata6c759512014-10-27 18:07:37 +00004932
Kaelyn Takata8363f042014-10-27 18:07:42 +00004933TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
4934 TypoDiagnosticGenerator TDG,
4935 TypoRecoveryCallback TRC) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00004936 assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
4937 auto TE = new (Context) TypoExpr(Context.DependentTy);
4938 auto &State = DelayedTypos[TE];
4939 State.Consumer = std::move(TCC);
4940 State.DiagHandler = std::move(TDG);
Kaelyn Takata8363f042014-10-27 18:07:42 +00004941 State.RecoveryHandler = std::move(TRC);
Kaelyn Takata6c759512014-10-27 18:07:37 +00004942 return TE;
4943}
4944
4945const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
4946 auto Entry = DelayedTypos.find(TE);
4947 assert(Entry != DelayedTypos.end() &&
4948 "Failed to get the state for a TypoExpr!");
4949 return Entry->second;
4950}
4951
4952void Sema::clearDelayedTypo(TypoExpr *TE) {
4953 DelayedTypos.erase(TE);
4954}