blob: 05bf303c98c774812f3996188ba5505193808da2 [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 Gregor960b5bc2009-01-15 00:26:24 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000017#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
Nick Lewyckyc3921482012-04-03 21:44:08 +000019#include "clang/AST/DeclLookups.h"
Douglas Gregor34074322009-01-14 22:20:51 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000022#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000023#include "clang/AST/ExprCXX.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Douglas Gregor34074322009-01-14 22:20:51 +000025#include "clang/Basic/LangOptions.h"
Richard Smith42413142015-05-15 20:05:43 +000026#include "clang/Lex/HeaderSearch.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000027#include "clang/Lex/ModuleLoader.h"
Richard Smith4caa4492015-05-15 02:34:32 +000028#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/Sema/DeclSpec.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000030#include "clang/Sema/Lookup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/Overload.h"
32#include "clang/Sema/Scope.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
35#include "clang/Sema/SemaInternal.h"
36#include "clang/Sema/TemplateDeduction.h"
37#include "clang/Sema/TypoCorrection.h"
Douglas Gregor34074322009-01-14 22:20:51 +000038#include "llvm/ADT/STLExtras.h"
Douglas Gregore254f902009-02-04 00:32:51 +000039#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner83cfc7c2011-07-18 01:54:02 +000040#include "llvm/ADT/TinyPtrVector.h"
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +000041#include "llvm/ADT/edit_distance.h"
John McCall6538c932009-10-10 05:48:19 +000042#include "llvm/Support/ErrorHandling.h"
Nick Lewycky13668f22012-04-03 20:26:45 +000043#include <algorithm>
44#include <iterator>
Douglas Gregor2d435302009-12-30 17:04:44 +000045#include <list>
Nick Lewycky13668f22012-04-03 20:26:45 +000046#include <set>
47#include <utility>
48#include <vector>
Douglas Gregor34074322009-01-14 22:20:51 +000049
50using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000051using namespace sema;
Douglas Gregor34074322009-01-14 22:20:51 +000052
John McCallf6c8a4e2009-11-10 07:01:13 +000053namespace {
54 class UnqualUsingEntry {
55 const DeclContext *Nominated;
56 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000057
John McCallf6c8a4e2009-11-10 07:01:13 +000058 public:
59 UnqualUsingEntry(const DeclContext *Nominated,
60 const DeclContext *CommonAncestor)
61 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
62 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000063
John McCallf6c8a4e2009-11-10 07:01:13 +000064 const DeclContext *getCommonAncestor() const {
65 return CommonAncestor;
66 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000067
John McCallf6c8a4e2009-11-10 07:01:13 +000068 const DeclContext *getNominatedNamespace() const {
69 return Nominated;
70 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000071
John McCallf6c8a4e2009-11-10 07:01:13 +000072 // Sort by the pointer value of the common ancestor.
73 struct Comparator {
74 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
75 return L.getCommonAncestor() < R.getCommonAncestor();
76 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000077
John McCallf6c8a4e2009-11-10 07:01:13 +000078 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
79 return E.getCommonAncestor() < DC;
80 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000081
John McCallf6c8a4e2009-11-10 07:01:13 +000082 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
83 return DC < E.getCommonAncestor();
84 }
85 };
86 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000087
John McCallf6c8a4e2009-11-10 07:01:13 +000088 /// A collection of using directives, as used by C++ unqualified
89 /// lookup.
90 class UnqualUsingDirectiveSet {
Richard Smithb920f852017-10-11 01:19:11 +000091 Sema &SemaRef;
92
Chris Lattner0e62c1c2011-07-23 10:55:15 +000093 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000094
John McCallf6c8a4e2009-11-10 07:01:13 +000095 ListTy list;
96 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000097
John McCallf6c8a4e2009-11-10 07:01:13 +000098 public:
Richard Smithb920f852017-10-11 01:19:11 +000099 UnqualUsingDirectiveSet(Sema &SemaRef) : SemaRef(SemaRef) {}
Douglas Gregor889ceb72009-02-03 19:21:40 +0000100
John McCallf6c8a4e2009-11-10 07:01:13 +0000101 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000102 // C++ [namespace.udir]p1:
John McCallf6c8a4e2009-11-10 07:01:13 +0000103 // During unqualified name lookup, the names appear as if they
104 // were declared in the nearest enclosing namespace which contains
105 // both the using-directive and the nominated namespace.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000106 DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
John McCallf6c8a4e2009-11-10 07:01:13 +0000107 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +0000108
John McCallf6c8a4e2009-11-10 07:01:13 +0000109 for (; S; S = S->getParent()) {
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000110 // C++ [namespace.udir]p1:
111 // A using-directive shall not appear in class scope, but may
112 // appear in namespace scope or in block scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000113 DeclContext *Ctx = S->getEntity();
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000114 if (Ctx && Ctx->isFileContext()) {
115 visit(Ctx, Ctx);
116 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
Aaron Ballman5df6aa42014-03-17 17:03:37 +0000117 for (auto *I : S->using_directives())
Richard Smithb920f852017-10-11 01:19:11 +0000118 if (SemaRef.isVisible(I))
119 visit(I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000120 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000121 }
122 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000123
124 // Visits a context and collect all of its using directives
125 // recursively. Treats all using directives as if they were
126 // declared in the context.
127 //
128 // A given context is only every visited once, so it is important
129 // that contexts be visited from the inside out in order to get
130 // the effective DCs right.
131 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
David Blaikie82e95a32014-11-19 07:49:47 +0000132 if (!visited.insert(DC).second)
John McCallf6c8a4e2009-11-10 07:01:13 +0000133 return;
134
135 addUsingDirectives(DC, EffectiveDC);
136 }
137
138 // Visits a using directive and collects all of its using
139 // directives recursively. Treats all using directives as if they
140 // were declared in the effective DC.
141 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
142 DeclContext *NS = UD->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +0000143 if (!visited.insert(NS).second)
John McCallf6c8a4e2009-11-10 07:01:13 +0000144 return;
145
146 addUsingDirective(UD, EffectiveDC);
147 addUsingDirectives(NS, EffectiveDC);
148 }
149
150 // Adds all the using directives in a context (and those nominated
151 // by its using directives, transitively) as if they appeared in
152 // the given effective context.
153 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Nick Lewycky4b81fc872015-10-18 20:32:12 +0000154 SmallVector<DeclContext*, 4> queue;
John McCallf6c8a4e2009-11-10 07:01:13 +0000155 while (true) {
Aaron Ballman804a7fb2014-03-17 17:14:12 +0000156 for (auto UD : DC->using_directives()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000157 DeclContext *NS = UD->getNominatedNamespace();
Richard Smitha544c512017-10-30 22:38:20 +0000158 if (SemaRef.isVisible(UD) && visited.insert(NS).second) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000159 addUsingDirective(UD, EffectiveDC);
160 queue.push_back(NS);
161 }
162 }
163
164 if (queue.empty())
165 return;
166
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000167 DC = queue.pop_back_val();
John McCallf6c8a4e2009-11-10 07:01:13 +0000168 }
169 }
170
171 // Add a using directive as if it had been declared in the given
172 // context. This helps implement C++ [namespace.udir]p3:
173 // The using-directive is transitive: if a scope contains a
174 // using-directive that nominates a second namespace that itself
175 // contains using-directives, the effect is as if the
176 // using-directives from the second namespace also appeared in
177 // the first.
178 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
179 // Find the common ancestor between the effective context and
180 // the nominated namespace.
181 DeclContext *Common = UD->getNominatedNamespace();
182 while (!Common->Encloses(EffectiveDC))
183 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000184 Common = Common->getPrimaryContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000185
John McCallf6c8a4e2009-11-10 07:01:13 +0000186 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
187 }
188
189 void done() {
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +0000190 llvm::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
John McCallf6c8a4e2009-11-10 07:01:13 +0000191 }
192
John McCallf6c8a4e2009-11-10 07:01:13 +0000193 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000194
John McCallf6c8a4e2009-11-10 07:01:13 +0000195 const_iterator begin() const { return list.begin(); }
196 const_iterator end() const { return list.end(); }
197
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000198 llvm::iterator_range<const_iterator>
John McCallf6c8a4e2009-11-10 07:01:13 +0000199 getNamespacesFor(DeclContext *DC) const {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000200 return llvm::make_range(std::equal_range(begin(), end(),
201 DC->getPrimaryContext(),
202 UnqualUsingEntry::Comparator()));
John McCallf6c8a4e2009-11-10 07:01:13 +0000203 }
204 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000205} // end anonymous namespace
Douglas Gregor889ceb72009-02-03 19:21:40 +0000206
Douglas Gregor889ceb72009-02-03 19:21:40 +0000207// Retrieve the set of identifier namespaces that correspond to a
208// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000209static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
210 bool CPlusPlus,
211 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000212 unsigned IDNS = 0;
213 switch (NameKind) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +0000214 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000215 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000216 case Sema::LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +0000217 case Sema::LookupLocalFriendName:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000218 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000219 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000220 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000221 if (Redeclaration)
222 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCallea305ed2009-12-18 10:40:03 +0000223 }
Richard Smith541b38b2013-09-20 01:15:31 +0000224 if (Redeclaration)
225 IDNS |= Decl::IDNS_LocalExtern;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000226 break;
227
John McCallb9467b62010-04-24 01:30:58 +0000228 case Sema::LookupOperatorName:
229 // Operator lookup is its own crazy thing; it is not the same
230 // as (e.g.) looking up an operator name for redeclaration.
231 assert(!Redeclaration && "cannot do redeclaration operator lookup");
232 IDNS = Decl::IDNS_NonMemberOperator;
233 break;
234
Douglas Gregor889ceb72009-02-03 19:21:40 +0000235 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000236 if (CPlusPlus) {
237 IDNS = Decl::IDNS_Type;
238
239 // When looking for a redeclaration of a tag name, we add:
240 // 1) TagFriend to find undeclared friend decls
241 // 2) Namespace because they can't "overload" with tag decls.
242 // 3) Tag because it includes class templates, which can't
243 // "overload" with tag decls.
244 if (Redeclaration)
245 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
246 } else {
247 IDNS = Decl::IDNS_Tag;
248 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000249 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000250
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000251 case Sema::LookupLabel:
252 IDNS = Decl::IDNS_Label;
253 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000254
Douglas Gregor889ceb72009-02-03 19:21:40 +0000255 case Sema::LookupMemberName:
256 IDNS = Decl::IDNS_Member;
257 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000258 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000259 break;
260
261 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000262 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
263 break;
264
Douglas Gregor889ceb72009-02-03 19:21:40 +0000265 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000266 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000267 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000268
John McCall84d87672009-12-10 09:41:52 +0000269 case Sema::LookupUsingDeclName:
Richard Smith83e78f52014-04-11 01:03:38 +0000270 assert(Redeclaration && "should only be used for redecl lookup");
271 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |
272 Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend |
273 Decl::IDNS_LocalExtern;
John McCall84d87672009-12-10 09:41:52 +0000274 break;
275
Douglas Gregor79947a22009-04-24 00:11:27 +0000276 case Sema::LookupObjCProtocolName:
277 IDNS = Decl::IDNS_ObjCProtocol;
278 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000279
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000280 case Sema::LookupOMPReductionName:
281 IDNS = Decl::IDNS_OMPReduction;
282 break;
283
Douglas Gregor39982192010-08-15 06:18:01 +0000284 case Sema::LookupAnyName:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000285 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor39982192010-08-15 06:18:01 +0000286 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
287 | Decl::IDNS_Type;
288 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000289 }
290 return IDNS;
291}
292
John McCallea305ed2009-12-18 10:40:03 +0000293void LookupResult::configure() {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000294 IDNS = getIDNS(LookupKind, getSema().getLangOpts().CPlusPlus,
John McCallea305ed2009-12-18 10:40:03 +0000295 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000296
Richard Smithbdd14642014-02-04 01:14:30 +0000297 // If we're looking for one of the allocation or deallocation
298 // operators, make sure that the implicitly-declared new and delete
299 // operators can be found.
300 switch (NameInfo.getName().getCXXOverloadedOperator()) {
301 case OO_New:
302 case OO_Delete:
303 case OO_Array_New:
304 case OO_Array_Delete:
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000305 getSema().DeclareGlobalNewDelete();
Richard Smithbdd14642014-02-04 01:14:30 +0000306 break;
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000307
Richard Smithbdd14642014-02-04 01:14:30 +0000308 default:
309 break;
310 }
Douglas Gregor15197662013-04-03 23:06:26 +0000311
Richard Smithbdd14642014-02-04 01:14:30 +0000312 // Compiler builtins are always visible, regardless of where they end
313 // up being declared.
314 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
315 if (unsigned BuiltinID = Id->getBuiltinID()) {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000316 if (!getSema().Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
Richard Smithbdd14642014-02-04 01:14:30 +0000317 AllowHidden = true;
Douglas Gregor15197662013-04-03 23:06:26 +0000318 }
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000319 }
John McCallea305ed2009-12-18 10:40:03 +0000320}
321
Alp Tokerc1086762013-12-07 13:51:35 +0000322bool LookupResult::sanity() const {
Richard Smithf97ad222014-04-01 18:33:50 +0000323 // This function is never called by NDEBUG builds.
John McCall19c1bfd2010-08-25 05:32:35 +0000324 assert(ResultKind != NotFound || Decls.size() == 0);
325 assert(ResultKind != Found || Decls.size() == 1);
326 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
327 (Decls.size() == 1 &&
328 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
329 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
330 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000331 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
332 Ambiguity == AmbiguousBaseSubobjectTypes)));
Craig Topperc3ec1492014-05-26 06:22:03 +0000333 assert((Paths != nullptr) == (ResultKind == Ambiguous &&
334 (Ambiguity == AmbiguousBaseSubobjectTypes ||
335 Ambiguity == AmbiguousBaseSubobjects)));
Alp Tokerc1086762013-12-07 13:51:35 +0000336 return true;
John McCall19c1bfd2010-08-25 05:32:35 +0000337}
John McCall19c1bfd2010-08-25 05:32:35 +0000338
John McCall9f3059a2009-10-09 21:13:30 +0000339// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000340void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000341 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000342}
343
Richard Smith3876cc82013-10-30 01:02:04 +0000344/// Get a representative context for a declaration such that two declarations
345/// will have the same context if they were found within the same scope.
Benjamin Kramerfc58b042013-11-01 11:50:55 +0000346static DeclContext *getContextForScopeMatching(Decl *D) {
Richard Smith3876cc82013-10-30 01:02:04 +0000347 // For function-local declarations, use that function as the context. This
348 // doesn't account for scopes within the function; the caller must deal with
349 // those.
350 DeclContext *DC = D->getLexicalDeclContext();
351 if (DC->isFunctionOrMethod())
352 return DC;
353
354 // Otherwise, look at the semantic context of the declaration. The
355 // declaration must have been found there.
356 return D->getDeclContext()->getRedeclContext();
357}
358
Richard Smith826711d2015-07-29 23:38:25 +0000359/// \brief Determine whether \p D is a better lookup result than \p Existing,
360/// given that they declare the same entity.
Richard Smithcd31b852015-08-22 21:37:34 +0000361static bool isPreferredLookupResult(Sema &S, Sema::LookupNameKind Kind,
Richard Smith826711d2015-07-29 23:38:25 +0000362 NamedDecl *D, NamedDecl *Existing) {
363 // When looking up redeclarations of a using declaration, prefer a using
364 // shadow declaration over any other declaration of the same entity.
365 if (Kind == Sema::LookupUsingDeclName && isa<UsingShadowDecl>(D) &&
366 !isa<UsingShadowDecl>(Existing))
367 return true;
368
369 auto *DUnderlying = D->getUnderlyingDecl();
370 auto *EUnderlying = Existing->getUnderlyingDecl();
371
Richard Smith990668b2015-11-12 22:04:34 +0000372 // If they have different underlying declarations, prefer a typedef over the
373 // original type (this happens when two type declarations denote the same
374 // type), per a generous reading of C++ [dcl.typedef]p3 and p4. The typedef
375 // might carry additional semantic information, such as an alignment override.
376 // However, per C++ [dcl.typedef]p5, when looking up a tag name, prefer a tag
377 // declaration over a typedef.
Richard Smith826711d2015-07-29 23:38:25 +0000378 if (DUnderlying->getCanonicalDecl() != EUnderlying->getCanonicalDecl()) {
379 assert(isa<TypeDecl>(DUnderlying) && isa<TypeDecl>(EUnderlying));
Richard Smith990668b2015-11-12 22:04:34 +0000380 bool HaveTag = isa<TagDecl>(EUnderlying);
381 bool WantTag = Kind == Sema::LookupTagName;
382 return HaveTag != WantTag;
Richard Smith826711d2015-07-29 23:38:25 +0000383 }
384
Richard Smithcd31b852015-08-22 21:37:34 +0000385 // Pick the function with more default arguments.
386 // FIXME: In the presence of ambiguous default arguments, we should keep both,
387 // so we can diagnose the ambiguity if the default argument is needed.
388 // See C++ [over.match.best]p3.
389 if (auto *DFD = dyn_cast<FunctionDecl>(DUnderlying)) {
390 auto *EFD = cast<FunctionDecl>(EUnderlying);
391 unsigned DMin = DFD->getMinRequiredArguments();
392 unsigned EMin = EFD->getMinRequiredArguments();
393 // If D has more default arguments, it is preferred.
394 if (DMin != EMin)
395 return DMin < EMin;
Richard Smith535ff802015-09-11 22:39:35 +0000396 // FIXME: When we track visibility for default function arguments, check
397 // that we pick the declaration with more visible default arguments.
Richard Smithcd31b852015-08-22 21:37:34 +0000398 }
399
400 // Pick the template with more default template arguments.
401 if (auto *DTD = dyn_cast<TemplateDecl>(DUnderlying)) {
402 auto *ETD = cast<TemplateDecl>(EUnderlying);
403 unsigned DMin = DTD->getTemplateParameters()->getMinRequiredArguments();
404 unsigned EMin = ETD->getTemplateParameters()->getMinRequiredArguments();
Richard Smith535ff802015-09-11 22:39:35 +0000405 // If D has more default arguments, it is preferred. Note that default
406 // arguments (and their visibility) is monotonically increasing across the
407 // redeclaration chain, so this is a quick proxy for "is more recent".
Richard Smithcd31b852015-08-22 21:37:34 +0000408 if (DMin != EMin)
409 return DMin < EMin;
Richard Smith535ff802015-09-11 22:39:35 +0000410 // If D has more *visible* default arguments, it is preferred. Note, an
411 // earlier default argument being visible does not imply that a later
412 // default argument is visible, so we can't just check the first one.
413 for (unsigned I = DMin, N = DTD->getTemplateParameters()->size();
414 I != N; ++I) {
415 if (!S.hasVisibleDefaultArgument(
416 ETD->getTemplateParameters()->getParam(I)) &&
417 S.hasVisibleDefaultArgument(
418 DTD->getTemplateParameters()->getParam(I)))
419 return true;
420 }
Richard Smithcd31b852015-08-22 21:37:34 +0000421 }
422
Vassil Vassilev4d75e8d2016-02-28 19:08:24 +0000423 // VarDecl can have incomplete array types, prefer the one with more complete
424 // array type.
425 if (VarDecl *DVD = dyn_cast<VarDecl>(DUnderlying)) {
426 VarDecl *EVD = cast<VarDecl>(EUnderlying);
427 if (EVD->getType()->isIncompleteType() &&
428 !DVD->getType()->isIncompleteType()) {
429 // Prefer the decl with a more complete type if visible.
430 return S.isVisible(DVD);
431 }
432 return false; // Avoid picking up a newer decl, just because it was newer.
433 }
434
Richard Smithcd31b852015-08-22 21:37:34 +0000435 // For most kinds of declaration, it doesn't really matter which one we pick.
436 if (!isa<FunctionDecl>(DUnderlying) && !isa<VarDecl>(DUnderlying)) {
437 // If the existing declaration is hidden, prefer the new one. Otherwise,
438 // keep what we've got.
439 return !S.isVisible(Existing);
440 }
441
442 // Pick the newer declaration; it might have a more precise type.
Richard Smith826711d2015-07-29 23:38:25 +0000443 for (Decl *Prev = DUnderlying->getPreviousDecl(); Prev;
444 Prev = Prev->getPreviousDecl())
445 if (Prev == EUnderlying)
446 return true;
Richard Smith826711d2015-07-29 23:38:25 +0000447 return false;
448}
449
Richard Smith990668b2015-11-12 22:04:34 +0000450/// Determine whether \p D can hide a tag declaration.
451static bool canHideTag(NamedDecl *D) {
452 // C++ [basic.scope.declarative]p4:
453 // Given a set of declarations in a single declarative region [...]
454 // exactly one declaration shall declare a class name or enumeration name
455 // that is not a typedef name and the other declarations shall all refer to
Richard Smith4eeaec42016-12-18 22:01:46 +0000456 // the same variable, non-static data member, or enumerator, or all refer
457 // to functions and function templates; in this case the class name or
458 // enumeration name is hidden.
Richard Smith990668b2015-11-12 22:04:34 +0000459 // C++ [basic.scope.hiding]p2:
460 // A class name or enumeration name can be hidden by the name of a
461 // variable, data member, function, or enumerator declared in the same
462 // scope.
Richard Smith4eeaec42016-12-18 22:01:46 +0000463 // An UnresolvedUsingValueDecl always instantiates to one of these.
Richard Smith990668b2015-11-12 22:04:34 +0000464 D = D->getUnderlyingDecl();
465 return isa<VarDecl>(D) || isa<EnumConstantDecl>(D) || isa<FunctionDecl>(D) ||
Richard Smith4eeaec42016-12-18 22:01:46 +0000466 isa<FunctionTemplateDecl>(D) || isa<FieldDecl>(D) ||
467 isa<UnresolvedUsingValueDecl>(D);
Richard Smith990668b2015-11-12 22:04:34 +0000468}
469
John McCall283b9012009-11-22 00:44:51 +0000470/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000471void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000472 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000473
John McCall9f3059a2009-10-09 21:13:30 +0000474 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000475 if (N == 0) {
Richard Smith826711d2015-07-29 23:38:25 +0000476 assert(ResultKind == NotFound ||
477 ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000478 return;
479 }
480
John McCall283b9012009-11-22 00:44:51 +0000481 // If there's a single decl, we need to examine it to decide what
482 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000483 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000484 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
485 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000486 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000487 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000488 ResultKind = FoundUnresolvedValue;
489 return;
490 }
John McCall9f3059a2009-10-09 21:13:30 +0000491
John McCall6538c932009-10-10 05:48:19 +0000492 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000493 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000494
Richard Smitha534a312015-07-21 23:54:07 +0000495 llvm::SmallDenseMap<NamedDecl*, unsigned, 16> Unique;
Richard Smith826711d2015-07-29 23:38:25 +0000496 llvm::SmallDenseMap<QualType, unsigned, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000497
John McCall9f3059a2009-10-09 21:13:30 +0000498 bool Ambiguous = false;
Richard Smith2dbe4042015-11-04 19:26:32 +0000499 bool HasTag = false, HasFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000500 bool HasFunctionTemplate = false, HasUnresolved = false;
Richard Smith2dbe4042015-11-04 19:26:32 +0000501 NamedDecl *HasNonFunction = nullptr;
502
503 llvm::SmallVector<NamedDecl*, 4> EquivalentNonFunctions;
John McCall9f3059a2009-10-09 21:13:30 +0000504
505 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000506
John McCall9f3059a2009-10-09 21:13:30 +0000507 unsigned I = 0;
508 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000509 NamedDecl *D = Decls[I]->getUnderlyingDecl();
510 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000511
Argyrios Kyrtzidis1fcd7fd2013-02-22 06:58:37 +0000512 // Ignore an invalid declaration unless it's the only one left.
Richard Smith5cd86f82015-11-03 03:13:11 +0000513 if (D->isInvalidDecl() && !(I == 0 && N == 1)) {
Argyrios Kyrtzidis1fcd7fd2013-02-22 06:58:37 +0000514 Decls[I] = Decls[--N];
515 continue;
516 }
517
Richard Smith826711d2015-07-29 23:38:25 +0000518 llvm::Optional<unsigned> ExistingI;
519
Douglas Gregor13e65872010-08-11 14:45:53 +0000520 // Redeclarations of types via typedef can occur both within a scope
521 // and, through using declarations and directives, across scopes. There is
522 // no ambiguity if they all refer to the same type, so unique based on the
523 // canonical type.
524 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
Richard Smith990668b2015-11-12 22:04:34 +0000525 QualType T = getSema().Context.getTypeDeclType(TD);
526 auto UniqueResult = UniqueTypes.insert(
527 std::make_pair(getSema().Context.getCanonicalType(T), I));
528 if (!UniqueResult.second) {
529 // The type is not unique.
530 ExistingI = UniqueResult.first->second;
Douglas Gregor13e65872010-08-11 14:45:53 +0000531 }
532 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000533
Richard Smith826711d2015-07-29 23:38:25 +0000534 // For non-type declarations, check for a prior lookup result naming this
535 // canonical declaration.
536 if (!ExistingI) {
537 auto UniqueResult = Unique.insert(std::make_pair(D, I));
538 if (!UniqueResult.second) {
539 // We've seen this entity before.
540 ExistingI = UniqueResult.first->second;
Richard Smitha534a312015-07-21 23:54:07 +0000541 }
Richard Smith826711d2015-07-29 23:38:25 +0000542 }
543
544 if (ExistingI) {
545 // This is not a unique lookup result. Pick one of the results and
546 // discard the other.
Richard Smithcd31b852015-08-22 21:37:34 +0000547 if (isPreferredLookupResult(getSema(), getLookupKind(), Decls[I],
Richard Smith826711d2015-07-29 23:38:25 +0000548 Decls[*ExistingI]))
549 Decls[*ExistingI] = Decls[I];
550 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000551 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000552 }
553
Douglas Gregor13e65872010-08-11 14:45:53 +0000554 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000555
Douglas Gregor13e65872010-08-11 14:45:53 +0000556 if (isa<UnresolvedUsingValueDecl>(D)) {
557 HasUnresolved = true;
558 } else if (isa<TagDecl>(D)) {
559 if (HasTag)
560 Ambiguous = true;
561 UniqueTagIndex = I;
562 HasTag = true;
563 } else if (isa<FunctionTemplateDecl>(D)) {
564 HasFunction = true;
565 HasFunctionTemplate = true;
566 } else if (isa<FunctionDecl>(D)) {
567 HasFunction = true;
568 } else {
Richard Smith2dbe4042015-11-04 19:26:32 +0000569 if (HasNonFunction) {
570 // If we're about to create an ambiguity between two declarations that
571 // are equivalent, but one is an internal linkage declaration from one
572 // module and the other is an internal linkage declaration from another
573 // module, just skip it.
574 if (getSema().isEquivalentInternalLinkageDeclaration(HasNonFunction,
575 D)) {
576 EquivalentNonFunctions.push_back(D);
577 Decls[I] = Decls[--N];
578 continue;
579 }
580
Douglas Gregor13e65872010-08-11 14:45:53 +0000581 Ambiguous = true;
Richard Smith2dbe4042015-11-04 19:26:32 +0000582 }
583 HasNonFunction = D;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000584 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000585 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000586 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000587
John McCall9f3059a2009-10-09 21:13:30 +0000588 // C++ [basic.scope.hiding]p2:
589 // A class name or enumeration name can be hidden by the name of
590 // an object, function, or enumerator declared in the same
591 // scope. If a class or enumeration name and an object, function,
592 // or enumerator are declared in the same scope (in any order)
593 // with the same name, the class or enumeration name is hidden
594 // wherever the object, function, or enumerator name is visible.
595 // But it's still an error if there are distinct tag types found,
596 // even if they're not visible. (ref?)
Richard Smith990668b2015-11-12 22:04:34 +0000597 if (N > 1 && HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000598 (HasFunction || HasNonFunction || HasUnresolved)) {
Richard Smith990668b2015-11-12 22:04:34 +0000599 NamedDecl *OtherDecl = Decls[UniqueTagIndex ? 0 : N - 1];
600 if (isa<TagDecl>(Decls[UniqueTagIndex]->getUnderlyingDecl()) &&
601 getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
602 getContextForScopeMatching(OtherDecl)) &&
603 canHideTag(OtherDecl))
Douglas Gregore63d0872010-10-23 16:06:17 +0000604 Decls[UniqueTagIndex] = Decls[--N];
605 else
606 Ambiguous = true;
607 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000608
Richard Smith2dbe4042015-11-04 19:26:32 +0000609 // FIXME: This diagnostic should really be delayed until we're done with
610 // the lookup result, in case the ambiguity is resolved by the caller.
611 if (!EquivalentNonFunctions.empty() && !Ambiguous)
612 getSema().diagnoseEquivalentInternalLinkageDeclarations(
613 getNameLoc(), HasNonFunction, EquivalentNonFunctions);
614
John McCall9f3059a2009-10-09 21:13:30 +0000615 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000616
John McCall80053822009-12-03 00:58:24 +0000617 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000618 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000619
John McCall9f3059a2009-10-09 21:13:30 +0000620 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000621 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000622 else if (HasUnresolved)
623 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000624 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000625 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000626 else
John McCall27b18f82009-11-17 02:14:36 +0000627 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000628}
629
John McCall5cebab12009-11-18 07:57:50 +0000630void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000631 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000632 for (I = P.begin(), E = P.end(); I != E; ++I)
David Blaikieff7d47a2012-12-19 00:45:41 +0000633 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
634 DE = I->Decls.end(); DI != DE; ++DI)
John McCall9f3059a2009-10-09 21:13:30 +0000635 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000636}
637
John McCall5cebab12009-11-18 07:57:50 +0000638void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000639 Paths = new CXXBasePaths;
640 Paths->swap(P);
641 addDeclsFromBasePaths(*Paths);
642 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000643 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000644}
645
John McCall5cebab12009-11-18 07:57:50 +0000646void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000647 Paths = new CXXBasePaths;
648 Paths->swap(P);
649 addDeclsFromBasePaths(*Paths);
650 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000651 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000652}
653
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000654void LookupResult::print(raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000655 Out << Decls.size() << " result(s)";
656 if (isAmbiguous()) Out << ", ambiguous";
657 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000658
John McCall9f3059a2009-10-09 21:13:30 +0000659 for (iterator I = begin(), E = end(); I != E; ++I) {
660 Out << "\n";
661 (*I)->print(Out, 2);
662 }
663}
664
Richard Smithba3a4f92016-01-12 21:59:26 +0000665LLVM_DUMP_METHOD void LookupResult::dump() {
666 llvm::errs() << "lookup results for " << getLookupName().getAsString()
667 << ":\n";
668 for (NamedDecl *D : *this)
669 D->dump();
670}
671
Douglas Gregord3a59182010-02-12 05:48:04 +0000672/// \brief Lookup a builtin function, when name lookup would otherwise
673/// fail.
674static bool LookupBuiltin(Sema &S, LookupResult &R) {
675 Sema::LookupNameKind NameKind = R.getLookupKind();
676
677 // If we didn't find a use of this identifier, and if the identifier
678 // corresponds to a compiler builtin, create the decl object for the builtin
679 // now, injecting it into translation unit scope, and return it.
680 if (NameKind == Sema::LookupOrdinaryName ||
681 NameKind == Sema::LookupRedeclarationWithLinkage) {
682 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
683 if (II) {
Eric Fiselier6ad68552016-07-01 01:24:09 +0000684 if (S.getLangOpts().CPlusPlus && NameKind == Sema::LookupOrdinaryName) {
685 if (II == S.getASTContext().getMakeIntegerSeqName()) {
686 R.addDecl(S.getASTContext().getMakeIntegerSeqDecl());
687 return true;
688 } else if (II == S.getASTContext().getTypePackElementName()) {
689 R.addDecl(S.getASTContext().getTypePackElementDecl());
690 return true;
691 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000692 }
Nico Webere1687c52013-06-20 21:44:55 +0000693
Douglas Gregord3a59182010-02-12 05:48:04 +0000694 // If this is a builtin on this (or all) targets, create the decl.
695 if (unsigned BuiltinID = II->getBuiltinID()) {
Anastasia Stulovab607e0f2016-02-02 11:29:43 +0000696 // In C++ and OpenCL (spec v1.2 s6.9.f), we don't have any predefined
697 // library functions like 'malloc'. Instead, we'll just error.
698 if ((S.getLangOpts().CPlusPlus || S.getLangOpts().OpenCL) &&
Douglas Gregord3a59182010-02-12 05:48:04 +0000699 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
700 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000701
702 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
703 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000704 R.isForRedeclaration(),
705 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000706 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000707 return true;
708 }
Douglas Gregord3a59182010-02-12 05:48:04 +0000709 }
710 }
711 }
712
713 return false;
714}
715
Douglas Gregor7454c562010-07-02 20:37:36 +0000716/// \brief Determine whether we can declare a special member function within
717/// the class at this point.
Richard Smith7d125a12012-11-27 21:20:31 +0000718static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +0000719 // We need to have a definition for the class.
720 if (!Class->getDefinition() || Class->isDependentContext())
721 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000722
Douglas Gregor7454c562010-07-02 20:37:36 +0000723 // We can't be in the middle of defining the class.
Richard Smith7d125a12012-11-27 21:20:31 +0000724 return !Class->isBeingDefined();
Douglas Gregor7454c562010-07-02 20:37:36 +0000725}
726
727void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smith7d125a12012-11-27 21:20:31 +0000728 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregora6d69502010-07-02 23:41:54 +0000729 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000730
731 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000732 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000733 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000734
Douglas Gregora6d69502010-07-02 23:41:54 +0000735 // If the copy constructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000736 if (Class->needsImplicitCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +0000737 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000738
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000739 // If the copy assignment operator has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000740 if (Class->needsImplicitCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000741 DeclareImplicitCopyAssignment(Class);
742
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000743 if (getLangOpts().CPlusPlus11) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000744 // If the move constructor has not yet been declared, do so now.
745 if (Class->needsImplicitMoveConstructor())
Richard Smitha87b7662016-05-13 18:48:05 +0000746 DeclareImplicitMoveConstructor(Class);
Sebastian Redl22653ba2011-08-30 19:58:05 +0000747
748 // If the move assignment operator has not yet been declared, do so now.
749 if (Class->needsImplicitMoveAssignment())
Richard Smitha87b7662016-05-13 18:48:05 +0000750 DeclareImplicitMoveAssignment(Class);
Sebastian Redl22653ba2011-08-30 19:58:05 +0000751 }
752
Douglas Gregor7454c562010-07-02 20:37:36 +0000753 // If the destructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000754 if (Class->needsImplicitDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000755 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000756}
757
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000758/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000759/// special member function.
760static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
761 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000762 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000763 case DeclarationName::CXXDestructorName:
764 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000765
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000766 case DeclarationName::CXXOperatorName:
767 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000768
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000769 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000770 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000771 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000772
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000773 return false;
774}
775
776/// \brief If there are any implicit member functions with the given name
777/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000778static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000779 DeclarationName Name,
Richard Smith32918772017-02-14 00:25:28 +0000780 SourceLocation Loc,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000781 const DeclContext *DC) {
782 if (!DC)
783 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000784
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000785 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000786 case DeclarationName::CXXConstructorName:
787 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith7d125a12012-11-27 21:20:31 +0000788 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000789 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000790 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000791 S.DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +0000792 if (Record->needsImplicitCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000793 S.DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000794 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000795 Record->needsImplicitMoveConstructor())
796 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000797 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000798 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000799
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000800 case DeclarationName::CXXDestructorName:
801 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith2be35f52012-12-01 02:35:44 +0000802 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smith7d125a12012-11-27 21:20:31 +0000803 CanDeclareSpecialMemberFunction(Record))
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000804 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000805 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000806
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000807 case DeclarationName::CXXOperatorName:
808 if (Name.getCXXOverloadedOperator() != OO_Equal)
809 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000810
Sebastian Redl22653ba2011-08-30 19:58:05 +0000811 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smith7d125a12012-11-27 21:20:31 +0000812 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000813 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smith2be35f52012-12-01 02:35:44 +0000814 if (Record->needsImplicitCopyAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000815 S.DeclareImplicitCopyAssignment(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000816 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000817 Record->needsImplicitMoveAssignment())
818 S.DeclareImplicitMoveAssignment(Class);
819 }
820 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000821 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000822
Richard Smith32918772017-02-14 00:25:28 +0000823 case DeclarationName::CXXDeductionGuideName:
824 S.DeclareImplicitDeductionGuides(Name.getCXXDeductionGuideTemplate(), Loc);
825 break;
826
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000827 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000828 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000829 }
830}
Douglas Gregor7454c562010-07-02 20:37:36 +0000831
John McCall9f3059a2009-10-09 21:13:30 +0000832// Adds all qualifying matches for a name within a decl context to the
833// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000834static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000835 bool Found = false;
836
Douglas Gregor7454c562010-07-02 20:37:36 +0000837 // Lazily declare C++ special member functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000838 if (S.getLangOpts().CPlusPlus)
Richard Smith32918772017-02-14 00:25:28 +0000839 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), R.getNameLoc(),
840 DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000841
Douglas Gregor7454c562010-07-02 20:37:36 +0000842 // Perform lookup into this declaration context.
Richard Smithcf4bdde2015-02-21 02:45:19 +0000843 DeclContext::lookup_result DR = DC->lookup(R.getLookupName());
Yaron Keren31bde582017-04-12 10:05:48 +0000844 for (NamedDecl *D : DR) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000845 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000846 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000847 Found = true;
848 }
849 }
John McCall9f3059a2009-10-09 21:13:30 +0000850
Douglas Gregord3a59182010-02-12 05:48:04 +0000851 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
852 return true;
853
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000854 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000855 != DeclarationName::CXXConversionFunctionName ||
856 R.getLookupName().getCXXNameType()->isDependentType() ||
857 !isa<CXXRecordDecl>(DC))
858 return Found;
859
860 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000861 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000862 // name lookup. Instead, any conversion function templates visible in the
863 // context of the use are considered. [...]
864 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000865 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000866 return Found;
867
Erich Keanec9cb1c12017-06-20 17:38:07 +0000868 // For conversion operators, 'operator auto' should only match
869 // 'operator auto'. Since 'auto' is not a type, it shouldn't be considered
870 // as a candidate for template substitution.
871 auto *ContainedDeducedType =
872 R.getLookupName().getCXXNameType()->getContainedDeducedType();
873 if (R.getLookupName().getNameKind() ==
874 DeclarationName::CXXConversionFunctionName &&
875 ContainedDeducedType && ContainedDeducedType->isUndeducedType())
876 return Found;
877
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +0000878 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
879 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruth3a693b72010-01-31 11:44:02 +0000880 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
881 if (!ConvTemplate)
882 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000883
Chandler Carruth3a693b72010-01-31 11:44:02 +0000884 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000885 // add the conversion function template. When we deduce template
886 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000887 // type of the new declaration with the type of the function template.
888 if (R.isForRedeclaration()) {
889 R.addDecl(ConvTemplate);
890 Found = true;
891 continue;
892 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000893
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000894 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000895 // [...] For each such operator, if argument deduction succeeds
896 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000897 // name lookup.
898 //
899 // When referencing a conversion function for any purpose other than
900 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000901 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000902 // specialization into the result set. We do this to avoid forcing all
903 // callers to perform special deduction for conversion functions.
Craig Toppere6706e42012-09-19 02:26:47 +0000904 TemplateDeductionInfo Info(R.getNameLoc());
Craig Topperc3ec1492014-05-26 06:22:03 +0000905 FunctionDecl *Specialization = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000906
907 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000908 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
909 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000910
Chandler Carruth3a693b72010-01-31 11:44:02 +0000911 // Compute the type of the function that we would expect the conversion
912 // function to have, if it were to match the name given.
913 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000914 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
Reid Kleckner78af0702013-08-27 23:08:25 +0000915 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
Richard Smith8acb4282014-07-31 21:57:55 +0000916 EPI.ExceptionSpec = EST_None;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000917 QualType ExpectedType
918 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000919 None, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000920
Chandler Carruth3a693b72010-01-31 11:44:02 +0000921 // Perform template argument deduction against the type that we would
922 // expect the function to have.
Craig Topperc3ec1492014-05-26 06:22:03 +0000923 if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
Chandler Carruth3a693b72010-01-31 11:44:02 +0000924 Specialization, Info)
925 == Sema::TDK_Success) {
926 R.addDecl(Specialization);
927 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000928 }
929 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000930
John McCall9f3059a2009-10-09 21:13:30 +0000931 return Found;
932}
933
John McCallf6c8a4e2009-11-10 07:01:13 +0000934// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000935static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000936CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000937 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000938
939 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
940
John McCallf6c8a4e2009-11-10 07:01:13 +0000941 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000942 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000943
John McCallf6c8a4e2009-11-10 07:01:13 +0000944 // Perform direct name lookup into the namespaces nominated by the
945 // using directives whose common ancestor is this namespace.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000946 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
947 if (LookupDirect(S, R, UUE.getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000948 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000949
950 R.resolveKind();
951
952 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000953}
954
955static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000956 if (DeclContext *Ctx = S->getEntity())
Douglas Gregor700792c2009-02-05 19:25:20 +0000957 return Ctx->isFileContext();
958 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000959}
Douglas Gregored8f2882009-01-30 01:04:22 +0000960
Douglas Gregor66230062010-03-15 14:33:29 +0000961// Find the next outer declaration context from this scope. This
962// routine actually returns the semantic outer context, which may
963// differ from the lexical context (encoded directly in the Scope
964// stack) when we are parsing a member of a class template. In this
965// case, the second element of the pair will be true, to indicate that
966// name lookup should continue searching in this semantic context when
967// it leaves the current template parameter scope.
968static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000969 DeclContext *DC = S->getEntity();
Craig Topperc3ec1492014-05-26 06:22:03 +0000970 DeclContext *Lexical = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000971 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000972 OuterS = OuterS->getParent()) {
973 if (OuterS->getEntity()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000974 Lexical = OuterS->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +0000975 break;
976 }
977 }
978
979 // C++ [temp.local]p8:
980 // In the definition of a member of a class template that appears
981 // outside of the namespace containing the class template
982 // definition, the name of a template-parameter hides the name of
983 // a member of this namespace.
984 //
985 // Example:
986 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000987 // namespace N {
988 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000989 //
990 // template<class T> class B {
991 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000992 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000993 // }
994 //
995 // template<class C> void N::B<C>::f(C) {
996 // C b; // C is the template parameter, not N::C
997 // }
998 //
999 // In this example, the lexical context we return is the
1000 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001001 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +00001002 !S->getParent()->isTemplateParamScope())
1003 return std::make_pair(Lexical, false);
1004
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001005 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +00001006 // For the example, this is the scope for the template parameters of
1007 // template<class C>.
1008 Scope *OutermostTemplateScope = S->getParent();
1009 while (OutermostTemplateScope->getParent() &&
1010 OutermostTemplateScope->getParent()->isTemplateParamScope())
1011 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001012
Douglas Gregor66230062010-03-15 14:33:29 +00001013 // Find the namespace context in which the original scope occurs. In
1014 // the example, this is namespace N.
1015 DeclContext *Semantic = DC;
1016 while (!Semantic->isFileContext())
1017 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001018
Douglas Gregor66230062010-03-15 14:33:29 +00001019 // Find the declaration context just outside of the template
1020 // parameter scope. This is the context in which the template is
1021 // being lexically declaration (a namespace context). In the
1022 // example, this is the global scope.
1023 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
1024 Lexical->Encloses(Semantic))
1025 return std::make_pair(Semantic, true);
1026
1027 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +00001028}
1029
Richard Smith541b38b2013-09-20 01:15:31 +00001030namespace {
1031/// An RAII object to specify that we want to find block scope extern
1032/// declarations.
1033struct FindLocalExternScope {
1034 FindLocalExternScope(LookupResult &R)
1035 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
1036 Decl::IDNS_LocalExtern) {
Eric Fiselier5485cc12017-07-31 00:24:28 +00001037 R.setFindLocalExtern(R.getIdentifierNamespace() &
1038 (Decl::IDNS_Ordinary | Decl::IDNS_NonMemberOperator));
Richard Smith541b38b2013-09-20 01:15:31 +00001039 }
1040 void restore() {
1041 R.setFindLocalExtern(OldFindLocalExtern);
1042 }
1043 ~FindLocalExternScope() {
1044 restore();
1045 }
1046 LookupResult &R;
1047 bool OldFindLocalExtern;
1048};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001049} // end anonymous namespace
Richard Smith541b38b2013-09-20 01:15:31 +00001050
John McCall27b18f82009-11-17 02:14:36 +00001051bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001052 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +00001053
1054 DeclarationName Name = R.getLookupName();
Richard Smith1c34fb72013-08-13 18:18:50 +00001055 Sema::LookupNameKind NameKind = R.getLookupKind();
John McCall27b18f82009-11-17 02:14:36 +00001056
Douglas Gregor330b9cf2010-07-02 21:50:04 +00001057 // If this is the name of an implicitly-declared special member function,
1058 // go through the scope stack to implicitly declare
1059 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
1060 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +00001061 if (DeclContext *DC = PreS->getEntity())
Richard Smith32918772017-02-14 00:25:28 +00001062 DeclareImplicitMemberFunctionsWithName(*this, Name, R.getNameLoc(), DC);
Douglas Gregor330b9cf2010-07-02 21:50:04 +00001063 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001064
Douglas Gregor330b9cf2010-07-02 21:50:04 +00001065 // Implicitly declare member functions with the name we're looking for, if in
1066 // fact we are in a scope where it matters.
1067
Douglas Gregor889ceb72009-02-03 19:21:40 +00001068 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +00001069 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +00001070 I = IdResolver.begin(Name),
1071 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001072
Douglas Gregor889ceb72009-02-03 19:21:40 +00001073 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001074 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +00001075 // ...During unqualified name lookup (3.4.1), the names appear as if
1076 // they were declared in the nearest enclosing namespace which contains
1077 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +00001078 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +00001079 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +00001080 //
1081 // For example:
1082 // namespace A { int i; }
1083 // void foo() {
1084 // int i;
1085 // {
1086 // using namespace A;
1087 // ++i; // finds local 'i', A::i appears at global scope
1088 // }
1089 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +00001090 //
Richard Smithb920f852017-10-11 01:19:11 +00001091 UnqualUsingDirectiveSet UDirs(*this);
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001092 bool VisitedUsingDirectives = false;
Richard Smith1c34fb72013-08-13 18:18:50 +00001093 bool LeftStartingScope = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00001094 DeclContext *OutsideOfTemplateParamDC = nullptr;
Richard Smith541b38b2013-09-20 01:15:31 +00001095
1096 // When performing a scope lookup, we want to find local extern decls.
1097 FindLocalExternScope FindLocals(R);
1098
Douglas Gregor700792c2009-02-05 19:25:20 +00001099 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00001100 DeclContext *Ctx = S->getEntity();
Olivier Goffart12b221982016-06-16 21:39:46 +00001101 bool SearchNamespaceScope = true;
Douglas Gregor889ceb72009-02-03 19:21:40 +00001102 // Check whether the IdResolver has anything in this scope.
John McCall48871652010-08-21 09:40:31 +00001103 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001104 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Olivier Goffart12b221982016-06-16 21:39:46 +00001105 if (NameKind == LookupRedeclarationWithLinkage &&
1106 !(*I)->isTemplateParameter()) {
1107 // If it's a template parameter, we still find it, so we can diagnose
1108 // the invalid redeclaration.
1109
Richard Smith1c34fb72013-08-13 18:18:50 +00001110 // Determine whether this (or a previous) declaration is
1111 // out-of-scope.
1112 if (!LeftStartingScope && !Initial->isDeclScope(*I))
1113 LeftStartingScope = true;
1114
1115 // If we found something outside of our starting scope that
Olivier Goffart12b221982016-06-16 21:39:46 +00001116 // does not have linkage, skip it.
1117 if (LeftStartingScope && !((*I)->hasLinkage())) {
Richard Smith1c34fb72013-08-13 18:18:50 +00001118 R.setShadowed();
1119 continue;
1120 }
Olivier Goffart12b221982016-06-16 21:39:46 +00001121 } else {
1122 // We found something in this scope, we should not look at the
1123 // namespace scope
1124 SearchNamespaceScope = false;
Richard Smith1c34fb72013-08-13 18:18:50 +00001125 }
Douglas Gregor4a814562011-12-14 16:03:29 +00001126 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001127 }
1128 }
Olivier Goffart12b221982016-06-16 21:39:46 +00001129 if (!SearchNamespaceScope) {
John McCall9f3059a2009-10-09 21:13:30 +00001130 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +00001131 if (S->isClassScope())
1132 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
1133 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +00001134 return true;
1135 }
1136
Richard Smith1c34fb72013-08-13 18:18:50 +00001137 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
Richard Smith114394f2013-08-09 04:35:01 +00001138 // C++11 [class.friend]p11:
1139 // If a friend declaration appears in a local class and the name
1140 // specified is an unqualified name, a prior declaration is
1141 // looked up without considering scopes that are outside the
1142 // innermost enclosing non-class scope.
1143 return false;
1144 }
1145
Douglas Gregor66230062010-03-15 14:33:29 +00001146 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1147 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1148 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001149 // found nothing, so look into the contexts between the
Douglas Gregor66230062010-03-15 14:33:29 +00001150 // lexical and semantic declaration contexts returned by
1151 // findOuterContext(). This implements the name lookup behavior
1152 // of C++ [temp.local]p8.
1153 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +00001154 OutsideOfTemplateParamDC = nullptr;
Douglas Gregor66230062010-03-15 14:33:29 +00001155 }
1156
1157 if (Ctx) {
1158 DeclContext *OuterCtx;
1159 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001160 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregor66230062010-03-15 14:33:29 +00001161 if (SearchAfterTemplateScope)
1162 OutsideOfTemplateParamDC = OuterCtx;
1163
Douglas Gregorea166062010-03-15 15:26:48 +00001164 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +00001165 // We do not directly look into transparent contexts, since
1166 // those entities will be found in the nearest enclosing
1167 // non-transparent context.
1168 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +00001169 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +00001170
1171 // We do not look directly into function or method contexts,
1172 // since all of the local variables and parameters of the
1173 // function/method are present within the Scope.
1174 if (Ctx->isFunctionOrMethod()) {
1175 // If we have an Objective-C instance method, look for ivars
1176 // in the corresponding interface.
1177 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
1178 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1179 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1180 ObjCInterfaceDecl *ClassDeclared;
1181 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001182 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +00001183 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001184 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1185 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +00001186 R.resolveKind();
1187 return true;
1188 }
1189 }
1190 }
1191 }
1192
1193 continue;
1194 }
1195
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001196 // If this is a file context, we need to perform unqualified name
1197 // lookup considering using directives.
1198 if (Ctx->isFileContext()) {
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001199 // If we haven't handled using directives yet, do so now.
1200 if (!VisitedUsingDirectives) {
1201 // Add using directives from this context up to the top level.
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001202 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1203 if (UCtx->isTransparentContext())
1204 continue;
1205
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001206 UDirs.visit(UCtx, UCtx);
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001207 }
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001208
1209 // Find the innermost file scope, so we can add using directives
1210 // from local scopes.
1211 Scope *InnermostFileScope = S;
1212 while (InnermostFileScope &&
1213 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1214 InnermostFileScope = InnermostFileScope->getParent();
1215 UDirs.visitScopeChain(Initial, InnermostFileScope);
1216
1217 UDirs.done();
1218
1219 VisitedUsingDirectives = true;
1220 }
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001221
1222 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1223 R.resolveKind();
1224 return true;
1225 }
1226
1227 continue;
1228 }
1229
Douglas Gregor7f737c02009-09-10 16:57:35 +00001230 // Perform qualified name lookup into this context.
1231 // FIXME: In some cases, we know that every name that could be found by
1232 // this qualified name lookup will also be on the identifier chain. For
1233 // example, inside a class without any base classes, we never need to
1234 // perform qualified lookup because all of the members are on top of the
1235 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001236 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +00001237 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +00001238 }
Douglas Gregor700792c2009-02-05 19:25:20 +00001239 }
Douglas Gregored8f2882009-01-30 01:04:22 +00001240 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001241
John McCallf6c8a4e2009-11-10 07:01:13 +00001242 // Stop if we ran out of scopes.
1243 // FIXME: This really, really shouldn't be happening.
1244 if (!S) return false;
1245
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001246 // If we are looking for members, no need to look into global/namespace scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00001247 if (NameKind == LookupMemberName)
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001248 return false;
1249
Douglas Gregor700792c2009-02-05 19:25:20 +00001250 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +00001251 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +00001252 //
Mike Stump87c57ac2009-05-16 07:39:55 +00001253 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1254 // don't build it for each lookup!
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001255 if (!VisitedUsingDirectives) {
1256 UDirs.visitScopeChain(Initial, S);
1257 UDirs.done();
1258 }
Richard Smith541b38b2013-09-20 01:15:31 +00001259
1260 // If we're not performing redeclaration lookup, do not look for local
1261 // extern declarations outside of a function scope.
1262 if (!R.isForRedeclaration())
1263 FindLocals.restore();
1264
Douglas Gregor700792c2009-02-05 19:25:20 +00001265 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +00001266 // Unqualified name lookup in C++ requires looking into scopes
1267 // that aren't strictly lexical, and therefore we walk through the
1268 // context as well as walking through the scopes.
1269 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001270 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +00001271 bool Found = false;
John McCall48871652010-08-21 09:40:31 +00001272 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001273 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001274 // We found something. Look for anything else in our scope
1275 // with this same name and in an acceptable identifier
1276 // namespace, so that we can construct an overload set if we
1277 // need to.
John McCall9f3059a2009-10-09 21:13:30 +00001278 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +00001279 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001280 }
1281 }
1282
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001283 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +00001284 R.resolveKind();
1285 return true;
1286 }
1287
Ted Kremenekc37877d2013-10-08 17:08:03 +00001288 DeclContext *Ctx = S->getEntity();
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001289 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1290 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1291 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001292 // found nothing, so look into the contexts between the
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001293 // lexical and semantic declaration contexts returned by
1294 // findOuterContext(). This implements the name lookup behavior
1295 // of C++ [temp.local]p8.
1296 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +00001297 OutsideOfTemplateParamDC = nullptr;
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001298 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001299
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001300 if (Ctx) {
1301 DeclContext *OuterCtx;
1302 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001303 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001304 if (SearchAfterTemplateScope)
1305 OutsideOfTemplateParamDC = OuterCtx;
1306
1307 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1308 // We do not directly look into transparent contexts, since
1309 // those entities will be found in the nearest enclosing
1310 // non-transparent context.
1311 if (Ctx->isTransparentContext())
1312 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001313
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001314 // If we have a context, and it's not a context stashed in the
1315 // template parameter scope for an out-of-line definition, also
1316 // look into that context.
Chandler Carruth6232e4d2016-11-04 06:16:09 +00001317 if (!(Found && S->isTemplateParamScope())) {
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001318 assert(Ctx->isFileContext() &&
1319 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001320
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001321 // Look into context considering using-directives.
1322 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1323 Found = true;
1324 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001325
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001326 if (Found) {
1327 R.resolveKind();
1328 return true;
1329 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001330
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001331 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1332 return false;
1333 }
1334 }
1335
Douglas Gregor3ce74932010-02-05 07:07:10 +00001336 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001337 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001338 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001339
John McCall9f3059a2009-10-09 21:13:30 +00001340 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001341}
1342
Richard Smith858e0e02017-05-11 23:11:16 +00001343void Sema::makeMergedDefinitionVisible(NamedDecl *ND) {
1344 if (auto *M = getCurrentModule())
Richard Smith87bb5692015-06-09 00:35:49 +00001345 Context.mergeDefinitionIntoModule(ND, M);
1346 else
1347 // We're not building a module; just make the definition visible.
Richard Smith90dc5252017-06-23 01:04:34 +00001348 ND->setVisibleDespiteOwningModule();
Richard Smith63e09bf2015-06-17 20:39:41 +00001349
1350 // If ND is a template declaration, make the template parameters
1351 // visible too. They're not (necessarily) within a mergeable DeclContext.
1352 if (auto *TD = dyn_cast<TemplateDecl>(ND))
1353 for (auto *Param : *TD->getTemplateParameters())
Richard Smith858e0e02017-05-11 23:11:16 +00001354 makeMergedDefinitionVisible(Param);
Richard Smithd9ba2242015-05-07 03:54:19 +00001355}
1356
Richard Smith0e5d7b82013-07-25 23:08:39 +00001357/// \brief Find the module in which the given declaration was defined.
Richard Smith42413142015-05-15 20:05:43 +00001358static Module *getDefiningModule(Sema &S, Decl *Entity) {
Richard Smith0e5d7b82013-07-25 23:08:39 +00001359 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1360 // If this function was instantiated from a template, the defining module is
1361 // the module containing the pattern.
1362 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1363 Entity = Pattern;
1364 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
Reid Klecknere7367d62014-10-14 20:28:40 +00001365 if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
1366 Entity = Pattern;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001367 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
Richard Smith2195ec92017-04-21 01:15:13 +00001368 if (auto *Pattern = ED->getTemplateInstantiationPattern())
1369 Entity = Pattern;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001370 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
Richard Smith2195ec92017-04-21 01:15:13 +00001371 if (VarDecl *Pattern = VD->getTemplateInstantiationPattern())
1372 Entity = Pattern;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001373 }
1374
Chandler Carruthbd186c02017-04-19 05:25:13 +00001375 // Walk up to the containing context. That might also have been instantiated
1376 // from a template.
Richard Smith17ad3ac2017-10-18 01:41:38 +00001377 DeclContext *Context = Entity->getLexicalDeclContext();
Chandler Carruthbd186c02017-04-19 05:25:13 +00001378 if (Context->isFileContext())
1379 return S.getOwningModule(Entity);
1380 return getDefiningModule(S, cast<Decl>(Context));
Richard Smith0e5d7b82013-07-25 23:08:39 +00001381}
1382
1383llvm::DenseSet<Module*> &Sema::getLookupModules() {
Richard Smith696e3122017-02-23 01:43:54 +00001384 unsigned N = CodeSynthesisContexts.size();
1385 for (unsigned I = CodeSynthesisContextLookupModules.size();
Richard Smith0e5d7b82013-07-25 23:08:39 +00001386 I != N; ++I) {
Richard Smith696e3122017-02-23 01:43:54 +00001387 Module *M = getDefiningModule(*this, CodeSynthesisContexts[I].Entity);
Richard Smith0e5d7b82013-07-25 23:08:39 +00001388 if (M && !LookupModulesCache.insert(M).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00001389 M = nullptr;
Richard Smith696e3122017-02-23 01:43:54 +00001390 CodeSynthesisContextLookupModules.push_back(M);
Richard Smith0e5d7b82013-07-25 23:08:39 +00001391 }
1392 return LookupModulesCache;
1393}
1394
Richard Smith42413142015-05-15 20:05:43 +00001395bool Sema::hasVisibleMergedDefinition(NamedDecl *Def) {
1396 for (Module *Merged : Context.getModulesWithMergedDefinition(Def))
1397 if (isModuleVisible(Merged))
1398 return true;
1399 return false;
1400}
1401
Richard Smithe03a6542017-07-05 01:42:07 +00001402bool Sema::hasMergedDefinitionInCurrentModule(NamedDecl *Def) {
Richard Smithd19389a2017-07-05 07:47:11 +00001403 // FIXME: When not in local visibility mode, we can't tell the difference
1404 // between a declaration being visible because we merged a local copy of
1405 // the same declaration into it, and it being visible because its owning
1406 // module is visible.
1407 if (Def->getModuleOwnershipKind() == Decl::ModuleOwnershipKind::Visible &&
1408 getLangOpts().ModulesLocalVisibility)
1409 return true;
Richard Smithe03a6542017-07-05 01:42:07 +00001410 for (Module *Merged : Context.getModulesWithMergedDefinition(Def))
1411 if (Merged->getTopLevelModuleName() == getLangOpts().CurrentModule)
1412 return true;
1413 return false;
1414}
1415
Richard Smithe7bd6de2015-06-10 20:30:23 +00001416template<typename ParmDecl>
Richard Smith35c1df52015-06-17 20:16:32 +00001417static bool
1418hasVisibleDefaultArgument(Sema &S, const ParmDecl *D,
1419 llvm::SmallVectorImpl<Module *> *Modules) {
Richard Smithe7bd6de2015-06-10 20:30:23 +00001420 if (!D->hasDefaultArgument())
1421 return false;
1422
1423 while (D) {
1424 auto &DefaultArg = D->getDefaultArgStorage();
1425 if (!DefaultArg.isInherited() && S.isVisible(D))
1426 return true;
1427
Richard Smith63e09bf2015-06-17 20:39:41 +00001428 if (!DefaultArg.isInherited() && Modules) {
1429 auto *NonConstD = const_cast<ParmDecl*>(D);
1430 Modules->push_back(S.getOwningModule(NonConstD));
1431 const auto &Merged = S.Context.getModulesWithMergedDefinition(NonConstD);
1432 Modules->insert(Modules->end(), Merged.begin(), Merged.end());
1433 }
Richard Smith35c1df52015-06-17 20:16:32 +00001434
Richard Smithe7bd6de2015-06-10 20:30:23 +00001435 // If there was a previous default argument, maybe its parameter is visible.
1436 D = DefaultArg.getInheritedFrom();
1437 }
1438 return false;
1439}
1440
Richard Smith35c1df52015-06-17 20:16:32 +00001441bool Sema::hasVisibleDefaultArgument(const NamedDecl *D,
1442 llvm::SmallVectorImpl<Module *> *Modules) {
Richard Smithe7bd6de2015-06-10 20:30:23 +00001443 if (auto *P = dyn_cast<TemplateTypeParmDecl>(D))
Richard Smith35c1df52015-06-17 20:16:32 +00001444 return ::hasVisibleDefaultArgument(*this, P, Modules);
Richard Smithe7bd6de2015-06-10 20:30:23 +00001445 if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))
Richard Smith35c1df52015-06-17 20:16:32 +00001446 return ::hasVisibleDefaultArgument(*this, P, Modules);
1447 return ::hasVisibleDefaultArgument(*this, cast<TemplateTemplateParmDecl>(D),
1448 Modules);
Richard Smithe7bd6de2015-06-10 20:30:23 +00001449}
1450
Richard Smith54f04402017-05-18 02:29:20 +00001451template<typename Filter>
1452static bool hasVisibleDeclarationImpl(Sema &S, const NamedDecl *D,
1453 llvm::SmallVectorImpl<Module *> *Modules,
1454 Filter F) {
1455 for (auto *Redecl : D->redecls()) {
1456 auto *R = cast<NamedDecl>(Redecl);
1457 if (!F(R))
1458 continue;
1459
1460 if (S.isVisible(R))
1461 return true;
1462
1463 if (Modules) {
1464 Modules->push_back(R->getOwningModule());
1465 const auto &Merged = S.Context.getModulesWithMergedDefinition(R);
1466 Modules->insert(Modules->end(), Merged.begin(), Merged.end());
1467 }
1468 }
1469
1470 return false;
1471}
1472
1473bool Sema::hasVisibleExplicitSpecialization(
1474 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1475 return hasVisibleDeclarationImpl(*this, D, Modules, [](const NamedDecl *D) {
1476 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1477 return RD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
1478 if (auto *FD = dyn_cast<FunctionDecl>(D))
1479 return FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
1480 if (auto *VD = dyn_cast<VarDecl>(D))
1481 return VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
1482 llvm_unreachable("unknown explicit specialization kind");
1483 });
1484}
1485
Richard Smith6739a102016-05-05 00:56:12 +00001486bool Sema::hasVisibleMemberSpecialization(
1487 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1488 assert(isa<CXXRecordDecl>(D->getDeclContext()) &&
1489 "not a member specialization");
Richard Smith54f04402017-05-18 02:29:20 +00001490 return hasVisibleDeclarationImpl(*this, D, Modules, [](const NamedDecl *D) {
Richard Smith6739a102016-05-05 00:56:12 +00001491 // If the specialization is declared at namespace scope, then it's a member
1492 // specialization declaration. If it's lexically inside the class
1493 // definition then it was instantiated.
1494 //
1495 // FIXME: This is a hack. There should be a better way to determine this.
1496 // FIXME: What about MS-style explicit specializations declared within a
1497 // class definition?
Richard Smith54f04402017-05-18 02:29:20 +00001498 return D->getLexicalDeclContext()->isFileContext();
1499 });
Richard Smith6739a102016-05-05 00:56:12 +00001500
1501 return false;
1502}
1503
Richard Smith0e5d7b82013-07-25 23:08:39 +00001504/// \brief Determine whether a declaration is visible to name lookup.
1505///
1506/// This routine determines whether the declaration D is visible in the current
1507/// lookup context, taking into account the current template instantiation
1508/// stack. During template instantiation, a declaration is visible if it is
1509/// visible from a module containing any entity on the template instantiation
1510/// path (by instantiating a template, you allow it to see the declarations that
1511/// your module can see, including those later on in your module).
1512bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001513 assert(D->isHidden() && "should not call this: not in slow case");
Richard Smith5196a172015-08-24 03:38:11 +00001514
Richard Smith54f04402017-05-18 02:29:20 +00001515 Module *DeclModule = SemaRef.getOwningModule(D);
Richard Smithe03a6542017-07-05 01:42:07 +00001516 if (!DeclModule) {
1517 // A module-private declaration with no owning module means this is in the
1518 // global module in the C++ Modules TS. This is visible within the same
1519 // translation unit only.
1520 // FIXME: Don't assume that "same translation unit" means the same thing
1521 // as "not from an AST file".
1522 assert(D->isModulePrivate() && "hidden decl has no module");
Richard Smithd19389a2017-07-05 07:47:11 +00001523 if (!D->isFromASTFile() || SemaRef.hasMergedDefinitionInCurrentModule(D))
1524 return true;
1525 } else {
1526 // If the owning module is visible, and the decl is not module private,
1527 // then the decl is visible too. (Module private is ignored within the same
1528 // top-level module.)
1529 if (D->isModulePrivate()
1530 ? DeclModule->getTopLevelModuleName() ==
1531 SemaRef.getLangOpts().CurrentModule ||
1532 SemaRef.hasMergedDefinitionInCurrentModule(D)
1533 : SemaRef.isModuleVisible(DeclModule) ||
1534 SemaRef.hasVisibleMergedDefinition(D))
1535 return true;
Richard Smithe03a6542017-07-05 01:42:07 +00001536 }
Richard Smith54f04402017-05-18 02:29:20 +00001537
Richard Smithd19389a2017-07-05 07:47:11 +00001538 // Determine whether a decl context is a file context for the purpose of
1539 // visibility. This looks through some (export and linkage spec) transparent
1540 // contexts, but not others (enums).
1541 auto IsEffectivelyFileContext = [](const DeclContext *DC) {
1542 return DC->isFileContext() || isa<LinkageSpecDecl>(DC) ||
1543 isa<ExportDecl>(DC);
1544 };
Richard Smith0e5d7b82013-07-25 23:08:39 +00001545
Richard Smithd19389a2017-07-05 07:47:11 +00001546 // If this declaration is not at namespace scope
Richard Smithbe3980b2015-03-27 00:41:57 +00001547 // then it is visible if its lexical parent has a visible definition.
1548 DeclContext *DC = D->getLexicalDeclContext();
Richard Smithd19389a2017-07-05 07:47:11 +00001549 if (DC && !IsEffectivelyFileContext(DC)) {
Richard Smithc7d48d12015-05-20 17:50:35 +00001550 // For a parameter, check whether our current template declaration's
1551 // lexical context is visible, not whether there's some other visible
1552 // definition of it, because parameters aren't "within" the definition.
Vassil Vassilev714b81c2016-09-08 20:34:41 +00001553 //
1554 // In C++ we need to check for a visible definition due to ODR merging,
1555 // and in C we must not because each declaration of a function gets its own
1556 // set of declarations for tags in prototype scope.
Richard Smithd19389a2017-07-05 07:47:11 +00001557 bool VisibleWithinParent;
1558 if (D->isTemplateParameter() || isa<ParmVarDecl>(D) ||
1559 (isa<FunctionDecl>(DC) && !SemaRef.getLangOpts().CPlusPlus))
1560 VisibleWithinParent = isVisible(SemaRef, cast<NamedDecl>(DC));
1561 else if (D->isModulePrivate()) {
1562 // A module-private declaration is only visible if an enclosing lexical
1563 // parent was merged with another definition in the current module.
1564 VisibleWithinParent = false;
1565 do {
1566 if (SemaRef.hasMergedDefinitionInCurrentModule(cast<NamedDecl>(DC))) {
1567 VisibleWithinParent = true;
1568 break;
1569 }
1570 DC = DC->getLexicalParent();
1571 } while (!IsEffectivelyFileContext(DC));
1572 } else {
1573 VisibleWithinParent = SemaRef.hasVisibleDefinition(cast<NamedDecl>(DC));
Richard Smithbe3980b2015-03-27 00:41:57 +00001574 }
Richard Smithd19389a2017-07-05 07:47:11 +00001575
1576 if (VisibleWithinParent && SemaRef.CodeSynthesisContexts.empty() &&
1577 // FIXME: Do something better in this case.
1578 !SemaRef.getLangOpts().ModulesLocalVisibility) {
1579 // Cache the fact that this declaration is implicitly visible because
1580 // its parent has a visible definition.
1581 D->setVisibleDespiteOwningModule();
1582 }
1583 return VisibleWithinParent;
Richard Smithbe3980b2015-03-27 00:41:57 +00001584 }
1585
Richard Smithd19389a2017-07-05 07:47:11 +00001586 // FIXME: All uses of DeclModule below this point should also check merged
1587 // modules.
1588 if (!DeclModule)
1589 return false;
1590
Richard Smith0e5d7b82013-07-25 23:08:39 +00001591 // Find the extra places where we need to look.
Hamza Soodd79c4402017-12-27 18:05:29 +00001592 const auto &LookupModules = SemaRef.getLookupModules();
Richard Smith0e5d7b82013-07-25 23:08:39 +00001593 if (LookupModules.empty())
1594 return false;
1595
1596 // If our lookup set contains the decl's module, it's visible.
1597 if (LookupModules.count(DeclModule))
1598 return true;
1599
1600 // If the declaration isn't exported, it's not visible in any other module.
1601 if (D->isModulePrivate())
1602 return false;
1603
1604 // Check whether DeclModule is transitively exported to an import of
1605 // the lookup set.
Yaron Keren941ad902015-11-23 19:28:42 +00001606 return std::any_of(LookupModules.begin(), LookupModules.end(),
Hamza Soodd79c4402017-12-27 18:05:29 +00001607 [&](const Module *M) {
1608 return M->isModuleVisible(DeclModule); });
Richard Smith0e5d7b82013-07-25 23:08:39 +00001609}
1610
Richard Smith42413142015-05-15 20:05:43 +00001611bool Sema::isVisibleSlow(const NamedDecl *D) {
1612 return LookupResult::isVisible(*this, const_cast<NamedDecl*>(D));
1613}
1614
Richard Smith10568d82015-11-17 03:02:41 +00001615bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) {
Richard Smithbecb92d2017-10-10 22:33:17 +00001616 // FIXME: If there are both visible and hidden declarations, we need to take
1617 // into account whether redeclaration is possible. Example:
1618 //
1619 // Non-imported module:
1620 // int f(T); // #1
1621 // Some TU:
1622 // static int f(U); // #2, not a redeclaration of #1
1623 // int f(T); // #3, finds both, should link with #1 if T != U, but
1624 // // with #2 if T == U; neither should be ambiguous.
Richard Smith10568d82015-11-17 03:02:41 +00001625 for (auto *D : R) {
1626 if (isVisible(D))
1627 return true;
Richard Smithbecb92d2017-10-10 22:33:17 +00001628 assert(D->isExternallyDeclarable() &&
1629 "should not have hidden, non-externally-declarable result here");
Richard Smith10568d82015-11-17 03:02:41 +00001630 }
Richard Smithbecb92d2017-10-10 22:33:17 +00001631
1632 // This function is called once "New" is essentially complete, but before a
1633 // previous declaration is attached. We can't query the linkage of "New" in
1634 // general, because attaching the previous declaration can change the
1635 // linkage of New to match the previous declaration.
1636 //
1637 // However, because we've just determined that there is no *visible* prior
1638 // declaration, we can compute the linkage here. There are two possibilities:
1639 //
1640 // * This is not a redeclaration; it's safe to compute the linkage now.
1641 //
1642 // * This is a redeclaration of a prior declaration that is externally
1643 // redeclarable. In that case, the linkage of the declaration is not
1644 // changed by attaching the prior declaration, because both are externally
1645 // declarable (and thus ExternalLinkage or VisibleNoLinkage).
1646 //
1647 // FIXME: This is subtle and fragile.
1648 return New->isExternallyDeclarable();
Richard Smith10568d82015-11-17 03:02:41 +00001649}
1650
Douglas Gregor4a814562011-12-14 16:03:29 +00001651/// \brief Retrieve the visible declaration corresponding to D, if any.
1652///
1653/// This routine determines whether the declaration D is visible in the current
1654/// module, with the current imports. If not, it checks whether any
1655/// redeclaration of D is visible, and if so, returns that declaration.
Richard Smith0e5d7b82013-07-25 23:08:39 +00001656///
Douglas Gregor4a814562011-12-14 16:03:29 +00001657/// \returns D, or a visible previous declaration of D, whichever is more recent
1658/// and visible. If no declaration of D is visible, returns null.
Richard Smith041740f2018-01-06 00:09:23 +00001659static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D,
1660 unsigned IDNS) {
Richard Smithe156254d2013-08-20 20:35:18 +00001661 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
Richard Smith0e5d7b82013-07-25 23:08:39 +00001662
Aaron Ballman86c93902014-03-06 23:45:36 +00001663 for (auto RD : D->redecls()) {
Richard Smith4083e032016-02-17 21:52:44 +00001664 // Don't bother with extra checks if we already know this one isn't visible.
1665 if (RD == D)
1666 continue;
1667
Richard Smith6739a102016-05-05 00:56:12 +00001668 auto ND = cast<NamedDecl>(RD);
1669 // FIXME: This is wrong in the case where the previous declaration is not
1670 // visible in the same scope as D. This needs to be done much more
1671 // carefully.
Richard Smith041740f2018-01-06 00:09:23 +00001672 if (ND->isInIdentifierNamespace(IDNS) &&
1673 LookupResult::isVisible(SemaRef, ND))
Richard Smith6739a102016-05-05 00:56:12 +00001674 return ND;
Douglas Gregor4a814562011-12-14 16:03:29 +00001675 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001676
Craig Topperc3ec1492014-05-26 06:22:03 +00001677 return nullptr;
Douglas Gregor4a814562011-12-14 16:03:29 +00001678}
1679
Richard Smith6739a102016-05-05 00:56:12 +00001680bool Sema::hasVisibleDeclarationSlow(const NamedDecl *D,
1681 llvm::SmallVectorImpl<Module *> *Modules) {
1682 assert(!isVisible(D) && "not in slow case");
Richard Smith54f04402017-05-18 02:29:20 +00001683 return hasVisibleDeclarationImpl(*this, D, Modules,
1684 [](const NamedDecl *) { return true; });
Richard Smith6739a102016-05-05 00:56:12 +00001685}
1686
Richard Smithe156254d2013-08-20 20:35:18 +00001687NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
Richard Smith4083e032016-02-17 21:52:44 +00001688 if (auto *ND = dyn_cast<NamespaceDecl>(D)) {
1689 // Namespaces are a bit of a special case: we expect there to be a lot of
1690 // redeclarations of some namespaces, all declarations of a namespace are
1691 // essentially interchangeable, all declarations are found by name lookup
1692 // if any is, and namespaces are never looked up during template
1693 // instantiation. So we benefit from caching the check in this case, and
1694 // it is correct to do so.
1695 auto *Key = ND->getCanonicalDecl();
1696 if (auto *Acceptable = getSema().VisibleNamespaceCache.lookup(Key))
1697 return Acceptable;
Richard Smith041740f2018-01-06 00:09:23 +00001698 auto *Acceptable = isVisible(getSema(), Key)
1699 ? Key
1700 : findAcceptableDecl(getSema(), Key, IDNS);
Richard Smith4083e032016-02-17 21:52:44 +00001701 if (Acceptable)
1702 getSema().VisibleNamespaceCache.insert(std::make_pair(Key, Acceptable));
1703 return Acceptable;
1704 }
1705
Richard Smith041740f2018-01-06 00:09:23 +00001706 return findAcceptableDecl(getSema(), D, IDNS);
Richard Smithe156254d2013-08-20 20:35:18 +00001707}
1708
Douglas Gregor34074322009-01-14 22:20:51 +00001709/// @brief Perform unqualified name lookup starting from a given
1710/// scope.
1711///
1712/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1713/// used to find names within the current scope. For example, 'x' in
1714/// @code
1715/// int x;
1716/// int f() {
1717/// return x; // unqualified name look finds 'x' in the global scope
1718/// }
1719/// @endcode
1720///
1721/// Different lookup criteria can find different names. For example, a
1722/// particular scope can have both a struct and a function of the same
1723/// name, and each can be found by certain lookup criteria. For more
1724/// information about lookup criteria, see the documentation for the
1725/// class LookupCriteria.
1726///
1727/// @param S The scope from which unqualified name lookup will
1728/// begin. If the lookup criteria permits, name lookup may also search
1729/// in the parent scopes.
1730///
James Dennett91738ff2012-06-22 10:32:46 +00001731/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1732/// look up and the lookup kind), and is updated with the results of lookup
1733/// including zero or more declarations and possibly additional information
1734/// used to diagnose ambiguities.
Douglas Gregor34074322009-01-14 22:20:51 +00001735///
James Dennett91738ff2012-06-22 10:32:46 +00001736/// @returns \c true if lookup succeeded and false otherwise.
John McCall27b18f82009-11-17 02:14:36 +00001737bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1738 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001739 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001740
John McCall27b18f82009-11-17 02:14:36 +00001741 LookupNameKind NameKind = R.getLookupKind();
1742
David Blaikiebbafb8a2012-03-11 07:00:24 +00001743 if (!getLangOpts().CPlusPlus) {
Douglas Gregor34074322009-01-14 22:20:51 +00001744 // Unqualified name lookup in C/Objective-C is purely lexical, so
1745 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001746 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001747 // Find the nearest non-transparent declaration scope.
1748 while (!(S->getFlags() & Scope::DeclScope) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001749 (S->getEntity() && S->getEntity()->isTransparentContext()))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001750 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001751 }
1752
Richard Smith541b38b2013-09-20 01:15:31 +00001753 // When performing a scope lookup, we want to find local extern decls.
1754 FindLocalExternScope FindLocals(R);
1755
Douglas Gregor34074322009-01-14 22:20:51 +00001756 // Scan up the scope chain looking for a decl that matches this
1757 // identifier that is in the appropriate namespace. This search
1758 // should not take long, as shadowing of names is uncommon, and
1759 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001760 bool LeftStartingScope = false;
1761
Douglas Gregored8f2882009-01-30 01:04:22 +00001762 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001763 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001764 I != IEnd; ++I)
Richard Smith0e5d7b82013-07-25 23:08:39 +00001765 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001766 if (NameKind == LookupRedeclarationWithLinkage) {
1767 // Determine whether this (or a previous) declaration is
1768 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001769 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001770 LeftStartingScope = true;
1771
1772 // If we found something outside of our starting scope that
1773 // does not have linkage, skip it.
Richard Smith1c34fb72013-08-13 18:18:50 +00001774 if (LeftStartingScope && !((*I)->hasLinkage())) {
1775 R.setShadowed();
Douglas Gregoreddf4332009-02-24 20:03:32 +00001776 continue;
Richard Smith1c34fb72013-08-13 18:18:50 +00001777 }
Douglas Gregoreddf4332009-02-24 20:03:32 +00001778 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001779 else if (NameKind == LookupObjCImplicitSelfParam &&
1780 !isa<ImplicitParamDecl>(*I))
1781 continue;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001782
Douglas Gregor4a814562011-12-14 16:03:29 +00001783 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001784
Douglas Gregorb59643b2012-01-03 23:26:26 +00001785 // Check whether there are any other declarations with the same name
1786 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001787 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001788 // Find the scope in which this declaration was declared (if it
1789 // actually exists in a Scope).
1790 while (S && !S->isDeclScope(D))
1791 S = S->getParent();
1792
1793 // If the scope containing the declaration is the translation unit,
1794 // then we'll need to perform our checks based on the matching
1795 // DeclContexts rather than matching scopes.
1796 if (S && isNamespaceOrTranslationUnitScope(S))
Craig Topperc3ec1492014-05-26 06:22:03 +00001797 S = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001798
1799 // Compute the DeclContext, if we need it.
Craig Topperc3ec1492014-05-26 06:22:03 +00001800 DeclContext *DC = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001801 if (!S)
1802 DC = (*I)->getDeclContext()->getRedeclContext();
1803
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001804 IdentifierResolver::iterator LastI = I;
1805 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001806 if (S) {
1807 // Match based on scope.
1808 if (!S->isDeclScope(*LastI))
1809 break;
1810 } else {
1811 // Match based on DeclContext.
1812 DeclContext *LastDC
1813 = (*LastI)->getDeclContext()->getRedeclContext();
1814 if (!LastDC->Equals(DC))
1815 break;
1816 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001817
1818 // If the declaration is in the right namespace and visible, add it.
1819 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1820 R.addDecl(LastD);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001821 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001822
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001823 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001824 }
Richard Smith541b38b2013-09-20 01:15:31 +00001825
John McCall9f3059a2009-10-09 21:13:30 +00001826 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001827 }
Douglas Gregor34074322009-01-14 22:20:51 +00001828 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001829 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001830 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001831 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001832 }
1833
1834 // If we didn't find a use of this identifier, and if the identifier
1835 // corresponds to a compiler builtin, create the decl object for the builtin
1836 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001837 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1838 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001839
Axel Naumann016538a2011-02-24 16:47:47 +00001840 // If we didn't find a use of this identifier, the ExternalSource
1841 // may be able to handle the situation.
1842 // Note: some lookup failures are expected!
1843 // See e.g. R.isForRedeclaration().
1844 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001845}
1846
John McCall6538c932009-10-10 05:48:19 +00001847/// @brief Perform qualified name lookup in the namespaces nominated by
1848/// using directives by the given context.
1849///
1850/// C++98 [namespace.qual]p2:
James Dennett51a8d8b2012-06-19 21:05:49 +00001851/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6538c932009-10-10 05:48:19 +00001852/// (where X is the global namespace), let S be the set of all
1853/// declarations of m in X and in the transitive closure of all
1854/// namespaces nominated by using-directives in X and its used
1855/// namespaces, except that using-directives are ignored in any
1856/// namespace, including X, directly containing one or more
1857/// declarations of m. No namespace is searched more than once in
1858/// the lookup of a name. If S is the empty set, the program is
1859/// ill-formed. Otherwise, if S has exactly one member, or if the
1860/// context of the reference is a using-declaration
1861/// (namespace.udecl), S is the required set of declarations of
1862/// m. Otherwise if the use of m is not one that allows a unique
1863/// declaration to be chosen from S, the program is ill-formed.
James Dennett51a8d8b2012-06-19 21:05:49 +00001864///
John McCall6538c932009-10-10 05:48:19 +00001865/// C++98 [namespace.qual]p5:
1866/// During the lookup of a qualified namespace member name, if the
1867/// lookup finds more than one declaration of the member, and if one
1868/// declaration introduces a class name or enumeration name and the
1869/// other declarations either introduce the same object, the same
1870/// enumerator or a set of functions, the non-type name hides the
1871/// class or enumeration name if and only if the declarations are
1872/// from the same namespace; otherwise (the declarations are from
1873/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001874static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001875 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001876 assert(StartDC->isFileContext() && "start context is not a file context");
1877
Richard Smithb920f852017-10-11 01:19:11 +00001878 // We have not yet looked into these namespaces, much less added
1879 // their "using-children" to the queue.
1880 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001881
1882 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001883 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001884 Visited.insert(StartDC);
1885
John McCall6538c932009-10-10 05:48:19 +00001886 // We have already looked into the initial namespace; seed the queue
1887 // with its using-children.
Richard Smithb920f852017-10-11 01:19:11 +00001888 for (auto *I : StartDC->using_directives()) {
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001889 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
Richard Smitha544c512017-10-30 22:38:20 +00001890 if (S.isVisible(I) && Visited.insert(ND).second)
John McCall6538c932009-10-10 05:48:19 +00001891 Queue.push_back(ND);
1892 }
1893
1894 // The easiest way to implement the restriction in [namespace.qual]p5
1895 // is to check whether any of the individual results found a tag
1896 // and, if so, to declare an ambiguity if the final result is not
1897 // a tag.
1898 bool FoundTag = false;
1899 bool FoundNonTag = false;
1900
John McCall5cebab12009-11-18 07:57:50 +00001901 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001902
1903 bool Found = false;
1904 while (!Queue.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001905 NamespaceDecl *ND = Queue.pop_back_val();
John McCall6538c932009-10-10 05:48:19 +00001906
1907 // We go through some convolutions here to avoid copying results
1908 // between LookupResults.
1909 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001910 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001911 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001912
1913 if (FoundDirect) {
1914 // First do any local hiding.
1915 DirectR.resolveKind();
1916
1917 // If the local result is a tag, remember that.
1918 if (DirectR.isSingleTagDecl())
1919 FoundTag = true;
1920 else
1921 FoundNonTag = true;
1922
1923 // Append the local results to the total results if necessary.
1924 if (UseLocal) {
1925 R.addAllDecls(LocalR);
1926 LocalR.clear();
1927 }
1928 }
1929
1930 // If we find names in this namespace, ignore its using directives.
1931 if (FoundDirect) {
1932 Found = true;
1933 continue;
1934 }
1935
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001936 for (auto I : ND->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00001937 NamespaceDecl *Nom = I->getNominatedNamespace();
Richard Smitha544c512017-10-30 22:38:20 +00001938 if (S.isVisible(I) && Visited.insert(Nom).second)
John McCall6538c932009-10-10 05:48:19 +00001939 Queue.push_back(Nom);
1940 }
1941 }
1942
1943 if (Found) {
1944 if (FoundTag && FoundNonTag)
1945 R.setAmbiguousQualifiedTagHiding();
1946 else
1947 R.resolveKind();
1948 }
1949
1950 return Found;
1951}
1952
Douglas Gregor39982192010-08-15 06:18:01 +00001953/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001954static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00001955 CXXBasePath &Path, DeclarationName Name) {
Douglas Gregor39982192010-08-15 06:18:01 +00001956 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001957
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00001958 Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00001959 return !Path.Decls.empty();
Douglas Gregor39982192010-08-15 06:18:01 +00001960}
1961
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001962/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001963/// static members, nested types, and enumerators.
1964template<typename InputIterator>
1965static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1966 Decl *D = (*First)->getUnderlyingDecl();
1967 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1968 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001969
Douglas Gregorc0d24902010-10-22 22:08:47 +00001970 if (isa<CXXMethodDecl>(D)) {
1971 // Determine whether all of the methods are static.
1972 bool AllMethodsAreStatic = true;
1973 for(; First != Last; ++First) {
1974 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001975
Douglas Gregorc0d24902010-10-22 22:08:47 +00001976 if (!isa<CXXMethodDecl>(D)) {
1977 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1978 break;
1979 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001980
Douglas Gregorc0d24902010-10-22 22:08:47 +00001981 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1982 AllMethodsAreStatic = false;
1983 break;
1984 }
1985 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001986
Douglas Gregorc0d24902010-10-22 22:08:47 +00001987 if (AllMethodsAreStatic)
1988 return true;
1989 }
1990
1991 return false;
1992}
1993
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001994/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001995///
1996/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1997/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001998/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001999///
2000/// Different lookup criteria can find different names. For example, a
2001/// particular scope can have both a struct and a function of the same
2002/// name, and each can be found by certain lookup criteria. For more
2003/// information about lookup criteria, see the documentation for the
2004/// class LookupCriteria.
2005///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002006/// \param R captures both the lookup criteria and any lookup results found.
2007///
2008/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00002009/// search. If the lookup criteria permits, name lookup may also search
2010/// in the parent contexts or (for C++ classes) base classes.
2011///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002012/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002013/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00002014///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002015/// \returns true if lookup succeeded, false if it failed.
2016bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2017 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00002018 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00002019
John McCall27b18f82009-11-17 02:14:36 +00002020 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00002021 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002022
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002023 // Make sure that the declaration context is complete.
2024 assert((!isa<TagDecl>(LookupCtx) ||
2025 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00002026 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith7d137e32012-03-23 03:33:32 +00002027 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002028 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00002029
Eugene Leviant0d8103e2015-11-18 12:48:05 +00002030 struct QualifiedLookupInScope {
2031 bool oldVal;
2032 DeclContext *Context;
2033 // Set flag in DeclContext informing debugger that we're looking for qualified name
2034 QualifiedLookupInScope(DeclContext *ctx) : Context(ctx) {
2035 oldVal = ctx->setUseQualifiedLookup();
2036 }
2037 ~QualifiedLookupInScope() {
2038 Context->setUseQualifiedLookup(oldVal);
2039 }
2040 } QL(LookupCtx);
2041
Douglas Gregord3a59182010-02-12 05:48:04 +00002042 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00002043 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00002044 if (isa<CXXRecordDecl>(LookupCtx))
2045 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00002046 return true;
2047 }
Douglas Gregor34074322009-01-14 22:20:51 +00002048
John McCall6538c932009-10-10 05:48:19 +00002049 // Don't descend into implied contexts for redeclarations.
2050 // C++98 [namespace.qual]p6:
2051 // In a declaration for a namespace member in which the
2052 // declarator-id is a qualified-id, given that the qualified-id
2053 // for the namespace member has the form
2054 // nested-name-specifier unqualified-id
2055 // the unqualified-id shall name a member of the namespace
2056 // designated by the nested-name-specifier.
2057 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00002058 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00002059 return false;
2060
John McCall27b18f82009-11-17 02:14:36 +00002061 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00002062 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00002063 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00002064
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002065 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00002066 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002067 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00002068 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00002069 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002070
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002071 // If we're performing qualified name lookup into a dependent class,
2072 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002073 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002074 // template instantiation time (at which point all bases will be available)
2075 // or we have to fail.
2076 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
2077 LookupRec->hasAnyDependentBases()) {
2078 R.setNotFoundInCurrentInstantiation();
2079 return false;
2080 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002081
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002082 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00002083 CXXBasePaths Paths;
2084 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002085
2086 // Look for this member in our base classes
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00002087 bool (*BaseCallback)(const CXXBaseSpecifier *Specifier, CXXBasePath &Path,
2088 DeclarationName Name) = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00002089 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00002090 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00002091 case LookupOrdinaryName:
2092 case LookupMemberName:
2093 case LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +00002094 case LookupLocalFriendName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00002095 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
2096 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002097
Douglas Gregor36d1b142009-10-06 17:59:45 +00002098 case LookupTagName:
2099 BaseCallback = &CXXRecordDecl::FindTagMember;
2100 break;
John McCall84d87672009-12-10 09:41:52 +00002101
Douglas Gregor39982192010-08-15 06:18:01 +00002102 case LookupAnyName:
2103 BaseCallback = &LookupAnyMember;
2104 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002105
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002106 case LookupOMPReductionName:
2107 BaseCallback = &CXXRecordDecl::FindOMPReductionMember;
2108 break;
2109
John McCall84d87672009-12-10 09:41:52 +00002110 case LookupUsingDeclName:
2111 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002112
Douglas Gregor36d1b142009-10-06 17:59:45 +00002113 case LookupOperatorName:
2114 case LookupNamespaceName:
2115 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002116 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00002117 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00002118 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002119
Douglas Gregor36d1b142009-10-06 17:59:45 +00002120 case LookupNestedNameSpecifierName:
2121 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
2122 break;
2123 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002124
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00002125 DeclarationName Name = R.getLookupName();
2126 if (!LookupRec->lookupInBases(
2127 [=](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
2128 return BaseCallback(Specifier, Path, Name);
2129 },
2130 Paths))
John McCall9f3059a2009-10-09 21:13:30 +00002131 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002132
John McCall553c0792010-01-23 00:46:32 +00002133 R.setNamingClass(LookupRec);
2134
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002135 // C++ [class.member.lookup]p2:
2136 // [...] If the resulting set of declarations are not all from
2137 // sub-objects of the same type, or the set has a nonstatic member
2138 // and includes members from distinct sub-objects, there is an
2139 // ambiguity and the program is ill-formed. Otherwise that set is
2140 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002141 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00002142 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00002143 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002144
Douglas Gregor36d1b142009-10-06 17:59:45 +00002145 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002146 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00002147 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002148
John McCall401982f2010-01-20 21:53:11 +00002149 // Pick the best (i.e. most permissive i.e. numerically lowest) access
2150 // across all paths.
2151 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002152
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002153 // Determine whether we're looking at a distinct sub-object or not.
2154 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00002155 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002156 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
2157 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00002158 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002159 }
2160
Douglas Gregorc0d24902010-10-22 22:08:47 +00002161 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002162 != Context.getCanonicalType(PathElement.Base->getType())) {
2163 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00002164 // different types. If the declaration sets aren't the same, this
Nikola Smiljanic1c125682014-07-09 05:42:35 +00002165 // lookup is ambiguous.
David Blaikieff7d47a2012-12-19 00:45:41 +00002166 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00002167 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikieff7d47a2012-12-19 00:45:41 +00002168 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
2169 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002170
David Blaikieff7d47a2012-12-19 00:45:41 +00002171 while (FirstD != FirstPath->Decls.end() &&
2172 CurrentD != Path->Decls.end()) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00002173 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
2174 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
2175 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002176
Douglas Gregorc0d24902010-10-22 22:08:47 +00002177 ++FirstD;
2178 ++CurrentD;
2179 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002180
David Blaikieff7d47a2012-12-19 00:45:41 +00002181 if (FirstD == FirstPath->Decls.end() &&
2182 CurrentD == Path->Decls.end())
Douglas Gregorc0d24902010-10-22 22:08:47 +00002183 continue;
2184 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002185
John McCall9f3059a2009-10-09 21:13:30 +00002186 R.setAmbiguousBaseSubobjectTypes(Paths);
2187 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002188 }
2189
Douglas Gregorc0d24902010-10-22 22:08:47 +00002190 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002191 // We have a different subobject of the same type.
2192
2193 // C++ [class.member.lookup]p5:
2194 // A static member, a nested type or an enumerator defined in
2195 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00002196 // has more than one base class subobject of type T.
David Blaikieff7d47a2012-12-19 00:45:41 +00002197 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002198 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002199
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002200 // We have found a nonstatic member name in multiple, distinct
2201 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00002202 R.setAmbiguousBaseSubobjects(Paths);
2203 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002204 }
2205 }
2206
2207 // Lookup in a base class succeeded; return these results.
2208
Aaron Ballman1e606f42014-07-15 22:03:49 +00002209 for (auto *D : Paths.front().Decls) {
John McCall553c0792010-01-23 00:46:32 +00002210 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
2211 D->getAccess());
2212 R.addDecl(D, AS);
2213 }
John McCall9f3059a2009-10-09 21:13:30 +00002214 R.resolveKind();
2215 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00002216}
2217
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00002218/// \brief Performs qualified name lookup or special type of lookup for
2219/// "__super::" scope specifier.
2220///
2221/// This routine is a convenience overload meant to be called from contexts
2222/// that need to perform a qualified name lookup with an optional C++ scope
2223/// specifier that might require special kind of lookup.
2224///
2225/// \param R captures both the lookup criteria and any lookup results found.
2226///
2227/// \param LookupCtx The context in which qualified name lookup will
2228/// search.
2229///
2230/// \param SS An optional C++ scope-specifier.
2231///
2232/// \returns true if lookup succeeded, false if it failed.
2233bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2234 CXXScopeSpec &SS) {
2235 auto *NNS = SS.getScopeRep();
2236 if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
2237 return LookupInSuper(R, NNS->getAsRecordDecl());
2238 else
2239
2240 return LookupQualifiedName(R, LookupCtx);
2241}
2242
Douglas Gregor34074322009-01-14 22:20:51 +00002243/// @brief Performs name lookup for a name that was parsed in the
2244/// source code, and may contain a C++ scope specifier.
2245///
2246/// This routine is a convenience routine meant to be called from
2247/// contexts that receive a name and an optional C++ scope specifier
2248/// (e.g., "N::M::x"). It will then perform either qualified or
2249/// unqualified name lookup (with LookupQualifiedName or LookupName,
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002250/// respectively) on the given name and return those results. It will
2251/// perform a special type of lookup for "__super::" scope specifier.
Douglas Gregor34074322009-01-14 22:20:51 +00002252///
2253/// @param S The scope from which unqualified name lookup will
2254/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00002255///
Douglas Gregore861bac2009-08-25 22:51:20 +00002256/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00002257///
Douglas Gregore861bac2009-08-25 22:51:20 +00002258/// @param EnteringContext Indicates whether we are going to enter the
2259/// context of the scope-specifier SS (if present).
2260///
John McCall9f3059a2009-10-09 21:13:30 +00002261/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002262bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00002263 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00002264 if (SS && SS->isInvalid()) {
2265 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002266 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00002267 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00002268 }
Mike Stump11289f42009-09-09 15:08:12 +00002269
Douglas Gregore861bac2009-08-25 22:51:20 +00002270 if (SS && SS->isSet()) {
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002271 NestedNameSpecifier *NNS = SS->getScopeRep();
2272 if (NNS->getKind() == NestedNameSpecifier::Super)
2273 return LookupInSuper(R, NNS->getAsRecordDecl());
2274
Douglas Gregore861bac2009-08-25 22:51:20 +00002275 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00002276 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00002277 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00002278 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00002279 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002280
John McCall27b18f82009-11-17 02:14:36 +00002281 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00002282 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00002283 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002284
Douglas Gregore861bac2009-08-25 22:51:20 +00002285 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00002286 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00002287 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00002288 R.setNotFoundInCurrentInstantiation();
2289 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00002290 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00002291 }
2292
Mike Stump11289f42009-09-09 15:08:12 +00002293 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00002294 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00002295}
2296
Nikola Smiljanic67860242014-09-26 00:28:20 +00002297/// \brief Perform qualified name lookup into all base classes of the given
2298/// class.
2299///
2300/// \param R captures both the lookup criteria and any lookup results found.
2301///
2302/// \param Class The context in which qualified name lookup will
2303/// search. Name lookup will search in all base classes merging the results.
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002304///
2305/// @returns True if any decls were found (but possibly ambiguous)
2306bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
John McCallf4a1b772015-09-09 23:04:17 +00002307 // The access-control rules we use here are essentially the rules for
2308 // doing a lookup in Class that just magically skipped the direct
2309 // members of Class itself. That is, the naming class is Class, and the
2310 // access includes the access of the base.
Nikola Smiljanic67860242014-09-26 00:28:20 +00002311 for (const auto &BaseSpec : Class->bases()) {
2312 CXXRecordDecl *RD = cast<CXXRecordDecl>(
2313 BaseSpec.getType()->castAs<RecordType>()->getDecl());
2314 LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
2315 Result.setBaseObjectType(Context.getRecordType(Class));
2316 LookupQualifiedName(Result, RD);
John McCallf4a1b772015-09-09 23:04:17 +00002317
2318 // Copy the lookup results into the target, merging the base's access into
2319 // the path access.
2320 for (auto I = Result.begin(), E = Result.end(); I != E; ++I) {
2321 R.addDecl(I.getDecl(),
2322 CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(),
2323 I.getAccess()));
2324 }
2325
2326 Result.suppressDiagnostics();
Nikola Smiljanic67860242014-09-26 00:28:20 +00002327 }
2328
2329 R.resolveKind();
John McCallf4a1b772015-09-09 23:04:17 +00002330 R.setNamingClass(Class);
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002331
2332 return !R.empty();
Nikola Smiljanic67860242014-09-26 00:28:20 +00002333}
Douglas Gregor889ceb72009-02-03 19:21:40 +00002334
James Dennett41725122012-06-22 10:16:05 +00002335/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002336/// from name lookup.
2337///
James Dennett41725122012-06-22 10:16:05 +00002338/// \param Result The result of the ambiguous lookup to be diagnosed.
Serge Pavlov99292092013-08-29 07:23:24 +00002339void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002340 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
2341
John McCall27b18f82009-11-17 02:14:36 +00002342 DeclarationName Name = Result.getLookupName();
2343 SourceLocation NameLoc = Result.getNameLoc();
2344 SourceRange LookupRange = Result.getContextRange();
2345
John McCall6538c932009-10-10 05:48:19 +00002346 switch (Result.getAmbiguityKind()) {
2347 case LookupResult::AmbiguousBaseSubobjects: {
2348 CXXBasePaths *Paths = Result.getBasePaths();
2349 QualType SubobjectType = Paths->front().back().Base->getType();
2350 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
2351 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
2352 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002353
David Blaikieff7d47a2012-12-19 00:45:41 +00002354 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6538c932009-10-10 05:48:19 +00002355 while (isa<CXXMethodDecl>(*Found) &&
2356 cast<CXXMethodDecl>(*Found)->isStatic())
2357 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002358
John McCall6538c932009-10-10 05:48:19 +00002359 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
Serge Pavlov99292092013-08-29 07:23:24 +00002360 break;
John McCall6538c932009-10-10 05:48:19 +00002361 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00002362
John McCall6538c932009-10-10 05:48:19 +00002363 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00002364 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
2365 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002366
John McCall6538c932009-10-10 05:48:19 +00002367 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002368 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00002369 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
2370 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002371 Path != PathEnd; ++Path) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002372 Decl *D = Path->Decls.front();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002373 if (DeclsPrinted.insert(D).second)
2374 Diag(D->getLocation(), diag::note_ambiguous_member_found);
2375 }
Serge Pavlov99292092013-08-29 07:23:24 +00002376 break;
Douglas Gregor1c846b02009-01-16 00:38:09 +00002377 }
2378
John McCall6538c932009-10-10 05:48:19 +00002379 case LookupResult::AmbiguousTagHiding: {
2380 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00002381
Nick Lewycky4b81fc872015-10-18 20:32:12 +00002382 llvm::SmallPtrSet<NamedDecl*, 8> TagDecls;
John McCall6538c932009-10-10 05:48:19 +00002383
Aaron Ballman1e606f42014-07-15 22:03:49 +00002384 for (auto *D : Result)
2385 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
John McCall6538c932009-10-10 05:48:19 +00002386 TagDecls.insert(TD);
2387 Diag(TD->getLocation(), diag::note_hidden_tag);
2388 }
2389
Aaron Ballman1e606f42014-07-15 22:03:49 +00002390 for (auto *D : Result)
2391 if (!isa<TagDecl>(D))
2392 Diag(D->getLocation(), diag::note_hiding_object);
John McCall6538c932009-10-10 05:48:19 +00002393
2394 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00002395 LookupResult::Filter F = Result.makeFilter();
2396 while (F.hasNext()) {
2397 if (TagDecls.count(F.next()))
2398 F.erase();
2399 }
2400 F.done();
Serge Pavlov99292092013-08-29 07:23:24 +00002401 break;
John McCall6538c932009-10-10 05:48:19 +00002402 }
2403
2404 case LookupResult::AmbiguousReference: {
2405 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002406
Aaron Ballman1e606f42014-07-15 22:03:49 +00002407 for (auto *D : Result)
2408 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
Serge Pavlov99292092013-08-29 07:23:24 +00002409 break;
John McCall6538c932009-10-10 05:48:19 +00002410 }
Serge Pavlov99292092013-08-29 07:23:24 +00002411 }
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002412}
Douglas Gregore254f902009-02-04 00:32:51 +00002413
John McCallf24d7bb2010-05-28 18:45:08 +00002414namespace {
2415 struct AssociatedLookup {
John McCall7d8b0412012-08-24 20:38:34 +00002416 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallf24d7bb2010-05-28 18:45:08 +00002417 Sema::AssociatedNamespaceSet &Namespaces,
2418 Sema::AssociatedClassSet &Classes)
John McCall7d8b0412012-08-24 20:38:34 +00002419 : S(S), Namespaces(Namespaces), Classes(Classes),
2420 InstantiationLoc(InstantiationLoc) {
John McCallf24d7bb2010-05-28 18:45:08 +00002421 }
2422
2423 Sema &S;
2424 Sema::AssociatedNamespaceSet &Namespaces;
2425 Sema::AssociatedClassSet &Classes;
John McCall7d8b0412012-08-24 20:38:34 +00002426 SourceLocation InstantiationLoc;
John McCallf24d7bb2010-05-28 18:45:08 +00002427 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002428} // end anonymous namespace
John McCallf24d7bb2010-05-28 18:45:08 +00002429
Mike Stump11289f42009-09-09 15:08:12 +00002430static void
John McCallf24d7bb2010-05-28 18:45:08 +00002431addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00002432
Douglas Gregor8b895222010-04-30 07:08:38 +00002433static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
2434 DeclContext *Ctx) {
2435 // Add the associated namespace for this class.
2436
2437 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
2438 // be a locally scoped record.
2439
Sebastian Redlbd595762010-08-31 20:53:31 +00002440 // We skip out of inline namespaces. The innermost non-inline namespace
2441 // contains all names of all its nested inline namespaces anyway, so we can
2442 // replace the entire inline namespace tree with its root.
2443 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
2444 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00002445 Ctx = Ctx->getParent();
2446
John McCallc7e8e792009-08-07 22:18:02 +00002447 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00002448 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00002449}
Douglas Gregor197e5f72009-07-08 07:51:57 +00002450
Mike Stump11289f42009-09-09 15:08:12 +00002451// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00002452// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00002453static void
John McCallf24d7bb2010-05-28 18:45:08 +00002454addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2455 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002456 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00002457 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00002458 switch (Arg.getKind()) {
2459 case TemplateArgument::Null:
2460 break;
Mike Stump11289f42009-09-09 15:08:12 +00002461
Douglas Gregor197e5f72009-07-08 07:51:57 +00002462 case TemplateArgument::Type:
2463 // [...] the namespaces and classes associated with the types of the
2464 // template arguments provided for template type parameters (excluding
2465 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00002466 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00002467 break;
Mike Stump11289f42009-09-09 15:08:12 +00002468
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002469 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002470 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00002471 // [...] the namespaces in which any template template arguments are
2472 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00002473 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002474 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00002475 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002476 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002477 DeclContext *Ctx = ClassTemplate->getDeclContext();
2478 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002479 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002480 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002481 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002482 }
2483 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002484 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002485
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002486 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00002487 case TemplateArgument::Integral:
2488 case TemplateArgument::Expression:
Eli Friedmanb826a002012-09-26 02:36:12 +00002489 case TemplateArgument::NullPtr:
Mike Stump11289f42009-09-09 15:08:12 +00002490 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00002491 // associated namespaces. ]
2492 break;
Mike Stump11289f42009-09-09 15:08:12 +00002493
Douglas Gregor197e5f72009-07-08 07:51:57 +00002494 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00002495 for (const auto &P : Arg.pack_elements())
2496 addAssociatedClassesAndNamespaces(Result, P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002497 break;
2498 }
2499}
2500
Douglas Gregore254f902009-02-04 00:32:51 +00002501// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00002502// argument-dependent lookup with an argument of class type
2503// (C++ [basic.lookup.koenig]p2).
2504static void
John McCallf24d7bb2010-05-28 18:45:08 +00002505addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2506 CXXRecordDecl *Class) {
2507
2508 // Just silently ignore anything whose name is __va_list_tag.
2509 if (Class->getDeclName() == Result.S.VAListTagName)
2510 return;
2511
Douglas Gregore254f902009-02-04 00:32:51 +00002512 // C++ [basic.lookup.koenig]p2:
2513 // [...]
2514 // -- If T is a class type (including unions), its associated
2515 // classes are: the class itself; the class of which it is a
2516 // member, if any; and its direct and indirect base
2517 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00002518 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00002519
2520 // Add the class of which it is a member, if any.
2521 DeclContext *Ctx = Class->getDeclContext();
2522 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002523 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002524 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002525 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002526
Douglas Gregore254f902009-02-04 00:32:51 +00002527 // Add the class itself. If we've already seen this class, we don't
2528 // need to visit base classes.
Richard Smith594461f2014-03-14 22:07:27 +00002529 //
2530 // FIXME: That's not correct, we may have added this class only because it
2531 // was the enclosing class of another class, and in that case we won't have
2532 // added its base classes yet.
Richard Smith6642bb32016-03-24 19:12:22 +00002533 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00002534 return;
2535
Mike Stump11289f42009-09-09 15:08:12 +00002536 // -- If T is a template-id, its associated namespaces and classes are
2537 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002538 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00002539 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00002540 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00002541 // namespaces in which any template template arguments are defined; and
2542 // the classes in which any member templates used as template template
2543 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00002544 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00002545 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00002546 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2547 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2548 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002549 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002550 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002551 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002552
Douglas Gregor197e5f72009-07-08 07:51:57 +00002553 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2554 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00002555 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002556 }
Mike Stump11289f42009-09-09 15:08:12 +00002557
John McCall67da35c2010-02-04 22:26:26 +00002558 // Only recurse into base classes for complete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00002559 if (!Result.S.isCompleteType(Result.InstantiationLoc,
2560 Result.S.Context.getRecordType(Class)))
Richard Smith594461f2014-03-14 22:07:27 +00002561 return;
John McCall67da35c2010-02-04 22:26:26 +00002562
Douglas Gregore254f902009-02-04 00:32:51 +00002563 // Add direct and indirect base classes along with their associated
2564 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002565 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00002566 Bases.push_back(Class);
2567 while (!Bases.empty()) {
2568 // Pop this class off the stack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002569 Class = Bases.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002570
2571 // Visit the base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +00002572 for (const auto &Base : Class->bases()) {
2573 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00002574 // In dependent contexts, we do ADL twice, and the first time around,
2575 // the base type might be a dependent TemplateSpecializationType, or a
2576 // TemplateTypeParmType. If that happens, simply ignore it.
2577 // FIXME: If we want to support export, we probably need to add the
2578 // namespace of the template in a TemplateSpecializationType, or even
2579 // the classes and namespaces of known non-dependent arguments.
2580 if (!BaseType)
2581 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002582 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6642bb32016-03-24 19:12:22 +00002583 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00002584 // Find the associated namespace for this base class.
2585 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00002586 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00002587
2588 // Make sure we visit the bases of this base class.
2589 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2590 Bases.push_back(BaseDecl);
2591 }
2592 }
2593 }
2594}
2595
2596// \brief Add the associated classes and namespaces for
2597// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00002598// (C++ [basic.lookup.koenig]p2).
2599static void
John McCallf24d7bb2010-05-28 18:45:08 +00002600addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00002601 // C++ [basic.lookup.koenig]p2:
2602 //
2603 // For each argument type T in the function call, there is a set
2604 // of zero or more associated namespaces and a set of zero or more
2605 // associated classes to be considered. The sets of namespaces and
2606 // classes is determined entirely by the types of the function
2607 // arguments (and the namespace of any template template
2608 // argument). Typedef names and using-declarations used to specify
2609 // the types do not contribute to this set. The sets of namespaces
2610 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00002611
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002612 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00002613 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2614
Douglas Gregore254f902009-02-04 00:32:51 +00002615 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00002616 switch (T->getTypeClass()) {
2617
2618#define TYPE(Class, Base)
2619#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2620#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2621#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2622#define ABSTRACT_TYPE(Class, Base)
2623#include "clang/AST/TypeNodes.def"
2624 // T is canonical. We can also ignore dependent types because
2625 // we don't need to do ADL at the definition point, but if we
2626 // wanted to implement template export (or if we find some other
2627 // use for associated classes and namespaces...) this would be
2628 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00002629 break;
Douglas Gregore254f902009-02-04 00:32:51 +00002630
John McCall0af3d3b2010-05-28 06:08:54 +00002631 // -- If T is a pointer to U or an array of U, its associated
2632 // namespaces and classes are those associated with U.
2633 case Type::Pointer:
2634 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2635 continue;
2636 case Type::ConstantArray:
2637 case Type::IncompleteArray:
2638 case Type::VariableArray:
2639 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2640 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002641
John McCall0af3d3b2010-05-28 06:08:54 +00002642 // -- If T is a fundamental type, its associated sets of
2643 // namespaces and classes are both empty.
2644 case Type::Builtin:
2645 break;
2646
2647 // -- If T is a class type (including unions), its associated
2648 // classes are: the class itself; the class of which it is a
2649 // member, if any; and its direct and indirect base
2650 // classes. Its associated namespaces are the namespaces in
2651 // which its associated classes are defined.
2652 case Type::Record: {
Richard Smith82b8d4e2015-12-18 22:19:11 +00002653 CXXRecordDecl *Class =
2654 cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002655 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00002656 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00002657 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00002658
John McCall0af3d3b2010-05-28 06:08:54 +00002659 // -- If T is an enumeration type, its associated namespace is
2660 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002661 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00002662 // it has no associated class.
2663 case Type::Enum: {
2664 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002665
John McCall0af3d3b2010-05-28 06:08:54 +00002666 DeclContext *Ctx = Enum->getDeclContext();
2667 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002668 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002669
John McCall0af3d3b2010-05-28 06:08:54 +00002670 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002671 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00002672
John McCall0af3d3b2010-05-28 06:08:54 +00002673 break;
2674 }
2675
2676 // -- If T is a function type, its associated namespaces and
2677 // classes are those associated with the function parameter
2678 // types and those associated with the return type.
2679 case Type::FunctionProto: {
2680 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002681 for (const auto &Arg : Proto->param_types())
2682 Queue.push_back(Arg.getTypePtr());
John McCall0af3d3b2010-05-28 06:08:54 +00002683 // fallthrough
Galina Kistanova33399112017-06-03 06:35:06 +00002684 LLVM_FALLTHROUGH;
John McCall0af3d3b2010-05-28 06:08:54 +00002685 }
2686 case Type::FunctionNoProto: {
2687 const FunctionType *FnType = cast<FunctionType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00002688 T = FnType->getReturnType().getTypePtr();
John McCall0af3d3b2010-05-28 06:08:54 +00002689 continue;
2690 }
2691
2692 // -- If T is a pointer to a member function of a class X, its
2693 // associated namespaces and classes are those associated
2694 // with the function parameter types and return type,
2695 // together with those associated with X.
2696 //
2697 // -- If T is a pointer to a data member of class X, its
2698 // associated namespaces and classes are those associated
2699 // with the member type together with those associated with
2700 // X.
2701 case Type::MemberPointer: {
2702 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2703
2704 // Queue up the class type into which this points.
2705 Queue.push_back(MemberPtr->getClass());
2706
2707 // And directly continue with the pointee type.
2708 T = MemberPtr->getPointeeType().getTypePtr();
2709 continue;
2710 }
2711
2712 // As an extension, treat this like a normal pointer.
2713 case Type::BlockPointer:
2714 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2715 continue;
2716
2717 // References aren't covered by the standard, but that's such an
2718 // obvious defect that we cover them anyway.
2719 case Type::LValueReference:
2720 case Type::RValueReference:
2721 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2722 continue;
2723
2724 // These are fundamental types.
2725 case Type::Vector:
2726 case Type::ExtVector:
2727 case Type::Complex:
2728 break;
2729
Richard Smith27d807c2013-04-30 13:56:41 +00002730 // Non-deduced auto types only get here for error cases.
2731 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00002732 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00002733 break;
2734
Douglas Gregor8e936662011-04-12 01:02:45 +00002735 // If T is an Objective-C object or interface type, or a pointer to an
2736 // object or interface type, the associated namespace is the global
2737 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002738 case Type::ObjCObject:
2739 case Type::ObjCInterface:
2740 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002741 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002742 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002743
2744 // Atomic types are just wrappers; use the associations of the
2745 // contained type.
2746 case Type::Atomic:
2747 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2748 continue;
Xiuli Pan9c14e282016-01-09 12:53:17 +00002749 case Type::Pipe:
2750 T = cast<PipeType>(T)->getElementType().getTypePtr();
2751 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002752 }
2753
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002754 if (Queue.empty())
2755 break;
2756 T = Queue.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002757 }
Douglas Gregore254f902009-02-04 00:32:51 +00002758}
2759
2760/// \brief Find the associated classes and namespaces for
2761/// argument-dependent lookup for a call with the given set of
2762/// arguments.
2763///
2764/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002765/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002766/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00002767void Sema::FindAssociatedClassesAndNamespaces(
2768 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2769 AssociatedNamespaceSet &AssociatedNamespaces,
2770 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002771 AssociatedNamespaces.clear();
2772 AssociatedClasses.clear();
2773
John McCall7d8b0412012-08-24 20:38:34 +00002774 AssociatedLookup Result(*this, InstantiationLoc,
2775 AssociatedNamespaces, AssociatedClasses);
John McCallf24d7bb2010-05-28 18:45:08 +00002776
Douglas Gregore254f902009-02-04 00:32:51 +00002777 // C++ [basic.lookup.koenig]p2:
2778 // For each argument type T in the function call, there is a set
2779 // of zero or more associated namespaces and a set of zero or more
2780 // associated classes to be considered. The sets of namespaces and
2781 // classes is determined entirely by the types of the function
2782 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002783 // argument).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002784 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregore254f902009-02-04 00:32:51 +00002785 Expr *Arg = Args[ArgIdx];
2786
2787 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002788 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002789 continue;
2790 }
2791
2792 // [...] In addition, if the argument is the name or address of a
2793 // set of overloaded functions and/or function templates, its
2794 // associated classes and namespaces are the union of those
2795 // associated with each of the members of the set: the namespace
2796 // in which the function or function template is defined and the
2797 // classes and namespaces associated with its (non-dependent)
2798 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002799 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002800 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002801 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002802 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002803
John McCallf24d7bb2010-05-28 18:45:08 +00002804 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2805 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002806
Aaron Ballman1e606f42014-07-15 22:03:49 +00002807 for (const auto *D : ULE->decls()) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002808 // Look through any using declarations to find the underlying function.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002809 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
Douglas Gregore254f902009-02-04 00:32:51 +00002810
2811 // Add the classes and namespaces associated with the parameter
2812 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002813 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002814 }
2815 }
2816}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002817
John McCall5cebab12009-11-18 07:57:50 +00002818NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002819 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002820 LookupNameKind NameKind,
2821 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002822 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002823 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002824 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002825}
2826
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002827/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002828ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002829 SourceLocation IdLoc,
2830 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002831 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002832 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002833 return cast_or_null<ObjCProtocolDecl>(D);
2834}
2835
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002836void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002837 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002838 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002839 // C++ [over.match.oper]p3:
2840 // -- The set of non-member candidates is the result of the
2841 // unqualified lookup of operator@ in the context of the
2842 // expression according to the usual rules for name lookup in
2843 // unqualified function calls (3.4.2) except that all member
Richard Smith100b24a2014-04-17 01:52:14 +00002844 // functions are ignored.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002845 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002846 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2847 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002848
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002849 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
Richard Smith100b24a2014-04-17 01:52:14 +00002850 Functions.append(Operators.begin(), Operators.end());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002851}
2852
Richard Smith8bae1be2017-02-24 02:07:20 +00002853Sema::SpecialMemberOverloadResult Sema::LookupSpecialMember(CXXRecordDecl *RD,
2854 CXXSpecialMember SM,
2855 bool ConstArg,
2856 bool VolatileArg,
2857 bool RValueThis,
2858 bool ConstThis,
2859 bool VolatileThis) {
Richard Smith7d125a12012-11-27 21:20:31 +00002860 assert(CanDeclareSpecialMemberFunction(RD) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002861 "doing special member lookup into record that isn't fully complete");
Richard Smith7d125a12012-11-27 21:20:31 +00002862 RD = RD->getDefinition();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002863 if (RValueThis || ConstThis || VolatileThis)
2864 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2865 "constructors and destructors always have unqualified lvalue this");
2866 if (ConstArg || VolatileArg)
2867 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2868 "parameter-less special members can't have qualified arguments");
2869
Richard Smith171e4b52017-02-15 04:18:23 +00002870 // FIXME: Get the caller to pass in a location for the lookup.
2871 SourceLocation LookupLoc = RD->getLocation();
2872
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002873 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002874 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002875 ID.AddInteger(SM);
2876 ID.AddInteger(ConstArg);
2877 ID.AddInteger(VolatileArg);
2878 ID.AddInteger(RValueThis);
2879 ID.AddInteger(ConstThis);
2880 ID.AddInteger(VolatileThis);
2881
2882 void *InsertPoint;
Richard Smith8bae1be2017-02-24 02:07:20 +00002883 SpecialMemberOverloadResultEntry *Result =
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002884 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2885
2886 // This was already cached
2887 if (Result)
Richard Smith8bae1be2017-02-24 02:07:20 +00002888 return *Result;
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002889
Richard Smith8bae1be2017-02-24 02:07:20 +00002890 Result = BumpAlloc.Allocate<SpecialMemberOverloadResultEntry>();
2891 Result = new (Result) SpecialMemberOverloadResultEntry(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002892 SpecialMemberCache.InsertNode(Result, InsertPoint);
2893
2894 if (SM == CXXDestructor) {
Richard Smith2be35f52012-12-01 02:35:44 +00002895 if (RD->needsImplicitDestructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002896 DeclareImplicitDestructor(RD);
2897 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002898 assert(DD && "record without a destructor");
2899 Result->setMethod(DD);
Richard Smith852265f2012-03-30 20:53:28 +00002900 Result->setKind(DD->isDeleted() ?
2901 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith83c478d2012-04-20 18:46:14 +00002902 SpecialMemberOverloadResult::Success);
Richard Smith8bae1be2017-02-24 02:07:20 +00002903 return *Result;
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002904 }
2905
Alexis Hunteef8ee02011-06-10 03:50:41 +00002906 // Prepare for overload resolution. Here we construct a synthetic argument
2907 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002908 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002909 DeclarationName Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002910 Expr *Arg = nullptr;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002911 unsigned NumArgs;
2912
Richard Smith83c478d2012-04-20 18:46:14 +00002913 QualType ArgType = CanTy;
2914 ExprValueKind VK = VK_LValue;
2915
Alexis Hunteef8ee02011-06-10 03:50:41 +00002916 if (SM == CXXDefaultConstructor) {
2917 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2918 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002919 if (RD->needsImplicitDefaultConstructor())
2920 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002921 } else {
2922 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2923 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smith2be35f52012-12-01 02:35:44 +00002924 if (RD->needsImplicitCopyConstructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002925 DeclareImplicitCopyConstructor(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002926 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002927 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002928 } else {
2929 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smith2be35f52012-12-01 02:35:44 +00002930 if (RD->needsImplicitCopyAssignment())
Alexis Hunt1da39282011-06-24 02:11:39 +00002931 DeclareImplicitCopyAssignment(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002932 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002933 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002934 }
2935
Alexis Hunteef8ee02011-06-10 03:50:41 +00002936 if (ConstArg)
2937 ArgType.addConst();
2938 if (VolatileArg)
2939 ArgType.addVolatile();
2940
2941 // This isn't /really/ specified by the standard, but it's implied
2942 // we should be working from an RValue in the case of move to ensure
2943 // that we prefer to bind to rvalue references, and an LValue in the
2944 // case of copy to ensure we don't bind to rvalue references.
2945 // Possibly an XValue is actually correct in the case of move, but
2946 // there is no semantic difference for class types in this restricted
2947 // case.
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002948 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002949 VK = VK_LValue;
2950 else
2951 VK = VK_RValue;
Richard Smith83c478d2012-04-20 18:46:14 +00002952 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00002953
Richard Smith171e4b52017-02-15 04:18:23 +00002954 OpaqueValueExpr FakeArg(LookupLoc, ArgType, VK);
Richard Smith83c478d2012-04-20 18:46:14 +00002955
2956 if (SM != CXXDefaultConstructor) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002957 NumArgs = 1;
Richard Smith83c478d2012-04-20 18:46:14 +00002958 Arg = &FakeArg;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002959 }
2960
2961 // Create the object argument
2962 QualType ThisTy = CanTy;
2963 if (ConstThis)
2964 ThisTy.addConst();
2965 if (VolatileThis)
2966 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002967 Expr::Classification Classification =
Richard Smith171e4b52017-02-15 04:18:23 +00002968 OpaqueValueExpr(LookupLoc, ThisTy,
Richard Smith83c478d2012-04-20 18:46:14 +00002969 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002970
2971 // Now we perform lookup on the name we computed earlier and do overload
2972 // resolution. Lookup is only performed directly into the class since there
2973 // will always be a (possibly implicit) declaration to shadow any others.
Richard Smith171e4b52017-02-15 04:18:23 +00002974 OverloadCandidateSet OCS(LookupLoc, OverloadCandidateSet::CSK_Normal);
David Blaikieff7d47a2012-12-19 00:45:41 +00002975 DeclContext::lookup_result R = RD->lookup(Name);
Richard Smith8c37ab52015-02-11 01:48:47 +00002976
2977 if (R.empty()) {
2978 // We might have no default constructor because we have a lambda's closure
2979 // type, rather than because there's some other declared constructor.
2980 // Every class has a copy/move constructor, copy/move assignment, and
2981 // destructor.
2982 assert(SM == CXXDefaultConstructor &&
2983 "lookup for a constructor or assignment operator was empty");
2984 Result->setMethod(nullptr);
2985 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Richard Smith8bae1be2017-02-24 02:07:20 +00002986 return *Result;
Richard Smith8c37ab52015-02-11 01:48:47 +00002987 }
Chandler Carruth7deaae72013-08-18 07:20:52 +00002988
2989 // Copy the candidates as our processing of them may load new declarations
2990 // from an external source and invalidate lookup_result.
2991 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2992
Richard Smith5179eb72016-06-28 19:03:57 +00002993 for (NamedDecl *CandDecl : Candidates) {
2994 if (CandDecl->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002995 continue;
2996
Richard Smith5179eb72016-06-28 19:03:57 +00002997 DeclAccessPair Cand = DeclAccessPair::make(CandDecl, AS_public);
2998 auto CtorInfo = getConstructorInfo(Cand);
2999 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand->getUnderlyingDecl())) {
Alexis Hunt080709f2011-06-23 00:26:20 +00003000 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Richard Smith5179eb72016-06-28 19:03:57 +00003001 AddMethodCandidate(M, Cand, RD, ThisTy, Classification,
3002 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3003 else if (CtorInfo)
3004 AddOverloadCandidate(CtorInfo.Constructor, CtorInfo.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003005 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt080709f2011-06-23 00:26:20 +00003006 else
Richard Smith5179eb72016-06-28 19:03:57 +00003007 AddOverloadCandidate(M, Cand, llvm::makeArrayRef(&Arg, NumArgs), OCS,
3008 true);
3009 } else if (FunctionTemplateDecl *Tmpl =
3010 dyn_cast<FunctionTemplateDecl>(Cand->getUnderlyingDecl())) {
3011 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
3012 AddMethodTemplateCandidate(
3013 Tmpl, Cand, RD, nullptr, ThisTy, Classification,
George Burgess IVce6284b2017-01-28 02:19:40 +00003014 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Richard Smith5179eb72016-06-28 19:03:57 +00003015 else if (CtorInfo)
3016 AddTemplateOverloadCandidate(
3017 CtorInfo.ConstructorTmpl, CtorInfo.FoundDecl, nullptr,
3018 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3019 else
3020 AddTemplateOverloadCandidate(
3021 Tmpl, Cand, nullptr, llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00003022 } else {
Richard Smith5179eb72016-06-28 19:03:57 +00003023 assert(isa<UsingDecl>(Cand.getDecl()) &&
3024 "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00003025 }
3026 }
3027
3028 OverloadCandidateSet::iterator Best;
Richard Smith171e4b52017-02-15 04:18:23 +00003029 switch (OCS.BestViableFunction(*this, LookupLoc, Best)) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00003030 case OR_Success:
3031 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith83c478d2012-04-20 18:46:14 +00003032 Result->setKind(SpecialMemberOverloadResult::Success);
Alexis Hunteef8ee02011-06-10 03:50:41 +00003033 break;
3034
3035 case OR_Deleted:
3036 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith852265f2012-03-30 20:53:28 +00003037 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00003038 break;
3039
3040 case OR_Ambiguous:
Craig Topperc3ec1492014-05-26 06:22:03 +00003041 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00003042 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
3043 break;
3044
Alexis Hunteef8ee02011-06-10 03:50:41 +00003045 case OR_No_Viable_Function:
Craig Topperc3ec1492014-05-26 06:22:03 +00003046 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00003047 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00003048 break;
3049 }
3050
Richard Smith8bae1be2017-02-24 02:07:20 +00003051 return *Result;
Alexis Hunteef8ee02011-06-10 03:50:41 +00003052}
3053
3054/// \brief Look up the default constructor for the given class.
3055CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Richard Smith8bae1be2017-02-24 02:07:20 +00003056 SpecialMemberOverloadResult Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00003057 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
3058 false, false);
3059
Richard Smith8bae1be2017-02-24 02:07:20 +00003060 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00003061}
3062
Alexis Hunt491ec602011-06-21 23:42:56 +00003063/// \brief Look up the copying constructor for the given class.
3064CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith83c478d2012-04-20 18:46:14 +00003065 unsigned Quals) {
Alexis Hunt899bd442011-06-10 04:44:37 +00003066 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3067 "non-const, non-volatile qualifiers for copy ctor arg");
Richard Smith8bae1be2017-02-24 02:07:20 +00003068 SpecialMemberOverloadResult Result =
Alexis Hunt899bd442011-06-10 04:44:37 +00003069 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
3070 Quals & Qualifiers::Volatile, false, false, false);
3071
Richard Smith8bae1be2017-02-24 02:07:20 +00003072 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
Alexis Hunt899bd442011-06-10 04:44:37 +00003073}
3074
Sebastian Redl22653ba2011-08-30 19:58:05 +00003075/// \brief Look up the moving constructor for the given class.
Richard Smith1c6461e2012-07-18 03:36:00 +00003076CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
3077 unsigned Quals) {
Richard Smith8bae1be2017-02-24 02:07:20 +00003078 SpecialMemberOverloadResult Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00003079 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
3080 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003081
Richard Smith8bae1be2017-02-24 02:07:20 +00003082 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003083}
3084
Douglas Gregor52b72822010-07-02 23:12:18 +00003085/// \brief Look up the constructors for the given class.
3086DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00003087 // If the implicit constructors have not yet been declared, do so now.
Richard Smith7d125a12012-11-27 21:20:31 +00003088 if (CanDeclareSpecialMemberFunction(Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00003089 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00003090 DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +00003091 if (Class->needsImplicitCopyConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00003092 DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003093 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00003094 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00003095 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003096
Douglas Gregor52b72822010-07-02 23:12:18 +00003097 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
3098 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
3099 return Class->lookup(Name);
3100}
3101
Alexis Hunt491ec602011-06-21 23:42:56 +00003102/// \brief Look up the copying assignment operator for the given class.
3103CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
3104 unsigned Quals, bool RValueThis,
Richard Smith83c478d2012-04-20 18:46:14 +00003105 unsigned ThisQuals) {
Alexis Hunt491ec602011-06-21 23:42:56 +00003106 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3107 "non-const, non-volatile qualifiers for copy assignment arg");
3108 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3109 "non-const, non-volatile qualifiers for copy assignment this");
Richard Smith8bae1be2017-02-24 02:07:20 +00003110 SpecialMemberOverloadResult Result =
Alexis Hunt491ec602011-06-21 23:42:56 +00003111 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
3112 Quals & Qualifiers::Volatile, RValueThis,
3113 ThisQuals & Qualifiers::Const,
3114 ThisQuals & Qualifiers::Volatile);
3115
Richard Smith8bae1be2017-02-24 02:07:20 +00003116 return Result.getMethod();
Alexis Hunt491ec602011-06-21 23:42:56 +00003117}
3118
Sebastian Redl22653ba2011-08-30 19:58:05 +00003119/// \brief Look up the moving assignment operator for the given class.
3120CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith1c6461e2012-07-18 03:36:00 +00003121 unsigned Quals,
Sebastian Redl22653ba2011-08-30 19:58:05 +00003122 bool RValueThis,
3123 unsigned ThisQuals) {
3124 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3125 "non-const, non-volatile qualifiers for copy assignment this");
Richard Smith8bae1be2017-02-24 02:07:20 +00003126 SpecialMemberOverloadResult Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00003127 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
3128 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl22653ba2011-08-30 19:58:05 +00003129 ThisQuals & Qualifiers::Const,
3130 ThisQuals & Qualifiers::Volatile);
3131
Richard Smith8bae1be2017-02-24 02:07:20 +00003132 return Result.getMethod();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003133}
3134
Douglas Gregore71edda2010-07-01 22:47:18 +00003135/// \brief Look for the destructor of the given class.
3136///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00003137/// During semantic analysis, this routine should be used in lieu of
3138/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00003139///
3140/// \returns The destructor for this class.
3141CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00003142 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
3143 false, false, false,
Richard Smith8bae1be2017-02-24 02:07:20 +00003144 false, false).getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00003145}
3146
Richard Smithbcc22fc2012-03-09 08:00:36 +00003147/// LookupLiteralOperator - Determine which literal operator should be used for
3148/// a user-defined literal, per C++11 [lex.ext].
3149///
3150/// Normal overload resolution is not used to select which literal operator to
3151/// call for a user-defined literal. Look up the provided literal operator name,
3152/// and filter the results to the appropriate set for the given argument types.
3153Sema::LiteralOperatorLookupResult
3154Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
3155 ArrayRef<QualType> ArgTys,
Richard Smithb8b41d32013-10-07 19:57:58 +00003156 bool AllowRaw, bool AllowTemplate,
Tim Northover97103382017-08-09 14:56:48 +00003157 bool AllowStringTemplate, bool DiagnoseMissing) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003158 LookupName(R, S);
3159 assert(R.getResultKind() != LookupResult::Ambiguous &&
3160 "literal operator lookup can't be ambiguous");
3161
3162 // Filter the lookup results appropriately.
3163 LookupResult::Filter F = R.makeFilter();
3164
Richard Smithbcc22fc2012-03-09 08:00:36 +00003165 bool FoundRaw = false;
Richard Smithb8b41d32013-10-07 19:57:58 +00003166 bool FoundTemplate = false;
3167 bool FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003168 bool FoundExactMatch = false;
3169
3170 while (F.hasNext()) {
3171 Decl *D = F.next();
3172 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
3173 D = USD->getTargetDecl();
3174
Douglas Gregorc1970572013-04-10 05:18:00 +00003175 // If the declaration we found is invalid, skip it.
3176 if (D->isInvalidDecl()) {
3177 F.erase();
3178 continue;
3179 }
3180
Richard Smithb8b41d32013-10-07 19:57:58 +00003181 bool IsRaw = false;
3182 bool IsTemplate = false;
3183 bool IsStringTemplate = false;
3184 bool IsExactMatch = false;
3185
Richard Smithbcc22fc2012-03-09 08:00:36 +00003186 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3187 if (FD->getNumParams() == 1 &&
3188 FD->getParamDecl(0)->getType()->getAs<PointerType>())
3189 IsRaw = true;
Richard Smith550de452013-01-15 07:12:59 +00003190 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003191 IsExactMatch = true;
3192 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
3193 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
3194 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
3195 IsExactMatch = false;
3196 break;
3197 }
3198 }
3199 }
3200 }
Richard Smithb8b41d32013-10-07 19:57:58 +00003201 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
3202 TemplateParameterList *Params = FD->getTemplateParameters();
3203 if (Params->size() == 1)
3204 IsTemplate = true;
3205 else
3206 IsStringTemplate = true;
3207 }
Richard Smithbcc22fc2012-03-09 08:00:36 +00003208
3209 if (IsExactMatch) {
3210 FoundExactMatch = true;
Richard Smithb8b41d32013-10-07 19:57:58 +00003211 AllowRaw = false;
3212 AllowTemplate = false;
3213 AllowStringTemplate = false;
3214 if (FoundRaw || FoundTemplate || FoundStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003215 // Go through again and remove the raw and template decls we've
3216 // already found.
3217 F.restart();
Richard Smithb8b41d32013-10-07 19:57:58 +00003218 FoundRaw = FoundTemplate = FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003219 }
Richard Smithb8b41d32013-10-07 19:57:58 +00003220 } else if (AllowRaw && IsRaw) {
3221 FoundRaw = true;
3222 } else if (AllowTemplate && IsTemplate) {
3223 FoundTemplate = true;
3224 } else if (AllowStringTemplate && IsStringTemplate) {
3225 FoundStringTemplate = true;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003226 } else {
3227 F.erase();
3228 }
3229 }
3230
3231 F.done();
3232
3233 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
3234 // parameter type, that is used in preference to a raw literal operator
3235 // or literal operator template.
3236 if (FoundExactMatch)
3237 return LOLR_Cooked;
3238
3239 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
3240 // operator template, but not both.
3241 if (FoundRaw && FoundTemplate) {
3242 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
Alp Tokera2794f92014-01-22 07:29:52 +00003243 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
Richard Smithc2bebe92016-05-11 20:37:46 +00003244 NoteOverloadCandidate(*I, (*I)->getUnderlyingDecl()->getAsFunction());
Richard Smithbcc22fc2012-03-09 08:00:36 +00003245 return LOLR_Error;
3246 }
3247
3248 if (FoundRaw)
3249 return LOLR_Raw;
3250
3251 if (FoundTemplate)
3252 return LOLR_Template;
3253
Richard Smithb8b41d32013-10-07 19:57:58 +00003254 if (FoundStringTemplate)
3255 return LOLR_StringTemplate;
3256
Richard Smithbcc22fc2012-03-09 08:00:36 +00003257 // Didn't find anything we could use.
Tim Northover97103382017-08-09 14:56:48 +00003258 if (DiagnoseMissing) {
3259 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
3260 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
3261 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
3262 << (AllowTemplate || AllowStringTemplate);
3263 return LOLR_Error;
3264 }
3265
3266 return LOLR_ErrorNoDiagnostic;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003267}
3268
John McCall8fe68082010-01-26 07:16:45 +00003269void ADLResult::insert(NamedDecl *New) {
3270 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
3271
3272 // If we haven't yet seen a decl for this key, or the last decl
3273 // was exactly this one, we're done.
Craig Topperc3ec1492014-05-26 06:22:03 +00003274 if (Old == nullptr || Old == New) {
John McCall8fe68082010-01-26 07:16:45 +00003275 Old = New;
3276 return;
3277 }
3278
3279 // Otherwise, decide which is a more recent redeclaration.
Alp Tokera2794f92014-01-22 07:29:52 +00003280 FunctionDecl *OldFD = Old->getAsFunction();
3281 FunctionDecl *NewFD = New->getAsFunction();
John McCall8fe68082010-01-26 07:16:45 +00003282
3283 FunctionDecl *Cursor = NewFD;
3284 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00003285 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00003286
3287 // If we got to the end without finding OldFD, OldFD is the newer
3288 // declaration; leave things as they are.
3289 if (!Cursor) return;
3290
3291 // If we do find OldFD, then NewFD is newer.
3292 if (Cursor == OldFD) break;
3293
3294 // Otherwise, keep looking.
3295 }
3296
3297 Old = New;
3298}
3299
Richard Smith100b24a2014-04-17 01:52:14 +00003300void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3301 ArrayRef<Expr *> Args, ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003302 // Find all of the associated namespaces and classes based on the
3303 // arguments we have.
3304 AssociatedNamespaceSet AssociatedNamespaces;
3305 AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00003306 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCallc7e8e792009-08-07 22:18:02 +00003307 AssociatedNamespaces,
3308 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003309
3310 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003311 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3312 // and let Y be the lookup set produced by argument dependent
3313 // lookup (defined as follows). If X contains [...] then Y is
3314 // empty. Otherwise Y is the set of declarations found in the
3315 // namespaces associated with the argument types as described
3316 // below. The set of declarations found by the lookup of the name
3317 // is the union of X and Y.
3318 //
3319 // Here, we compute Y and add its members to the overloaded
3320 // candidate set.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003321 for (auto *NS : AssociatedNamespaces) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003322 // When considering an associated namespace, the lookup is the
3323 // same as the lookup performed when the associated namespace is
3324 // used as a qualifier (3.4.3.2) except that:
3325 //
3326 // -- Any using-directives in the associated namespace are
3327 // ignored.
3328 //
John McCallc7e8e792009-08-07 22:18:02 +00003329 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003330 // associated classes are visible within their respective
3331 // namespaces even if they are not visible during an ordinary
3332 // lookup (11.4).
Aaron Ballman1e606f42014-07-15 22:03:49 +00003333 DeclContext::lookup_result R = NS->lookup(Name);
3334 for (auto *D : R) {
Richard Smith041740f2018-01-06 00:09:23 +00003335 auto *Underlying = D;
3336 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
3337 Underlying = USD->getTargetDecl();
3338
3339 if (!isa<FunctionDecl>(Underlying) &&
3340 !isa<FunctionTemplateDecl>(Underlying))
3341 continue;
3342
3343 if (!isVisible(D)) {
3344 D = findAcceptableDecl(
3345 *this, D, (Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend));
3346 if (!D)
3347 continue;
3348 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
3349 Underlying = USD->getTargetDecl();
3350 }
3351
John McCallaa74a0c2009-08-28 07:59:38 +00003352 // If the only declaration here is an ordinary friend, consider
3353 // it only if it was declared in an associated classes.
Richard Smith541b38b2013-09-20 01:15:31 +00003354 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) {
3355 // If it's neither ordinarily visible nor a friend, we can't find it.
3356 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0)
3357 continue;
3358
Richard Smith64017682013-07-17 23:53:16 +00003359 bool DeclaredInAssociatedClass = false;
3360 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
3361 DeclContext *LexDC = DI->getLexicalDeclContext();
3362 if (isa<CXXRecordDecl>(LexDC) &&
Richard Smith82b8d4e2015-12-18 22:19:11 +00003363 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)) &&
3364 isVisible(cast<NamedDecl>(DI))) {
Richard Smith64017682013-07-17 23:53:16 +00003365 DeclaredInAssociatedClass = true;
3366 break;
3367 }
3368 }
3369 if (!DeclaredInAssociatedClass)
John McCalld1e9d832009-08-11 06:59:38 +00003370 continue;
3371 }
Mike Stump11289f42009-09-09 15:08:12 +00003372
Richard Smith197f68d2017-10-11 01:49:57 +00003373 // FIXME: Preserve D as the FoundDecl.
3374 Result.insert(Underlying);
Douglas Gregor6127ca42009-06-23 20:14:09 +00003375 }
3376 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003377}
Douglas Gregor2d435302009-12-30 17:04:44 +00003378
3379//----------------------------------------------------------------------------
3380// Search for all visible declarations.
3381//----------------------------------------------------------------------------
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00003382VisibleDeclConsumer::~VisibleDeclConsumer() { }
Douglas Gregor2d435302009-12-30 17:04:44 +00003383
Richard Smithe156254d2013-08-20 20:35:18 +00003384bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
3385
Douglas Gregor2d435302009-12-30 17:04:44 +00003386namespace {
3387
3388class ShadowContextRAII;
3389
3390class VisibleDeclsRecord {
3391public:
3392 /// \brief An entry in the shadow map, which is optimized to store a
3393 /// single declaration (the common case) but can also store a list
3394 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00003395 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00003396
3397private:
3398 /// \brief A mapping from declaration names to the declarations that have
3399 /// this name within a particular scope.
3400 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
3401
3402 /// \brief A list of shadow maps, which is used to model name hiding.
3403 std::list<ShadowMap> ShadowMaps;
3404
3405 /// \brief The declaration contexts we have already visited.
3406 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
3407
3408 friend class ShadowContextRAII;
3409
3410public:
3411 /// \brief Determine whether we have already visited this context
3412 /// (and, if not, note that we are going to visit that context now).
3413 bool visitedContext(DeclContext *Ctx) {
David Blaikie82e95a32014-11-19 07:49:47 +00003414 return !VisitedContexts.insert(Ctx).second;
Douglas Gregor2d435302009-12-30 17:04:44 +00003415 }
3416
Douglas Gregor39982192010-08-15 06:18:01 +00003417 bool alreadyVisitedContext(DeclContext *Ctx) {
3418 return VisitedContexts.count(Ctx);
3419 }
3420
Douglas Gregor2d435302009-12-30 17:04:44 +00003421 /// \brief Determine whether the given declaration is hidden in the
3422 /// current scope.
3423 ///
3424 /// \returns the declaration that hides the given declaration, or
3425 /// NULL if no such declaration exists.
3426 NamedDecl *checkHidden(NamedDecl *ND);
3427
3428 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00003429 void add(NamedDecl *ND) {
3430 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
3431 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003432};
3433
3434/// \brief RAII object that records when we've entered a shadow context.
3435class ShadowContextRAII {
3436 VisibleDeclsRecord &Visible;
3437
3438 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
3439
3440public:
3441 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
Benjamin Kramer3204b152015-05-29 19:42:19 +00003442 Visible.ShadowMaps.emplace_back();
Douglas Gregor2d435302009-12-30 17:04:44 +00003443 }
3444
3445 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00003446 Visible.ShadowMaps.pop_back();
3447 }
3448};
3449
3450} // end anonymous namespace
3451
Douglas Gregor2d435302009-12-30 17:04:44 +00003452NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
3453 unsigned IDNS = ND->getIdentifierNamespace();
3454 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
3455 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3456 SM != SMEnd; ++SM) {
3457 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
3458 if (Pos == SM->end())
3459 continue;
3460
Aaron Ballman1e606f42014-07-15 22:03:49 +00003461 for (auto *D : Pos->second) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003462 // A tag declaration does not hide a non-tag declaration.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003463 if (D->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003464 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00003465 Decl::IDNS_ObjCProtocol)))
3466 continue;
3467
3468 // Protocols are in distinct namespaces from everything else.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003469 if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor2d435302009-12-30 17:04:44 +00003470 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Aaron Ballman1e606f42014-07-15 22:03:49 +00003471 D->getIdentifierNamespace() != IDNS)
Douglas Gregor2d435302009-12-30 17:04:44 +00003472 continue;
3473
Douglas Gregor09bbc652010-01-14 15:47:35 +00003474 // Functions and function templates in the same scope overload
3475 // rather than hide. FIXME: Look for hiding based on function
3476 // signatures!
Aaron Ballman1e606f42014-07-15 22:03:49 +00003477 if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Alp Tokera2794f92014-01-22 07:29:52 +00003478 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00003479 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00003480 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003481
Alex Lorenze7e8f802017-01-23 17:23:23 +00003482 // A shadow declaration that's created by a resolved using declaration
3483 // is not hidden by the same using declaration.
3484 if (isa<UsingShadowDecl>(ND) && isa<UsingDecl>(D) &&
3485 cast<UsingShadowDecl>(ND)->getUsingDecl() == D)
3486 continue;
3487
Douglas Gregor2d435302009-12-30 17:04:44 +00003488 // We've found a declaration that hides this one.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003489 return D;
Douglas Gregor2d435302009-12-30 17:04:44 +00003490 }
3491 }
3492
Craig Topperc3ec1492014-05-26 06:22:03 +00003493 return nullptr;
Douglas Gregor2d435302009-12-30 17:04:44 +00003494}
3495
3496static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
3497 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003498 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00003499 VisibleDeclConsumer &Consumer,
Alex Lorenze6afa392017-05-11 13:48:57 +00003500 VisibleDeclsRecord &Visited,
Sam McCallbb2cf632018-01-12 14:51:47 +00003501 bool IncludeDependentBases,
3502 bool LoadExternal) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00003503 if (!Ctx)
3504 return;
3505
Douglas Gregor2d435302009-12-30 17:04:44 +00003506 // Make sure we don't visit the same context twice.
3507 if (Visited.visitedContext(Ctx->getPrimaryContext()))
3508 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003509
Haojian Wu10d95c52018-01-17 14:29:25 +00003510 Consumer.EnteredContext(Ctx);
3511
Richard Smith9e2341d2015-03-23 03:25:59 +00003512 // Outside C++, lookup results for the TU live on identifiers.
3513 if (isa<TranslationUnitDecl>(Ctx) &&
3514 !Result.getSema().getLangOpts().CPlusPlus) {
3515 auto &S = Result.getSema();
3516 auto &Idents = S.Context.Idents;
3517
3518 // Ensure all external identifiers are in the identifier table.
Sam McCallbb2cf632018-01-12 14:51:47 +00003519 if (LoadExternal)
3520 if (IdentifierInfoLookup *External = Idents.getExternalIdentifierLookup()) {
3521 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
3522 for (StringRef Name = Iter->Next(); !Name.empty(); Name = Iter->Next())
3523 Idents.get(Name);
3524 }
Richard Smith9e2341d2015-03-23 03:25:59 +00003525
3526 // Walk all lookup results in the TU for each identifier.
3527 for (const auto &Ident : Idents) {
3528 for (auto I = S.IdResolver.begin(Ident.getValue()),
3529 E = S.IdResolver.end();
3530 I != E; ++I) {
3531 if (S.IdResolver.isDeclInScope(*I, Ctx)) {
3532 if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
3533 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3534 Visited.add(ND);
3535 }
3536 }
3537 }
3538 }
3539
3540 return;
3541 }
3542
Douglas Gregor7454c562010-07-02 20:37:36 +00003543 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3544 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3545
Sam McCallabdcc612018-01-24 17:50:20 +00003546 // We sometimes skip loading namespace-level results (they tend to be huge).
3547 bool Load = LoadExternal ||
3548 !(isa<TranslationUnitDecl>(Ctx) || isa<NamespaceDecl>(Ctx));
Douglas Gregor2d435302009-12-30 17:04:44 +00003549 // Enumerate all of the results in this context.
Sam McCallbb2cf632018-01-12 14:51:47 +00003550 for (DeclContextLookupResult R :
Sam McCallabdcc612018-01-24 17:50:20 +00003551 Load ? Ctx->lookups()
3552 : Ctx->noload_lookups(/*PreserveInternalState=*/false)) {
Richard Smith9e2341d2015-03-23 03:25:59 +00003553 for (auto *D : R) {
3554 if (auto *ND = Result.getAcceptableDecl(D)) {
3555 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3556 Visited.add(ND);
Douglas Gregora3b23b02010-12-09 21:44:02 +00003557 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003558 }
3559 }
3560
3561 // Traverse using directives for qualified name lookup.
3562 if (QualifiedNameLookup) {
3563 ShadowContextRAII Shadow(Visited);
Aaron Ballman804a7fb2014-03-17 17:14:12 +00003564 for (auto I : Ctx->using_directives()) {
Richard Smithb920f852017-10-11 01:19:11 +00003565 if (!Result.getSema().isVisible(I))
3566 continue;
Aaron Ballman63ab7602014-03-07 13:44:44 +00003567 LookupVisibleDecls(I->getNominatedNamespace(), Result,
Alex Lorenze6afa392017-05-11 13:48:57 +00003568 QualifiedNameLookup, InBaseClass, Consumer, Visited,
Sam McCallbb2cf632018-01-12 14:51:47 +00003569 IncludeDependentBases, LoadExternal);
Douglas Gregor2d435302009-12-30 17:04:44 +00003570 }
3571 }
3572
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003573 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00003574 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00003575 if (!Record->hasDefinition())
3576 return;
3577
Aaron Ballman574705e2014-03-13 15:41:46 +00003578 for (const auto &B : Record->bases()) {
3579 QualType BaseType = B.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003580
Alex Lorenze6afa392017-05-11 13:48:57 +00003581 RecordDecl *RD;
3582 if (BaseType->isDependentType()) {
3583 if (!IncludeDependentBases) {
3584 // Don't look into dependent bases, because name lookup can't look
3585 // there anyway.
3586 continue;
3587 }
3588 const auto *TST = BaseType->getAs<TemplateSpecializationType>();
3589 if (!TST)
3590 continue;
3591 TemplateName TN = TST->getTemplateName();
3592 const auto *TD =
3593 dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl());
3594 if (!TD)
3595 continue;
3596 RD = TD->getTemplatedDecl();
3597 } else {
3598 const auto *Record = BaseType->getAs<RecordType>();
3599 if (!Record)
3600 continue;
3601 RD = Record->getDecl();
3602 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003603
Douglas Gregor2d435302009-12-30 17:04:44 +00003604 // FIXME: It would be nice to be able to determine whether referencing
3605 // a particular member would be ambiguous. For example, given
3606 //
3607 // struct A { int member; };
3608 // struct B { int member; };
3609 // struct C : A, B { };
3610 //
3611 // void f(C *c) { c->### }
3612 //
3613 // accessing 'member' would result in an ambiguity. However, we
3614 // could be smart enough to qualify the member with the base
3615 // class, e.g.,
3616 //
3617 // c->B::member
3618 //
3619 // or
3620 //
3621 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003622
Douglas Gregor2d435302009-12-30 17:04:44 +00003623 // Find results in this base class (and its bases).
3624 ShadowContextRAII Shadow(Visited);
Alex Lorenze6afa392017-05-11 13:48:57 +00003625 LookupVisibleDecls(RD, Result, QualifiedNameLookup, true, Consumer,
Sam McCallbb2cf632018-01-12 14:51:47 +00003626 Visited, IncludeDependentBases, LoadExternal);
Douglas Gregor2d435302009-12-30 17:04:44 +00003627 }
3628 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003629
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003630 // Traverse the contexts of Objective-C classes.
3631 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3632 // Traverse categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003633 for (auto *Cat : IFace->visible_categories()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003634 ShadowContextRAII Shadow(Visited);
Sam McCallbb2cf632018-01-12 14:51:47 +00003635 LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false, Consumer,
3636 Visited, IncludeDependentBases, LoadExternal);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003637 }
3638
3639 // Traverse protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003640 for (auto *I : IFace->all_referenced_protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003641 ShadowContextRAII Shadow(Visited);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003642 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Sam McCallbb2cf632018-01-12 14:51:47 +00003643 Visited, IncludeDependentBases, LoadExternal);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003644 }
3645
3646 // Traverse the superclass.
3647 if (IFace->getSuperClass()) {
3648 ShadowContextRAII Shadow(Visited);
3649 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Sam McCallbb2cf632018-01-12 14:51:47 +00003650 true, Consumer, Visited, IncludeDependentBases,
3651 LoadExternal);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003652 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003653
Douglas Gregor0b59e802010-04-19 18:02:19 +00003654 // If there is an implementation, traverse it. We do this to find
3655 // synthesized ivars.
3656 if (IFace->getImplementation()) {
3657 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003658 LookupVisibleDecls(IFace->getImplementation(), Result,
Sam McCallbb2cf632018-01-12 14:51:47 +00003659 QualifiedNameLookup, InBaseClass, Consumer, Visited,
3660 IncludeDependentBases, LoadExternal);
Douglas Gregor0b59e802010-04-19 18:02:19 +00003661 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003662 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003663 for (auto *I : Protocol->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003664 ShadowContextRAII Shadow(Visited);
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003665 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Sam McCallbb2cf632018-01-12 14:51:47 +00003666 Visited, IncludeDependentBases, LoadExternal);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003667 }
3668 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003669 for (auto *I : Category->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003670 ShadowContextRAII Shadow(Visited);
Aaron Ballman19a41762014-03-14 12:55:57 +00003671 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Sam McCallbb2cf632018-01-12 14:51:47 +00003672 Visited, IncludeDependentBases, LoadExternal);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003673 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003674
Douglas Gregor0b59e802010-04-19 18:02:19 +00003675 // If there is an implementation, traverse it.
3676 if (Category->getImplementation()) {
3677 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003678 LookupVisibleDecls(Category->getImplementation(), Result,
Sam McCallbb2cf632018-01-12 14:51:47 +00003679 QualifiedNameLookup, true, Consumer, Visited,
3680 IncludeDependentBases, LoadExternal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003681 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003682 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003683}
3684
3685static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3686 UnqualUsingDirectiveSet &UDirs,
3687 VisibleDeclConsumer &Consumer,
Sam McCallbb2cf632018-01-12 14:51:47 +00003688 VisibleDeclsRecord &Visited,
3689 bool LoadExternal) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003690 if (!S)
3691 return;
3692
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003693 if (!S->getEntity() ||
3694 (!S->getParent() &&
Ted Kremenekc37877d2013-10-08 17:08:03 +00003695 !Visited.alreadyVisitedContext(S->getEntity())) ||
3696 (S->getEntity())->isFunctionOrMethod()) {
Richard Smith541b38b2013-09-20 01:15:31 +00003697 FindLocalExternScope FindLocals(Result);
Benjamin Kramer17ba6692017-10-13 22:14:34 +00003698 // Walk through the declarations in this Scope. The consumer might add new
3699 // decls to the scope as part of deserialization, so make a copy first.
3700 SmallVector<Decl *, 8> ScopeDecls(S->decls().begin(), S->decls().end());
3701 for (Decl *D : ScopeDecls) {
Aaron Ballman35c54952014-03-17 16:55:25 +00003702 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Douglas Gregor4a814562011-12-14 16:03:29 +00003703 if ((ND = Result.getAcceptableDecl(ND))) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003704 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003705 Visited.add(ND);
3706 }
3707 }
3708 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003709
Douglas Gregor66230062010-03-15 14:33:29 +00003710 // FIXME: C++ [temp.local]p8
Craig Topperc3ec1492014-05-26 06:22:03 +00003711 DeclContext *Entity = nullptr;
Douglas Gregor4f248632010-01-01 17:44:25 +00003712 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003713 // Look into this scope's declaration context, along with any of its
3714 // parent lookup contexts (e.g., enclosing classes), up to the point
3715 // where we hit the context stored in the next outer scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00003716 Entity = S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00003717 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003718
Douglas Gregorea166062010-03-15 15:26:48 +00003719 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00003720 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003721 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3722 if (Method->isInstanceMethod()) {
3723 // For instance methods, look for ivars in the method's interface.
3724 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3725 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003726 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003727 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Sam McCallbb2cf632018-01-12 14:51:47 +00003728 /*InBaseClass=*/false, Consumer, Visited,
3729 /*IncludeDependentBases=*/false, LoadExternal);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003730 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003731 }
3732
3733 // We've already performed all of the name lookup that we need
3734 // to for Objective-C methods; the next context will be the
3735 // outer scope.
3736 break;
3737 }
3738
Douglas Gregor2d435302009-12-30 17:04:44 +00003739 if (Ctx->isFunctionOrMethod())
3740 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003741
3742 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Sam McCallbb2cf632018-01-12 14:51:47 +00003743 /*InBaseClass=*/false, Consumer, Visited,
3744 /*IncludeDependentBases=*/false, LoadExternal);
Douglas Gregor2d435302009-12-30 17:04:44 +00003745 }
3746 } else if (!S->getParent()) {
3747 // Look into the translation unit scope. We walk through the translation
3748 // unit's declaration context, because the Scope itself won't have all of
3749 // the declarations if we loaded a precompiled header.
3750 // FIXME: We would like the translation unit's Scope object to point to the
3751 // translation unit, so we don't need this special "if" branch. However,
3752 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003753 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00003754 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003755 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00003756 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003757 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Sam McCallbb2cf632018-01-12 14:51:47 +00003758 /*InBaseClass=*/false, Consumer, Visited,
3759 /*IncludeDependentBases=*/false, LoadExternal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003760 }
3761
Douglas Gregor2d435302009-12-30 17:04:44 +00003762 if (Entity) {
3763 // Lookup visible declarations in any namespaces found by using
3764 // directives.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003765 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
3766 LookupVisibleDecls(const_cast<DeclContext *>(UUE.getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003767 Result, /*QualifiedNameLookup=*/false,
Sam McCallbb2cf632018-01-12 14:51:47 +00003768 /*InBaseClass=*/false, Consumer, Visited,
3769 /*IncludeDependentBases=*/false, LoadExternal);
Douglas Gregor2d435302009-12-30 17:04:44 +00003770 }
3771
3772 // Lookup names in the parent scope.
3773 ShadowContextRAII Shadow(Visited);
Sam McCallbb2cf632018-01-12 14:51:47 +00003774 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited,
3775 LoadExternal);
Douglas Gregor2d435302009-12-30 17:04:44 +00003776}
3777
3778void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003779 VisibleDeclConsumer &Consumer,
Sam McCallbb2cf632018-01-12 14:51:47 +00003780 bool IncludeGlobalScope, bool LoadExternal) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003781 // Determine the set of using directives available during
3782 // unqualified name lookup.
3783 Scope *Initial = S;
Richard Smithb920f852017-10-11 01:19:11 +00003784 UnqualUsingDirectiveSet UDirs(*this);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003785 if (getLangOpts().CPlusPlus) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003786 // Find the first namespace or translation-unit scope.
3787 while (S && !isNamespaceOrTranslationUnitScope(S))
3788 S = S->getParent();
3789
3790 UDirs.visitScopeChain(Initial, S);
3791 }
3792 UDirs.done();
3793
3794 // Look for visible declarations.
3795 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003796 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003797 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003798 if (!IncludeGlobalScope)
3799 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003800 ShadowContextRAII Shadow(Visited);
Sam McCallbb2cf632018-01-12 14:51:47 +00003801 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited, LoadExternal);
Douglas Gregor2d435302009-12-30 17:04:44 +00003802}
3803
3804void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003805 VisibleDeclConsumer &Consumer,
Alex Lorenze6afa392017-05-11 13:48:57 +00003806 bool IncludeGlobalScope,
Sam McCallbb2cf632018-01-12 14:51:47 +00003807 bool IncludeDependentBases, bool LoadExternal) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003808 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003809 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003810 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003811 if (!IncludeGlobalScope)
3812 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003813 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003814 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Alex Lorenze6afa392017-05-11 13:48:57 +00003815 /*InBaseClass=*/false, Consumer, Visited,
Sam McCallbb2cf632018-01-12 14:51:47 +00003816 IncludeDependentBases, LoadExternal);
Douglas Gregor2d435302009-12-30 17:04:44 +00003817}
3818
Chris Lattner43e7f312011-02-18 02:08:43 +00003819/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003820/// If GnuLabelLoc is a valid source location, then this is a definition
3821/// of an __label__ label name, otherwise it is a normal label definition
3822/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003823LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003824 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003825 // Do a lookup to see if we have a label with this name already.
Craig Topperc3ec1492014-05-26 06:22:03 +00003826 NamedDecl *Res = nullptr;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003827
3828 if (GnuLabelLoc.isValid()) {
3829 // Local label definitions always shadow existing labels.
3830 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3831 Scope *S = CurScope;
3832 PushOnScopeChains(Res, S, true);
3833 return cast<LabelDecl>(Res);
3834 }
3835
3836 // Not a GNU local label.
3837 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3838 // If we found a label, check to see if it is in the same context as us.
3839 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003840 if (Res && Res->getDeclContext() != CurContext)
Craig Topperc3ec1492014-05-26 06:22:03 +00003841 Res = nullptr;
3842 if (!Res) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003843 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003844 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3845 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003846 assert(S && "Not in a function?");
3847 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003848 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003849 return cast<LabelDecl>(Res);
3850}
3851
3852//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003853// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003854//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003855
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003856static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3857 TypoCorrection &Candidate) {
3858 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3859 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3860}
3861
3862static void LookupPotentialTypoResult(Sema &SemaRef,
3863 LookupResult &Res,
3864 IdentifierInfo *Name,
3865 Scope *S, CXXScopeSpec *SS,
3866 DeclContext *MemberContext,
3867 bool EnteringContext,
3868 bool isObjCIvarLookup,
3869 bool FindHidden);
3870
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003871/// \brief Check whether the declarations found for a typo correction are
Richard Smith3092d722017-06-05 22:29:36 +00003872/// visible. Set the correction's RequiresImport flag to true if none of the
3873/// declarations are visible, false otherwise.
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003874static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003875 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3876
3877 for (/**/; DI != DE; ++DI)
3878 if (!LookupResult::isVisible(SemaRef, *DI))
3879 break;
Richard Smith3092d722017-06-05 22:29:36 +00003880 // No filtering needed if all decls are visible.
3881 if (DI == DE) {
3882 TC.setRequiresImport(false);
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003883 return;
Richard Smith3092d722017-06-05 22:29:36 +00003884 }
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003885
3886 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3887 bool AnyVisibleDecls = !NewDecls.empty();
3888
3889 for (/**/; DI != DE; ++DI) {
Richard Smith041740f2018-01-06 00:09:23 +00003890 if (LookupResult::isVisible(SemaRef, *DI)) {
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003891 if (!AnyVisibleDecls) {
3892 // Found a visible decl, discard all hidden ones.
3893 AnyVisibleDecls = true;
3894 NewDecls.clear();
3895 }
Richard Smith041740f2018-01-06 00:09:23 +00003896 NewDecls.push_back(*DI);
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003897 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
3898 NewDecls.push_back(*DI);
3899 }
3900
3901 if (NewDecls.empty())
3902 TC = TypoCorrection();
3903 else {
3904 TC.setCorrectionDecls(NewDecls);
3905 TC.setRequiresImport(!AnyVisibleDecls);
3906 }
3907}
3908
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003909// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3910// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3911// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3912static void getNestedNameSpecifierIdentifiers(
3913 NestedNameSpecifier *NNS,
3914 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3915 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3916 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3917 else
3918 Identifiers.clear();
3919
3920 const IdentifierInfo *II = nullptr;
3921
3922 switch (NNS->getKind()) {
3923 case NestedNameSpecifier::Identifier:
3924 II = NNS->getAsIdentifier();
3925 break;
3926
3927 case NestedNameSpecifier::Namespace:
3928 if (NNS->getAsNamespace()->isAnonymousNamespace())
3929 return;
3930 II = NNS->getAsNamespace()->getIdentifier();
3931 break;
3932
3933 case NestedNameSpecifier::NamespaceAlias:
3934 II = NNS->getAsNamespaceAlias()->getIdentifier();
3935 break;
3936
3937 case NestedNameSpecifier::TypeSpecWithTemplate:
3938 case NestedNameSpecifier::TypeSpec:
3939 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3940 break;
3941
3942 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00003943 case NestedNameSpecifier::Super:
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003944 return;
3945 }
3946
3947 if (II)
3948 Identifiers.push_back(II);
3949}
3950
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003951void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003952 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003953 // Don't consider hidden names for typo correction.
3954 if (Hiding)
3955 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003956
Douglas Gregor2d435302009-12-30 17:04:44 +00003957 // Only consider entities with identifiers for names, ignoring
3958 // special names (constructors, overloaded operators, selectors,
3959 // etc.).
3960 IdentifierInfo *Name = ND->getIdentifier();
3961 if (!Name)
3962 return;
3963
Richard Smithe156254d2013-08-20 20:35:18 +00003964 // Only consider visible declarations and declarations from modules with
3965 // names that exactly match.
Richard Smith041740f2018-01-06 00:09:23 +00003966 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo)
Richard Smithe156254d2013-08-20 20:35:18 +00003967 return;
3968
Douglas Gregor57756ea2010-10-14 22:11:03 +00003969 FoundName(Name->getName());
3970}
3971
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003972void TypoCorrectionConsumer::FoundName(StringRef Name) {
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003973 // Compute the edit distance between the typo and the name of this
3974 // entity, and add the identifier to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003975 addName(Name, nullptr);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003976}
3977
3978void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3979 // Compute the edit distance between the typo and this keyword,
3980 // and add the keyword to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003981 addName(Keyword, nullptr, nullptr, true);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003982}
3983
3984void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
3985 NestedNameSpecifier *NNS, bool isKeyword) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003986 // Use a simple length-based heuristic to determine the minimum possible
3987 // edit distance. If the minimum isn't good enough, bail out early.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003988 StringRef TypoStr = Typo->getName();
3989 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
3990 if (MinED && TypoStr.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00003991 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003992
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003993 // Compute an upper bound on the allowable edit distance, so that the
3994 // edit-distance algorithm can short-circuit.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003995 unsigned UpperBound = (TypoStr.size() + 2) / 3 + 1;
3996 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003997 if (ED >= UpperBound) return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003998
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003999 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004000 if (isKeyword) TC.makeKeyword();
Kaelyn Takata0a313022014-11-20 22:06:26 +00004001 TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004002 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004003}
4004
Kaelyn Takatad2287c32014-10-27 18:07:13 +00004005static const unsigned MaxTypoDistanceResultSets = 5;
4006
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004007void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004008 StringRef TypoStr = Typo->getName();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004009 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004010
4011 // For very short typos, ignore potential corrections that have a different
4012 // base identifier from the typo or which have a normalized edit distance
4013 // longer than the typo itself.
4014 if (TypoStr.size() < 3 &&
4015 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
4016 return;
4017
4018 // If the correction is resolved but is not viable, ignore it.
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00004019 if (Correction.isResolved()) {
4020 checkCorrectionVisibility(SemaRef, Correction);
4021 if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
4022 return;
4023 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004024
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004025 TypoResultList &CList =
4026 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00004027
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004028 if (!CList.empty() && !CList.back().isResolved())
4029 CList.pop_back();
4030 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
4031 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
4032 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
4033 RI != RIEnd; ++RI) {
4034 // If the Correction refers to a decl already in the result list,
4035 // replace the existing result if the string representation of Correction
4036 // comes before the current result alphabetically, then stop as there is
4037 // nothing more to be done to add Correction to the candidate set.
4038 if (RI->getCorrectionDecl() == NewND) {
4039 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
4040 *RI = Correction;
4041 return;
4042 }
4043 }
4044 }
4045 if (CList.empty() || Correction.isResolved())
4046 CList.push_back(Correction);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004047
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00004048 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004049 CorrectionResults.erase(std::prev(CorrectionResults.end()));
4050}
4051
4052void TypoCorrectionConsumer::addNamespaces(
4053 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
4054 SearchNamespaces = true;
4055
4056 for (auto KNPair : KnownNamespaces)
4057 Namespaces.addNameSpecifier(KNPair.first);
4058
4059 bool SSIsTemplate = false;
4060 if (NestedNameSpecifier *NNS =
4061 (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
4062 if (const Type *T = NNS->getAsType())
4063 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
4064 }
Richard Smith2a40fb72015-11-18 01:19:02 +00004065 // Do not transform this into an iterator-based loop. The loop body can
4066 // trigger the creation of further types (through lazy deserialization) and
4067 // invalide iterators into this list.
4068 auto &Types = SemaRef.getASTContext().getTypes();
4069 for (unsigned I = 0; I != Types.size(); ++I) {
4070 const auto *TI = Types[I];
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004071 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
4072 CD = CD->getCanonicalDecl();
4073 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
4074 !CD->isUnion() && CD->getIdentifier() &&
4075 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
4076 (CD->isBeingDefined() || CD->isCompleteDefinition()))
4077 Namespaces.addNameSpecifier(CD);
4078 }
4079 }
4080}
4081
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00004082const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
4083 if (++CurrentTCIndex < ValidatedCorrections.size())
4084 return ValidatedCorrections[CurrentTCIndex];
4085
4086 CurrentTCIndex = ValidatedCorrections.size();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004087 while (!CorrectionResults.empty()) {
4088 auto DI = CorrectionResults.begin();
4089 if (DI->second.empty()) {
4090 CorrectionResults.erase(DI);
4091 continue;
4092 }
4093
4094 auto RI = DI->second.begin();
4095 if (RI->second.empty()) {
4096 DI->second.erase(RI);
4097 performQualifiedLookups();
4098 continue;
4099 }
4100
4101 TypoCorrection TC = RI->second.pop_back_val();
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00004102 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00004103 ValidatedCorrections.push_back(TC);
4104 return ValidatedCorrections[CurrentTCIndex];
4105 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004106 }
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00004107 return ValidatedCorrections[0]; // The empty correction.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004108}
4109
4110bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
4111 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
4112 DeclContext *TempMemberContext = MemberContext;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004113 CXXScopeSpec *TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004114retry_lookup:
4115 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
4116 EnteringContext,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004117 CorrectionValidator->IsObjCIvarLookup,
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004118 Name == Typo && !Candidate.WillReplaceSpecifier());
4119 switch (Result.getResultKind()) {
4120 case LookupResult::NotFound:
4121 case LookupResult::NotFoundInCurrentInstantiation:
4122 case LookupResult::FoundUnresolvedValue:
4123 if (TempSS) {
4124 // Immediately retry the lookup without the given CXXScopeSpec
4125 TempSS = nullptr;
4126 Candidate.WillReplaceSpecifier(true);
4127 goto retry_lookup;
4128 }
4129 if (TempMemberContext) {
4130 if (SS && !TempSS)
Kaelyn Takata6c759512014-10-27 18:07:37 +00004131 TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004132 TempMemberContext = nullptr;
4133 goto retry_lookup;
4134 }
4135 if (SearchNamespaces)
4136 QualifiedResults.push_back(Candidate);
4137 break;
4138
4139 case LookupResult::Ambiguous:
4140 // We don't deal with ambiguities.
4141 break;
4142
4143 case LookupResult::Found:
4144 case LookupResult::FoundOverloaded:
4145 // Store all of the Decls for overloaded symbols
4146 for (auto *TRD : Result)
4147 Candidate.addCorrectionDecl(TRD);
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00004148 checkCorrectionVisibility(SemaRef, Candidate);
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004149 if (!isCandidateViable(*CorrectionValidator, Candidate)) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004150 if (SearchNamespaces)
4151 QualifiedResults.push_back(Candidate);
4152 break;
4153 }
Kaelyn Takata20deb1d2015-01-28 00:46:09 +00004154 Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004155 return true;
4156 }
4157 return false;
4158}
4159
4160void TypoCorrectionConsumer::performQualifiedLookups() {
4161 unsigned TypoLen = Typo->getName().size();
Benjamin Kramer2e018ef2016-05-27 13:36:58 +00004162 for (const TypoCorrection &QR : QualifiedResults) {
4163 for (const auto &NSI : Namespaces) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004164 DeclContext *Ctx = NSI.DeclCtx;
4165 const Type *NSType = NSI.NameSpecifier->getAsType();
4166
4167 // If the current NestedNameSpecifier refers to a class and the
4168 // current correction candidate is the name of that class, then skip
4169 // it as it is unlikely a qualified version of the class' constructor
4170 // is an appropriate correction.
Hans Wennborgdcfba332015-10-06 23:40:43 +00004171 if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() :
4172 nullptr) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004173 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
4174 continue;
4175 }
4176
4177 TypoCorrection TC(QR);
4178 TC.ClearCorrectionDecls();
4179 TC.setCorrectionSpecifier(NSI.NameSpecifier);
4180 TC.setQualifierDistance(NSI.EditDistance);
4181 TC.setCallbackDistance(0); // Reset the callback distance
4182
4183 // If the current correction candidate and namespace combination are
4184 // too far away from the original typo based on the normalized edit
4185 // distance, then skip performing a qualified name lookup.
4186 unsigned TmpED = TC.getEditDistance(true);
4187 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
4188 TypoLen / TmpED < 3)
4189 continue;
4190
4191 Result.clear();
4192 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
4193 if (!SemaRef.LookupQualifiedName(Result, Ctx))
4194 continue;
4195
4196 // Any corrections added below will be validated in subsequent
4197 // iterations of the main while() loop over the Consumer's contents.
4198 switch (Result.getResultKind()) {
4199 case LookupResult::Found:
4200 case LookupResult::FoundOverloaded: {
4201 if (SS && SS->isValid()) {
4202 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
4203 std::string OldQualified;
4204 llvm::raw_string_ostream OldOStream(OldQualified);
4205 SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
4206 OldOStream << Typo->getName();
4207 // If correction candidate would be an identical written qualified
4208 // identifer, then the existing CXXScopeSpec probably included a
4209 // typedef that didn't get accounted for properly.
4210 if (OldOStream.str() == NewQualified)
4211 break;
4212 }
4213 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
4214 TRD != TRDEnd; ++TRD) {
4215 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4216 NSType ? NSType->getAsCXXRecordDecl()
4217 : nullptr,
4218 TRD.getPair()) == Sema::AR_accessible)
4219 TC.addCorrectionDecl(*TRD);
4220 }
Kaelyn Takata0a313022014-11-20 22:06:26 +00004221 if (TC.isResolved()) {
4222 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004223 addCorrection(TC);
Kaelyn Takata0a313022014-11-20 22:06:26 +00004224 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004225 break;
4226 }
4227 case LookupResult::NotFound:
4228 case LookupResult::NotFoundInCurrentInstantiation:
4229 case LookupResult::Ambiguous:
4230 case LookupResult::FoundUnresolvedValue:
4231 break;
4232 }
4233 }
4234 }
4235 QualifiedResults.clear();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004236}
4237
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004238TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
4239 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
Benjamin Kramer15537272015-03-13 16:10:42 +00004240 : Context(Context), CurContextChain(buildContextChain(CurContext)) {
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004241 if (NestedNameSpecifier *NNS =
4242 CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
4243 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
4244 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4245
4246 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
4247 }
4248 // Build the list of identifiers that would be used for an absolute
4249 // (from the global context) NestedNameSpecifier referring to the current
4250 // context.
David Majnemerf7e36092016-06-23 00:15:04 +00004251 for (DeclContext *C : llvm::reverse(CurContextChain)) {
4252 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C))
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004253 CurContextIdentifiers.push_back(ND->getIdentifier());
4254 }
4255
4256 // Add the global context as a NestedNameSpecifier
Hans Wennborg66010132014-06-11 21:24:13 +00004257 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
4258 NestedNameSpecifier::GlobalSpecifier(Context), 1};
4259 DistanceMap[1].push_back(SI);
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004260}
4261
Kaelyn Takata7dcc0e62014-06-11 18:07:08 +00004262auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
4263 DeclContext *Start) -> DeclContextList {
Nick Lewycky0d9b3192013-04-08 21:55:21 +00004264 assert(Start && "Building a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004265 DeclContextList Chain;
Craig Topperc3ec1492014-05-26 06:22:03 +00004266 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004267 DC = DC->getLookupParent()) {
4268 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
4269 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
4270 !(ND && ND->isAnonymousNamespace()))
4271 Chain.push_back(DC->getPrimaryContext());
4272 }
4273 return Chain;
4274}
4275
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004276unsigned
4277TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
4278 DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004279 unsigned NumSpecifiers = 0;
David Majnemerf7e36092016-06-23 00:15:04 +00004280 for (DeclContext *C : llvm::reverse(DeclChain)) {
4281 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004282 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
4283 ++NumSpecifiers;
David Majnemerf7e36092016-06-23 00:15:04 +00004284 } else if (auto *RD = dyn_cast_or_null<RecordDecl>(C)) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004285 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
4286 RD->getTypeForDecl());
4287 ++NumSpecifiers;
4288 }
4289 }
4290 return NumSpecifiers;
4291}
4292
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004293void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
4294 DeclContext *Ctx) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004295 NestedNameSpecifier *NNS = nullptr;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004296 unsigned NumSpecifiers = 0;
Kaelyn Takata0fc75192014-06-11 18:06:56 +00004297 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004298 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
4299
4300 // Eliminate common elements from the two DeclContext chains.
David Majnemerf7e36092016-06-23 00:15:04 +00004301 for (DeclContext *C : llvm::reverse(CurContextChain)) {
4302 if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() != C)
4303 break;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004304 NamespaceDeclChain.pop_back();
4305 }
4306
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004307 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004308 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004309
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004310 // Add an explicit leading '::' specifier if needed.
4311 if (NamespaceDeclChain.empty()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004312 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004313 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004314 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004315 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004316 } else if (NamedDecl *ND =
4317 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004318 IdentifierInfo *Name = ND->getIdentifier();
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004319 bool SameNameSpecifier = false;
4320 if (std::find(CurNameSpecifierIdentifiers.begin(),
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004321 CurNameSpecifierIdentifiers.end(),
4322 Name) != CurNameSpecifierIdentifiers.end()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004323 std::string NewNameSpecifier;
4324 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
4325 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
4326 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4327 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4328 SpecifierOStream.flush();
4329 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004330 }
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004331 if (SameNameSpecifier ||
4332 std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
4333 Name) != CurContextIdentifiers.end()) {
4334 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4335 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4336 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004337 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004338 }
4339 }
4340
4341 // If the built NestedNameSpecifier would be replacing an existing
4342 // NestedNameSpecifier, use the number of component identifiers that
4343 // would need to be changed as the edit distance instead of the number
4344 // of components in the built NestedNameSpecifier.
4345 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
4346 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
4347 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4348 NumSpecifiers = llvm::ComputeEditDistance(
Craig Topper8c2a2a02014-08-30 16:55:39 +00004349 llvm::makeArrayRef(CurNameSpecifierIdentifiers),
4350 llvm::makeArrayRef(NewNameSpecifierIdentifiers));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004351 }
4352
Hans Wennborg66010132014-06-11 21:24:13 +00004353 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
4354 DistanceMap[NumSpecifiers].push_back(SI);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004355}
4356
Douglas Gregord507d772010-10-20 03:06:34 +00004357/// \brief Perform name lookup for a possible result for typo correction.
4358static void LookupPotentialTypoResult(Sema &SemaRef,
4359 LookupResult &Res,
4360 IdentifierInfo *Name,
4361 Scope *S, CXXScopeSpec *SS,
4362 DeclContext *MemberContext,
4363 bool EnteringContext,
Richard Smithe156254d2013-08-20 20:35:18 +00004364 bool isObjCIvarLookup,
4365 bool FindHidden) {
Douglas Gregord507d772010-10-20 03:06:34 +00004366 Res.suppressDiagnostics();
4367 Res.clear();
4368 Res.setLookupName(Name);
Richard Smithe156254d2013-08-20 20:35:18 +00004369 Res.setAllowHidden(FindHidden);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004370 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00004371 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004372 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00004373 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
4374 Res.addDecl(Ivar);
4375 Res.resolveKind();
4376 return;
4377 }
4378 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004379
Manman Ren5b786402016-01-28 18:49:28 +00004380 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(
4381 Name, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Douglas Gregord507d772010-10-20 03:06:34 +00004382 Res.addDecl(Prop);
4383 Res.resolveKind();
4384 return;
4385 }
4386 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004387
Douglas Gregord507d772010-10-20 03:06:34 +00004388 SemaRef.LookupQualifiedName(Res, MemberContext);
4389 return;
4390 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004391
4392 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00004393 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004394
Douglas Gregord507d772010-10-20 03:06:34 +00004395 // Fake ivar lookup; this should really be part of
4396 // LookupParsedName.
4397 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
4398 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004399 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00004400 (Res.isSingleResult() &&
4401 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004402 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00004403 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
4404 Res.addDecl(IV);
4405 Res.resolveKind();
4406 }
4407 }
4408 }
4409}
4410
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004411/// \brief Add keywords to the consumer as possible typo corrections.
4412static void AddKeywordsToConsumer(Sema &SemaRef,
4413 TypoCorrectionConsumer &Consumer,
Richard Smithb3a1df02012-06-08 21:35:42 +00004414 Scope *S, CorrectionCandidateCallback &CCC,
4415 bool AfterNestedNameSpecifier) {
4416 if (AfterNestedNameSpecifier) {
4417 // For 'X::', we know exactly which keywords can appear next.
4418 Consumer.addKeywordResult("template");
4419 if (CCC.WantExpressionKeywords)
4420 Consumer.addKeywordResult("operator");
4421 return;
4422 }
4423
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004424 if (CCC.WantObjCSuper)
4425 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004426
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004427 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004428 // Add type-specifier keywords to the set of results.
Craig Topperd6d31ac2013-07-15 08:24:27 +00004429 static const char *const CTypeSpecs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004430 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00004431 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004432 "_Complex", "_Imaginary",
4433 // storage-specifiers as well
4434 "extern", "inline", "static", "typedef"
4435 };
4436
Craig Toppere5ce8312013-07-15 03:38:40 +00004437 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004438 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
4439 Consumer.addKeywordResult(CTypeSpecs[I]);
4440
David Blaikiebbafb8a2012-03-11 07:00:24 +00004441 if (SemaRef.getLangOpts().C99)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004442 Consumer.addKeywordResult("restrict");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004443 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004444 Consumer.addKeywordResult("bool");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004445 else if (SemaRef.getLangOpts().C99)
Douglas Gregor3b22a882011-07-01 21:27:45 +00004446 Consumer.addKeywordResult("_Bool");
4447
David Blaikiebbafb8a2012-03-11 07:00:24 +00004448 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004449 Consumer.addKeywordResult("class");
4450 Consumer.addKeywordResult("typename");
4451 Consumer.addKeywordResult("wchar_t");
4452
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004453 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004454 Consumer.addKeywordResult("char16_t");
4455 Consumer.addKeywordResult("char32_t");
4456 Consumer.addKeywordResult("constexpr");
4457 Consumer.addKeywordResult("decltype");
4458 Consumer.addKeywordResult("thread_local");
4459 }
4460 }
4461
David Blaikiebbafb8a2012-03-11 07:00:24 +00004462 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004463 Consumer.addKeywordResult("typeof");
Kaelyn Takatab04846b2014-07-28 18:14:02 +00004464 } else if (CCC.WantFunctionLikeCasts) {
4465 static const char *const CastableTypeSpecs[] = {
4466 "char", "double", "float", "int", "long", "short",
4467 "signed", "unsigned", "void"
4468 };
4469 for (auto *kw : CastableTypeSpecs)
4470 Consumer.addKeywordResult(kw);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004471 }
4472
David Blaikiebbafb8a2012-03-11 07:00:24 +00004473 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004474 Consumer.addKeywordResult("const_cast");
4475 Consumer.addKeywordResult("dynamic_cast");
4476 Consumer.addKeywordResult("reinterpret_cast");
4477 Consumer.addKeywordResult("static_cast");
4478 }
4479
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004480 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004481 Consumer.addKeywordResult("sizeof");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004482 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004483 Consumer.addKeywordResult("false");
4484 Consumer.addKeywordResult("true");
4485 }
4486
David Blaikiebbafb8a2012-03-11 07:00:24 +00004487 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topperd6d31ac2013-07-15 08:24:27 +00004488 static const char *const CXXExprs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004489 "delete", "new", "operator", "throw", "typeid"
4490 };
Craig Toppere5ce8312013-07-15 03:38:40 +00004491 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004492 for (unsigned I = 0; I != NumCXXExprs; ++I)
4493 Consumer.addKeywordResult(CXXExprs[I]);
4494
4495 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
4496 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
4497 Consumer.addKeywordResult("this");
4498
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004499 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004500 Consumer.addKeywordResult("alignof");
4501 Consumer.addKeywordResult("nullptr");
4502 }
4503 }
Jordan Rose58d54722012-06-30 21:33:57 +00004504
4505 if (SemaRef.getLangOpts().C11) {
4506 // FIXME: We should not suggest _Alignof if the alignof macro
4507 // is present.
4508 Consumer.addKeywordResult("_Alignof");
4509 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004510 }
4511
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004512 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004513 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
4514 // Statements.
Craig Topperd6d31ac2013-07-15 08:24:27 +00004515 static const char *const CStmts[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004516 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Toppere5ce8312013-07-15 03:38:40 +00004517 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004518 for (unsigned I = 0; I != NumCStmts; ++I)
4519 Consumer.addKeywordResult(CStmts[I]);
4520
David Blaikiebbafb8a2012-03-11 07:00:24 +00004521 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004522 Consumer.addKeywordResult("catch");
4523 Consumer.addKeywordResult("try");
4524 }
4525
4526 if (S && S->getBreakParent())
4527 Consumer.addKeywordResult("break");
4528
4529 if (S && S->getContinueParent())
4530 Consumer.addKeywordResult("continue");
4531
Reid Kleckner87a31802018-03-12 21:43:02 +00004532 if (SemaRef.getCurFunction() &&
4533 !SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004534 Consumer.addKeywordResult("case");
4535 Consumer.addKeywordResult("default");
4536 }
4537 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004538 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004539 Consumer.addKeywordResult("namespace");
4540 Consumer.addKeywordResult("template");
4541 }
4542
4543 if (S && S->isClassScope()) {
4544 Consumer.addKeywordResult("explicit");
4545 Consumer.addKeywordResult("friend");
4546 Consumer.addKeywordResult("mutable");
4547 Consumer.addKeywordResult("private");
4548 Consumer.addKeywordResult("protected");
4549 Consumer.addKeywordResult("public");
4550 Consumer.addKeywordResult("virtual");
4551 }
4552 }
4553
David Blaikiebbafb8a2012-03-11 07:00:24 +00004554 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004555 Consumer.addKeywordResult("using");
4556
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004557 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004558 Consumer.addKeywordResult("static_assert");
4559 }
4560 }
4561}
4562
Kaelyn Takata6c759512014-10-27 18:07:37 +00004563std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
4564 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4565 Scope *S, CXXScopeSpec *SS,
4566 std::unique_ptr<CorrectionCandidateCallback> CCC,
4567 DeclContext *MemberContext, bool EnteringContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004568 const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00004569
4570 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4571 DisableTypoCorrection)
4572 return nullptr;
4573
4574 // In Microsoft mode, don't perform typo correction in a template member
4575 // function dependent context because it interferes with the "lookup into
4576 // dependent bases of class templates" feature.
4577 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
4578 isa<CXXMethodDecl>(CurContext))
4579 return nullptr;
4580
4581 // We only attempt to correct typos for identifiers.
4582 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4583 if (!Typo)
4584 return nullptr;
4585
4586 // If the scope specifier itself was invalid, don't try to correct
4587 // typos.
4588 if (SS && SS->isInvalid())
4589 return nullptr;
4590
Richard Smith696e3122017-02-23 01:43:54 +00004591 // Never try to correct typos during any kind of code synthesis.
4592 if (!CodeSynthesisContexts.empty())
Kaelyn Takata6c759512014-10-27 18:07:37 +00004593 return nullptr;
4594
4595 // Don't try to correct 'super'.
4596 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4597 return nullptr;
4598
4599 // Abort if typo correction already failed for this specific typo.
4600 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4601 if (locs != TypoCorrectionFailures.end() &&
4602 locs->second.count(TypoName.getLoc()))
4603 return nullptr;
4604
4605 // Don't try to correct the identifier "vector" when in AltiVec mode.
4606 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4607 // remove this workaround.
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00004608 if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector"))
Kaelyn Takata6c759512014-10-27 18:07:37 +00004609 return nullptr;
4610
Nick Lewycky24653262014-12-16 21:39:02 +00004611 // Provide a stop gap for files that are just seriously broken. Trying
4612 // to correct all typos can turn into a HUGE performance penalty, causing
4613 // some files to take minutes to get rejected by the parser.
4614 unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
4615 if (Limit && TyposCorrected >= Limit)
4616 return nullptr;
4617 ++TyposCorrected;
4618
Kaelyn Takata6c759512014-10-27 18:07:37 +00004619 // If we're handling a missing symbol error, using modules, and the
4620 // special search all modules option is used, look for a missing import.
4621 if (ErrorRecovery && getLangOpts().Modules &&
4622 getLangOpts().ModulesSearchAll) {
4623 // The following has the side effect of loading the missing module.
4624 getModuleLoader().lookupMissingImports(Typo->getName(),
4625 TypoName.getLocStart());
4626 }
4627
4628 CorrectionCandidateCallback &CCCRef = *CCC;
4629 auto Consumer = llvm::make_unique<TypoCorrectionConsumer>(
4630 *this, TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
4631 EnteringContext);
4632
Kaelyn Takata6c759512014-10-27 18:07:37 +00004633 // Perform name lookup to find visible, similarly-named entities.
Nick Lewycky24653262014-12-16 21:39:02 +00004634 bool IsUnqualifiedLookup = false;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004635 DeclContext *QualifiedDC = MemberContext;
4636 if (MemberContext) {
4637 LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
4638
4639 // Look in qualified interfaces.
4640 if (OPT) {
4641 for (auto *I : OPT->quals())
4642 LookupVisibleDecls(I, LookupKind, *Consumer);
4643 }
4644 } else if (SS && SS->isSet()) {
4645 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4646 if (!QualifiedDC)
4647 return nullptr;
4648
Kaelyn Takata6c759512014-10-27 18:07:37 +00004649 LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
4650 } else {
4651 IsUnqualifiedLookup = true;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004652 }
4653
4654 // Determine whether we are going to search in the various namespaces for
4655 // corrections.
4656 bool SearchNamespaces
4657 = getLangOpts().CPlusPlus &&
4658 (IsUnqualifiedLookup || (SS && SS->isSet()));
4659
4660 if (IsUnqualifiedLookup || SearchNamespaces) {
4661 // For unqualified lookup, look through all of the names that we have
4662 // seen in this translation unit.
4663 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4664 for (const auto &I : Context.Idents)
4665 Consumer->FoundName(I.getKey());
4666
4667 // Walk through identifiers in external identifier sources.
4668 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4669 if (IdentifierInfoLookup *External
4670 = Context.Idents.getExternalIdentifierLookup()) {
4671 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4672 do {
4673 StringRef Name = Iter->Next();
4674 if (Name.empty())
4675 break;
4676
4677 Consumer->FoundName(Name);
4678 } while (true);
4679 }
4680 }
4681
4682 AddKeywordsToConsumer(*this, *Consumer, S, CCCRef, SS && SS->isNotEmpty());
4683
4684 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4685 // to search those namespaces.
4686 if (SearchNamespaces) {
4687 // Load any externally-known namespaces.
4688 if (ExternalSource && !LoadedExternalKnownNamespaces) {
4689 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
4690 LoadedExternalKnownNamespaces = true;
4691 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4692 for (auto *N : ExternalKnownNamespaces)
4693 KnownNamespaces[N] = true;
4694 }
4695
4696 Consumer->addNamespaces(KnownNamespaces);
4697 }
4698
4699 return Consumer;
4700}
4701
Douglas Gregor2d435302009-12-30 17:04:44 +00004702/// \brief Try to "correct" a typo in the source code by finding
4703/// visible declarations whose names are similar to the name that was
4704/// present in the source code.
4705///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004706/// \param TypoName the \c DeclarationNameInfo structure that contains
4707/// the name that was present in the source code along with its location.
4708///
4709/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00004710///
4711/// \param S the scope in which name lookup occurs.
4712///
4713/// \param SS the nested-name-specifier that precedes the name we're
4714/// looking for, if present.
4715///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004716/// \param CCC A CorrectionCandidateCallback object that provides further
4717/// validation of typo correction candidates. It also provides flags for
4718/// determining the set of keywords permitted.
4719///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00004720/// \param MemberContext if non-NULL, the context in which to look for
4721/// a member access expression.
4722///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004723/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00004724/// the nested-name-specifier SS.
4725///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004726/// \param OPT when non-NULL, the search for visible declarations will
4727/// also walk the protocols in the qualified interfaces of \p OPT.
4728///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004729/// \returns a \c TypoCorrection containing the corrected name if the typo
4730/// along with information such as the \c NamedDecl where the corrected name
4731/// was declared, and any additional \c NestedNameSpecifier needed to access
4732/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
4733TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
4734 Sema::LookupNameKind LookupKind,
4735 Scope *S, CXXScopeSpec *SS,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004736 std::unique_ptr<CorrectionCandidateCallback> CCC,
John Thompson2255f2c2014-04-23 12:57:01 +00004737 CorrectTypoKind Mode,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004738 DeclContext *MemberContext,
4739 bool EnteringContext,
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004740 const ObjCObjectPointerType *OPT,
4741 bool RecordFailure) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004742 assert(CCC && "CorrectTypo requires a CorrectionCandidateCallback");
4743
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004744 // Always let the ExternalSource have the first chance at correction, even
4745 // if we would otherwise have given up.
4746 if (ExternalSource) {
4747 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004748 TypoName, LookupKind, S, SS, *CCC, MemberContext, EnteringContext, OPT))
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004749 return Correction;
4750 }
4751
Kaelyn Takata6c759512014-10-27 18:07:37 +00004752 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4753 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4754 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4755 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
4756 bool ObjCMessageReceiver = CCC->WantObjCSuper && !CCC->WantRemainingKeywords;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004757
Kaelyn Takata6c759512014-10-27 18:07:37 +00004758 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Kaelyn Takata6c759512014-10-27 18:07:37 +00004759 auto Consumer = makeTypoCorrectionConsumer(
4760 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004761 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004762
Kaelyn Takata6c759512014-10-27 18:07:37 +00004763 if (!Consumer)
4764 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004765
Douglas Gregor280e1ee2010-04-14 20:04:41 +00004766 // If we haven't found anything, we're done.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004767 if (Consumer->empty())
Nick Lewycky24653262014-12-16 21:39:02 +00004768 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregor2d435302009-12-30 17:04:44 +00004769
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004770 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4771 // is not more that about a third of the length of the typo's identifier.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004772 unsigned ED = Consumer->getBestEditDistance(true);
4773 unsigned TypoLen = Typo->getName().size();
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004774 if (ED > 0 && TypoLen / ED < 3)
Nick Lewycky24653262014-12-16 21:39:02 +00004775 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004776
Kaelyn Takata6c759512014-10-27 18:07:37 +00004777 TypoCorrection BestTC = Consumer->getNextCorrection();
4778 TypoCorrection SecondBestTC = Consumer->getNextCorrection();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004779 if (!BestTC)
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004780 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004781
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004782 ED = BestTC.getEditDistance();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004783
Kaelyn Takata6c759512014-10-27 18:07:37 +00004784 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004785 // If this was an unqualified lookup and we believe the callback
4786 // object wouldn't have filtered out possible corrections, note
4787 // that no correction was found.
Nick Lewycky24653262014-12-16 21:39:02 +00004788 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004789 }
4790
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004791 // If only a single name remains, return that result.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004792 if (!SecondBestTC ||
4793 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
4794 const TypoCorrection &Result = BestTC;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004795
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00004796 // Don't correct to a keyword that's the same as the typo; the keyword
4797 // wasn't actually in scope.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004798 if (ED == 0 && Result.isKeyword())
4799 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004800
David Blaikie04ea41c2012-10-12 20:00:44 +00004801 TypoCorrection TC = Result;
4802 TC.setCorrectionRange(SS, TypoName);
Kaelyn Takataa95ebc62014-06-17 23:47:29 +00004803 checkCorrectionVisibility(*this, TC);
David Blaikie04ea41c2012-10-12 20:00:44 +00004804 return TC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004805 } else if (SecondBestTC && ObjCMessageReceiver) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004806 // Prefer 'super' when we're completing in a message-receiver
4807 // context.
4808
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004809 if (BestTC.getCorrection().getAsString() != "super") {
4810 if (SecondBestTC.getCorrection().getAsString() == "super")
4811 BestTC = SecondBestTC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004812 else if ((*Consumer)["super"].front().isKeyword())
4813 BestTC = (*Consumer)["super"].front();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004814 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004815 // Don't correct to a keyword that's the same as the typo; the keyword
4816 // wasn't actually in scope.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004817 if (BestTC.getEditDistance() == 0 ||
4818 BestTC.getCorrection().getAsString() != "super")
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004819 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004820
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004821 BestTC.setCorrectionRange(SS, TypoName);
4822 return BestTC;
Douglas Gregoraf9eb592010-10-15 13:35:25 +00004823 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004824
Kaelyn Takata73429fd2014-06-10 21:03:49 +00004825 // Record the failure's location if needed and return an empty correction. If
4826 // this was an unqualified lookup and we believe the callback object did not
4827 // filter out possible corrections, also cache the failure for the typo.
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004828 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004829}
4830
Kaelyn Takata6c759512014-10-27 18:07:37 +00004831/// \brief Try to "correct" a typo in the source code by finding
4832/// visible declarations whose names are similar to the name that was
4833/// present in the source code.
4834///
4835/// \param TypoName the \c DeclarationNameInfo structure that contains
4836/// the name that was present in the source code along with its location.
4837///
4838/// \param LookupKind the name-lookup criteria used to search for the name.
4839///
4840/// \param S the scope in which name lookup occurs.
4841///
4842/// \param SS the nested-name-specifier that precedes the name we're
4843/// looking for, if present.
4844///
4845/// \param CCC A CorrectionCandidateCallback object that provides further
4846/// validation of typo correction candidates. It also provides flags for
4847/// determining the set of keywords permitted.
4848///
4849/// \param TDG A TypoDiagnosticGenerator functor that will be used to print
4850/// diagnostics when the actual typo correction is attempted.
4851///
Kaelyn Takata8363f042014-10-27 18:07:42 +00004852/// \param TRC A TypoRecoveryCallback functor that will be used to build an
4853/// Expr from a typo correction candidate.
4854///
Kaelyn Takata6c759512014-10-27 18:07:37 +00004855/// \param MemberContext if non-NULL, the context in which to look for
4856/// a member access expression.
4857///
4858/// \param EnteringContext whether we're entering the context described by
4859/// the nested-name-specifier SS.
4860///
4861/// \param OPT when non-NULL, the search for visible declarations will
4862/// also walk the protocols in the qualified interfaces of \p OPT.
4863///
4864/// \returns a new \c TypoExpr that will later be replaced in the AST with an
4865/// Expr representing the result of performing typo correction, or nullptr if
4866/// typo correction is not possible. If nullptr is returned, no diagnostics will
4867/// be emitted and it is the responsibility of the caller to emit any that are
4868/// needed.
4869TypoExpr *Sema::CorrectTypoDelayed(
4870 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4871 Scope *S, CXXScopeSpec *SS,
4872 std::unique_ptr<CorrectionCandidateCallback> CCC,
Kaelyn Takata8363f042014-10-27 18:07:42 +00004873 TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,
Kaelyn Takata6c759512014-10-27 18:07:37 +00004874 DeclContext *MemberContext, bool EnteringContext,
4875 const ObjCObjectPointerType *OPT) {
4876 assert(CCC && "CorrectTypoDelayed requires a CorrectionCandidateCallback");
4877
Kaelyn Takata6c759512014-10-27 18:07:37 +00004878 auto Consumer = makeTypoCorrectionConsumer(
4879 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004880 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Kaelyn Takata6c759512014-10-27 18:07:37 +00004881
Benjamin Kramerb8727332016-05-19 10:46:10 +00004882 // Give the external sema source a chance to correct the typo.
4883 TypoCorrection ExternalTypo;
4884 if (ExternalSource && Consumer) {
4885 ExternalTypo = ExternalSource->CorrectTypo(
Benjamin Kramer97d7a662016-05-19 21:53:33 +00004886 TypoName, LookupKind, S, SS, *Consumer->getCorrectionValidator(),
4887 MemberContext, EnteringContext, OPT);
Benjamin Kramerb8727332016-05-19 10:46:10 +00004888 if (ExternalTypo)
4889 Consumer->addCorrection(ExternalTypo);
4890 }
4891
Kaelyn Takata6c759512014-10-27 18:07:37 +00004892 if (!Consumer || Consumer->empty())
4893 return nullptr;
4894
4895 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4896 // is not more that about a third of the length of the typo's identifier.
4897 unsigned ED = Consumer->getBestEditDistance(true);
4898 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Benjamin Kramerb8727332016-05-19 10:46:10 +00004899 if (!ExternalTypo && ED > 0 && Typo->getName().size() / ED < 3)
Kaelyn Takata6c759512014-10-27 18:07:37 +00004900 return nullptr;
4901
4902 ExprEvalContexts.back().NumTypos++;
Kaelyn Takata8363f042014-10-27 18:07:42 +00004903 return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC));
Kaelyn Takata6c759512014-10-27 18:07:37 +00004904}
4905
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004906void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4907 if (!CDecl) return;
4908
4909 if (isKeyword())
4910 CorrectionDecls.clear();
4911
Richard Smithde6d6c42015-12-29 19:43:10 +00004912 CorrectionDecls.push_back(CDecl);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004913
4914 if (!CorrectionName)
4915 CorrectionName = CDecl->getDeclName();
4916}
4917
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004918std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4919 if (CorrectionNameSpec) {
4920 std::string tmpBuffer;
4921 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4922 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikied4da8722013-05-14 21:04:00 +00004923 PrefixOStream << CorrectionName;
Benjamin Kramer73faad62012-04-14 08:26:28 +00004924 return PrefixOStream.str();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004925 }
4926
4927 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00004928}
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004929
Nico Weberb58e51c2014-11-19 05:21:39 +00004930bool CorrectionCandidateCallback::ValidateCandidate(
4931 const TypoCorrection &candidate) {
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004932 if (!candidate.isResolved())
4933 return true;
4934
4935 if (candidate.isKeyword())
4936 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4937 WantRemainingKeywords || WantObjCSuper;
4938
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004939 bool HasNonType = false;
4940 bool HasStaticMethod = false;
4941 bool HasNonStaticMethod = false;
4942 for (Decl *D : candidate) {
4943 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
4944 D = FTD->getTemplatedDecl();
4945 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4946 if (Method->isStatic())
4947 HasStaticMethod = true;
4948 else
4949 HasNonStaticMethod = true;
4950 }
4951 if (!isa<TypeDecl>(D))
4952 HasNonType = true;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004953 }
4954
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004955 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
4956 !candidate.getCorrectionSpecifier())
4957 return false;
4958
4959 return WantTypeSpecifiers || HasNonType;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004960}
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004961
4962FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004963 bool HasExplicitTemplateArgs,
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004964 MemberExpr *ME)
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004965 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004966 CurContext(SemaRef.CurContext), MemberFn(ME) {
Kaelyn Takatab04846b2014-07-28 18:14:02 +00004967 WantTypeSpecifiers = false;
4968 WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus && NumArgs == 1;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004969 WantRemainingKeywords = false;
4970}
4971
4972bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4973 if (!candidate.getCorrectionDecl())
4974 return candidate.isKeyword();
4975
Aaron Ballman1e606f42014-07-15 22:03:49 +00004976 for (auto *C : candidate) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004977 FunctionDecl *FD = nullptr;
Aaron Ballman1e606f42014-07-15 22:03:49 +00004978 NamedDecl *ND = C->getUnderlyingDecl();
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004979 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4980 FD = FTD->getTemplatedDecl();
4981 if (!HasExplicitTemplateArgs && !FD) {
4982 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4983 // If the Decl is neither a function nor a template function,
4984 // determine if it is a pointer or reference to a function. If so,
4985 // check against the number of arguments expected for the pointee.
4986 QualType ValType = cast<ValueDecl>(ND)->getType();
4987 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4988 ValType = ValType->getPointeeType();
4989 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
Alp Toker9cacbab2014-01-20 20:26:09 +00004990 if (FPT->getNumParams() == NumArgs)
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004991 return true;
4992 }
4993 }
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004994
4995 // Skip the current candidate if it is not a FunctionDecl or does not accept
4996 // the current number of arguments.
4997 if (!FD || !(FD->getNumParams() >= NumArgs &&
4998 FD->getMinRequiredArguments() <= NumArgs))
4999 continue;
5000
Kaelyn Takatafb271f02014-04-04 22:16:30 +00005001 // If the current candidate is a non-static C++ method, skip the candidate
5002 // unless the method being corrected--or the current DeclContext, if the
5003 // function being corrected is not a method--is a method in the same class
5004 // or a descendent class of the candidate's parent class.
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00005005 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Kaelyn Takatafb271f02014-04-04 22:16:30 +00005006 if (MemberFn || !MD->isStatic()) {
5007 CXXMethodDecl *CurMD =
5008 MemberFn
5009 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
5010 : dyn_cast_or_null<CXXMethodDecl>(CurContext);
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00005011 CXXRecordDecl *CurRD =
Craig Topperc3ec1492014-05-26 06:22:03 +00005012 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00005013 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
5014 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
5015 continue;
5016 }
5017 }
5018 return true;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00005019 }
5020 return false;
5021}
Richard Smithf9b15102013-08-17 00:46:16 +00005022
5023void Sema::diagnoseTypo(const TypoCorrection &Correction,
5024 const PartialDiagnostic &TypoDiag,
5025 bool ErrorRecovery) {
5026 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
5027 ErrorRecovery);
5028}
5029
Richard Smithe156254d2013-08-20 20:35:18 +00005030/// Find which declaration we should import to provide the definition of
5031/// the given declaration.
Richard Smith42413142015-05-15 20:05:43 +00005032static NamedDecl *getDefinitionToImport(NamedDecl *D) {
5033 if (VarDecl *VD = dyn_cast<VarDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00005034 return VD->getDefinition();
Yaron Keren18c3d062016-07-13 19:04:51 +00005035 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5036 return FD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00005037 if (TagDecl *TD = dyn_cast<TagDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00005038 return TD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00005039 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00005040 return ID->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00005041 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00005042 return PD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00005043 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00005044 return getDefinitionToImport(TD->getTemplatedDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005045 return nullptr;
Richard Smithe156254d2013-08-20 20:35:18 +00005046}
5047
Richard Smithf2b1eb92015-06-15 20:15:48 +00005048void Sema::diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
Richard Smith6739a102016-05-05 00:56:12 +00005049 MissingImportKind MIK, bool Recover) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00005050 // Suggest importing a module providing the definition of this entity, if
5051 // possible.
5052 NamedDecl *Def = getDefinitionToImport(Decl);
5053 if (!Def)
5054 Def = Decl;
5055
Richard Smithf2b1eb92015-06-15 20:15:48 +00005056 Module *Owner = getOwningModule(Decl);
5057 assert(Owner && "definition of hidden declaration is not in a module");
5058
Richard Smith35c1df52015-06-17 20:16:32 +00005059 llvm::SmallVector<Module*, 8> OwningModules;
5060 OwningModules.push_back(Owner);
Richard Smithf2b1eb92015-06-15 20:15:48 +00005061 auto Merged = Context.getModulesWithMergedDefinition(Decl);
Richard Smith35c1df52015-06-17 20:16:32 +00005062 OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end());
5063
Richard Smith6739a102016-05-05 00:56:12 +00005064 diagnoseMissingImport(Loc, Decl, Decl->getLocation(), OwningModules, MIK,
Richard Smith35c1df52015-06-17 20:16:32 +00005065 Recover);
5066}
5067
Richard Smith4eb83932016-04-27 21:57:05 +00005068/// \brief Get a "quoted.h" or <angled.h> include path to use in a diagnostic
5069/// suggesting the addition of a #include of the specified file.
5070static std::string getIncludeStringForHeader(Preprocessor &PP,
5071 const FileEntry *E) {
5072 bool IsSystem;
5073 auto Path =
5074 PP.getHeaderSearchInfo().suggestPathToFileForDiagnostics(E, &IsSystem);
5075 return (IsSystem ? '<' : '"') + Path + (IsSystem ? '>' : '"');
5076}
5077
Richard Smith35c1df52015-06-17 20:16:32 +00005078void Sema::diagnoseMissingImport(SourceLocation UseLoc, NamedDecl *Decl,
5079 SourceLocation DeclLoc,
5080 ArrayRef<Module *> Modules,
5081 MissingImportKind MIK, bool Recover) {
5082 assert(!Modules.empty());
5083
Richard Smith54f04402017-05-18 02:29:20 +00005084 // Weed out duplicates from module list.
5085 llvm::SmallVector<Module*, 8> UniqueModules;
5086 llvm::SmallDenseSet<Module*, 8> UniqueModuleSet;
5087 for (auto *M : Modules)
5088 if (UniqueModuleSet.insert(M).second)
5089 UniqueModules.push_back(M);
5090 Modules = UniqueModules;
5091
Richard Smith35c1df52015-06-17 20:16:32 +00005092 if (Modules.size() > 1) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00005093 std::string ModuleList;
Richard Smithf2b1eb92015-06-15 20:15:48 +00005094 unsigned N = 0;
Richard Smith35c1df52015-06-17 20:16:32 +00005095 for (Module *M : Modules) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00005096 ModuleList += "\n ";
Richard Smith35c1df52015-06-17 20:16:32 +00005097 if (++N == 5 && N != Modules.size()) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00005098 ModuleList += "[...]";
5099 break;
5100 }
5101 ModuleList += M->getFullModuleName();
5102 }
5103
Richard Smith35c1df52015-06-17 20:16:32 +00005104 Diag(UseLoc, diag::err_module_unimported_use_multiple)
5105 << (int)MIK << Decl << ModuleList;
Richard Smithcbf7d8a2017-05-19 23:49:00 +00005106 } else if (const FileEntry *E = PP.getModuleHeaderToIncludeForDiagnostics(
5107 UseLoc, Modules[0], DeclLoc)) {
Richard Smith4eb83932016-04-27 21:57:05 +00005108 // The right way to make the declaration visible is to include a header;
5109 // suggest doing so.
5110 //
5111 // FIXME: Find a smart place to suggest inserting a #include, and add
5112 // a FixItHint there.
5113 Diag(UseLoc, diag::err_module_unimported_use_header)
5114 << (int)MIK << Decl << Modules[0]->getFullModuleName()
5115 << getIncludeStringForHeader(PP, E);
Richard Smithf2b1eb92015-06-15 20:15:48 +00005116 } else {
Richard Smithacef17a2016-05-05 02:14:06 +00005117 // FIXME: Add a FixItHint that imports the corresponding module.
Richard Smith35c1df52015-06-17 20:16:32 +00005118 Diag(UseLoc, diag::err_module_unimported_use)
5119 << (int)MIK << Decl << Modules[0]->getFullModuleName();
Richard Smithf2b1eb92015-06-15 20:15:48 +00005120 }
Richard Smith35c1df52015-06-17 20:16:32 +00005121
5122 unsigned DiagID;
5123 switch (MIK) {
5124 case MissingImportKind::Declaration:
5125 DiagID = diag::note_previous_declaration;
5126 break;
5127 case MissingImportKind::Definition:
5128 DiagID = diag::note_previous_definition;
5129 break;
5130 case MissingImportKind::DefaultArgument:
5131 DiagID = diag::note_default_argument_declared_here;
5132 break;
Richard Smith6739a102016-05-05 00:56:12 +00005133 case MissingImportKind::ExplicitSpecialization:
5134 DiagID = diag::note_explicit_specialization_declared_here;
5135 break;
5136 case MissingImportKind::PartialSpecialization:
5137 DiagID = diag::note_partial_specialization_declared_here;
5138 break;
Richard Smith35c1df52015-06-17 20:16:32 +00005139 }
5140 Diag(DeclLoc, DiagID);
Richard Smithf2b1eb92015-06-15 20:15:48 +00005141
5142 // Try to recover by implicitly importing this module.
5143 if (Recover)
Richard Smith35c1df52015-06-17 20:16:32 +00005144 createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
Richard Smithf2b1eb92015-06-15 20:15:48 +00005145}
5146
Richard Smithf9b15102013-08-17 00:46:16 +00005147/// \brief Diagnose a successfully-corrected typo. Separated from the correction
5148/// itself to allow external validation of the result, etc.
5149///
5150/// \param Correction The result of performing typo correction.
5151/// \param TypoDiag The diagnostic to produce. This will have the corrected
5152/// string added to it (and usually also a fixit).
5153/// \param PrevNote A note to use when indicating the location of the entity to
5154/// which we are correcting. Will have the correction string added to it.
5155/// \param ErrorRecovery If \c true (the default), the caller is going to
5156/// recover from the typo as if the corrected string had been typed.
5157/// In this case, \c PDiag must be an error, and we will attach a fixit
5158/// to it.
5159void Sema::diagnoseTypo(const TypoCorrection &Correction,
5160 const PartialDiagnostic &TypoDiag,
5161 const PartialDiagnostic &PrevNote,
5162 bool ErrorRecovery) {
5163 std::string CorrectedStr = Correction.getAsString(getLangOpts());
5164 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
5165 FixItHint FixTypo = FixItHint::CreateReplacement(
5166 Correction.getCorrectionRange(), CorrectedStr);
5167
Richard Smithe156254d2013-08-20 20:35:18 +00005168 // Maybe we're just missing a module import.
5169 if (Correction.requiresImport()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00005170 NamedDecl *Decl = Correction.getFoundDecl();
Richard Smithe156254d2013-08-20 20:35:18 +00005171 assert(Decl && "import required but no declaration to import");
5172
Richard Smithf2b1eb92015-06-15 20:15:48 +00005173 diagnoseMissingImport(Correction.getCorrectionRange().getBegin(), Decl,
Richard Smith6739a102016-05-05 00:56:12 +00005174 MissingImportKind::Declaration, ErrorRecovery);
Richard Smithe156254d2013-08-20 20:35:18 +00005175 return;
5176 }
5177
Richard Smithf9b15102013-08-17 00:46:16 +00005178 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
5179 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
5180
5181 NamedDecl *ChosenDecl =
Richard Smithde6d6c42015-12-29 19:43:10 +00005182 Correction.isKeyword() ? nullptr : Correction.getFoundDecl();
Richard Smithf9b15102013-08-17 00:46:16 +00005183 if (PrevNote.getDiagID() && ChosenDecl)
5184 Diag(ChosenDecl->getLocation(), PrevNote)
5185 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
Benjamin Kramer7de99692016-11-16 18:15:26 +00005186
5187 // Add any extra diagnostics.
5188 for (const PartialDiagnostic &PD : Correction.getExtraDiagnostics())
5189 Diag(Correction.getCorrectionRange().getBegin(), PD);
Richard Smithf9b15102013-08-17 00:46:16 +00005190}
Kaelyn Takata6c759512014-10-27 18:07:37 +00005191
Kaelyn Takata8363f042014-10-27 18:07:42 +00005192TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
5193 TypoDiagnosticGenerator TDG,
5194 TypoRecoveryCallback TRC) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00005195 assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
5196 auto TE = new (Context) TypoExpr(Context.DependentTy);
5197 auto &State = DelayedTypos[TE];
5198 State.Consumer = std::move(TCC);
5199 State.DiagHandler = std::move(TDG);
Kaelyn Takata8363f042014-10-27 18:07:42 +00005200 State.RecoveryHandler = std::move(TRC);
Kaelyn Takata6c759512014-10-27 18:07:37 +00005201 return TE;
5202}
5203
5204const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
5205 auto Entry = DelayedTypos.find(TE);
5206 assert(Entry != DelayedTypos.end() &&
5207 "Failed to get the state for a TypoExpr!");
5208 return Entry->second;
5209}
5210
5211void Sema::clearDelayedTypo(TypoExpr *TE) {
5212 DelayedTypos.erase(TE);
5213}
Richard Smithba3a4f92016-01-12 21:59:26 +00005214
5215void Sema::ActOnPragmaDump(Scope *S, SourceLocation IILoc, IdentifierInfo *II) {
5216 DeclarationNameInfo Name(II, IILoc);
5217 LookupResult R(*this, Name, LookupAnyName, Sema::NotForRedeclaration);
5218 R.suppressDiagnostics();
5219 R.setHideTags(false);
5220 LookupName(R, S);
5221 R.dump();
5222}