blob: 7066215b2b05460d945b5bfe7bbbf95774eb0488 [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 {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000091 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000092
John McCallf6c8a4e2009-11-10 07:01:13 +000093 ListTy list;
94 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000095
John McCallf6c8a4e2009-11-10 07:01:13 +000096 public:
97 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +000098
John McCallf6c8a4e2009-11-10 07:01:13 +000099 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000100 // C++ [namespace.udir]p1:
John McCallf6c8a4e2009-11-10 07:01:13 +0000101 // During unqualified name lookup, the names appear as if they
102 // were declared in the nearest enclosing namespace which contains
103 // both the using-directive and the nominated namespace.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000104 DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
John McCallf6c8a4e2009-11-10 07:01:13 +0000105 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +0000106
John McCallf6c8a4e2009-11-10 07:01:13 +0000107 for (; S; S = S->getParent()) {
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000108 // C++ [namespace.udir]p1:
109 // A using-directive shall not appear in class scope, but may
110 // appear in namespace scope or in block scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000111 DeclContext *Ctx = S->getEntity();
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000112 if (Ctx && Ctx->isFileContext()) {
113 visit(Ctx, Ctx);
114 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
Aaron Ballman5df6aa42014-03-17 17:03:37 +0000115 for (auto *I : S->using_directives())
116 visit(I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000117 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000118 }
119 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000120
121 // Visits a context and collect all of its using directives
122 // recursively. Treats all using directives as if they were
123 // declared in the context.
124 //
125 // A given context is only every visited once, so it is important
126 // that contexts be visited from the inside out in order to get
127 // the effective DCs right.
128 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
David Blaikie82e95a32014-11-19 07:49:47 +0000129 if (!visited.insert(DC).second)
John McCallf6c8a4e2009-11-10 07:01:13 +0000130 return;
131
132 addUsingDirectives(DC, EffectiveDC);
133 }
134
135 // Visits a using directive and collects all of its using
136 // directives recursively. Treats all using directives as if they
137 // were declared in the effective DC.
138 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
139 DeclContext *NS = UD->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +0000140 if (!visited.insert(NS).second)
John McCallf6c8a4e2009-11-10 07:01:13 +0000141 return;
142
143 addUsingDirective(UD, EffectiveDC);
144 addUsingDirectives(NS, EffectiveDC);
145 }
146
147 // Adds all the using directives in a context (and those nominated
148 // by its using directives, transitively) as if they appeared in
149 // the given effective context.
150 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Nick Lewycky4b81fc872015-10-18 20:32:12 +0000151 SmallVector<DeclContext*, 4> queue;
John McCallf6c8a4e2009-11-10 07:01:13 +0000152 while (true) {
Aaron Ballman804a7fb2014-03-17 17:14:12 +0000153 for (auto UD : DC->using_directives()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000154 DeclContext *NS = UD->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +0000155 if (visited.insert(NS).second) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000156 addUsingDirective(UD, EffectiveDC);
157 queue.push_back(NS);
158 }
159 }
160
161 if (queue.empty())
162 return;
163
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000164 DC = queue.pop_back_val();
John McCallf6c8a4e2009-11-10 07:01:13 +0000165 }
166 }
167
168 // Add a using directive as if it had been declared in the given
169 // context. This helps implement C++ [namespace.udir]p3:
170 // The using-directive is transitive: if a scope contains a
171 // using-directive that nominates a second namespace that itself
172 // contains using-directives, the effect is as if the
173 // using-directives from the second namespace also appeared in
174 // the first.
175 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
176 // Find the common ancestor between the effective context and
177 // the nominated namespace.
178 DeclContext *Common = UD->getNominatedNamespace();
179 while (!Common->Encloses(EffectiveDC))
180 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000181 Common = Common->getPrimaryContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000182
John McCallf6c8a4e2009-11-10 07:01:13 +0000183 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
184 }
185
186 void done() {
187 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
188 }
189
John McCallf6c8a4e2009-11-10 07:01:13 +0000190 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000191
John McCallf6c8a4e2009-11-10 07:01:13 +0000192 const_iterator begin() const { return list.begin(); }
193 const_iterator end() const { return list.end(); }
194
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000195 llvm::iterator_range<const_iterator>
John McCallf6c8a4e2009-11-10 07:01:13 +0000196 getNamespacesFor(DeclContext *DC) const {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000197 return llvm::make_range(std::equal_range(begin(), end(),
198 DC->getPrimaryContext(),
199 UnqualUsingEntry::Comparator()));
John McCallf6c8a4e2009-11-10 07:01:13 +0000200 }
201 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000202} // end anonymous namespace
Douglas Gregor889ceb72009-02-03 19:21:40 +0000203
Douglas Gregor889ceb72009-02-03 19:21:40 +0000204// Retrieve the set of identifier namespaces that correspond to a
205// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000206static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
207 bool CPlusPlus,
208 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000209 unsigned IDNS = 0;
210 switch (NameKind) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +0000211 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000212 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000213 case Sema::LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +0000214 case Sema::LookupLocalFriendName:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000215 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000216 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000217 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000218 if (Redeclaration)
219 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCallea305ed2009-12-18 10:40:03 +0000220 }
Richard Smith541b38b2013-09-20 01:15:31 +0000221 if (Redeclaration)
222 IDNS |= Decl::IDNS_LocalExtern;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000223 break;
224
John McCallb9467b62010-04-24 01:30:58 +0000225 case Sema::LookupOperatorName:
226 // Operator lookup is its own crazy thing; it is not the same
227 // as (e.g.) looking up an operator name for redeclaration.
228 assert(!Redeclaration && "cannot do redeclaration operator lookup");
229 IDNS = Decl::IDNS_NonMemberOperator;
230 break;
231
Douglas Gregor889ceb72009-02-03 19:21:40 +0000232 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000233 if (CPlusPlus) {
234 IDNS = Decl::IDNS_Type;
235
236 // When looking for a redeclaration of a tag name, we add:
237 // 1) TagFriend to find undeclared friend decls
238 // 2) Namespace because they can't "overload" with tag decls.
239 // 3) Tag because it includes class templates, which can't
240 // "overload" with tag decls.
241 if (Redeclaration)
242 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
243 } else {
244 IDNS = Decl::IDNS_Tag;
245 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000246 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000247
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000248 case Sema::LookupLabel:
249 IDNS = Decl::IDNS_Label;
250 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000251
Douglas Gregor889ceb72009-02-03 19:21:40 +0000252 case Sema::LookupMemberName:
253 IDNS = Decl::IDNS_Member;
254 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000255 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000256 break;
257
258 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000259 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
260 break;
261
Douglas Gregor889ceb72009-02-03 19:21:40 +0000262 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000263 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000264 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000265
John McCall84d87672009-12-10 09:41:52 +0000266 case Sema::LookupUsingDeclName:
Richard Smith83e78f52014-04-11 01:03:38 +0000267 assert(Redeclaration && "should only be used for redecl lookup");
268 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |
269 Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend |
270 Decl::IDNS_LocalExtern;
John McCall84d87672009-12-10 09:41:52 +0000271 break;
272
Douglas Gregor79947a22009-04-24 00:11:27 +0000273 case Sema::LookupObjCProtocolName:
274 IDNS = Decl::IDNS_ObjCProtocol;
275 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000276
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000277 case Sema::LookupOMPReductionName:
278 IDNS = Decl::IDNS_OMPReduction;
279 break;
280
Douglas Gregor39982192010-08-15 06:18:01 +0000281 case Sema::LookupAnyName:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000282 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor39982192010-08-15 06:18:01 +0000283 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
284 | Decl::IDNS_Type;
285 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000286 }
287 return IDNS;
288}
289
John McCallea305ed2009-12-18 10:40:03 +0000290void LookupResult::configure() {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000291 IDNS = getIDNS(LookupKind, getSema().getLangOpts().CPlusPlus,
John McCallea305ed2009-12-18 10:40:03 +0000292 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000293
Richard Smithbdd14642014-02-04 01:14:30 +0000294 // If we're looking for one of the allocation or deallocation
295 // operators, make sure that the implicitly-declared new and delete
296 // operators can be found.
297 switch (NameInfo.getName().getCXXOverloadedOperator()) {
298 case OO_New:
299 case OO_Delete:
300 case OO_Array_New:
301 case OO_Array_Delete:
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000302 getSema().DeclareGlobalNewDelete();
Richard Smithbdd14642014-02-04 01:14:30 +0000303 break;
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000304
Richard Smithbdd14642014-02-04 01:14:30 +0000305 default:
306 break;
307 }
Douglas Gregor15197662013-04-03 23:06:26 +0000308
Richard Smithbdd14642014-02-04 01:14:30 +0000309 // Compiler builtins are always visible, regardless of where they end
310 // up being declared.
311 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
312 if (unsigned BuiltinID = Id->getBuiltinID()) {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000313 if (!getSema().Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
Richard Smithbdd14642014-02-04 01:14:30 +0000314 AllowHidden = true;
Douglas Gregor15197662013-04-03 23:06:26 +0000315 }
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000316 }
John McCallea305ed2009-12-18 10:40:03 +0000317}
318
Alp Tokerc1086762013-12-07 13:51:35 +0000319bool LookupResult::sanity() const {
Richard Smithf97ad222014-04-01 18:33:50 +0000320 // This function is never called by NDEBUG builds.
John McCall19c1bfd2010-08-25 05:32:35 +0000321 assert(ResultKind != NotFound || Decls.size() == 0);
322 assert(ResultKind != Found || Decls.size() == 1);
323 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
324 (Decls.size() == 1 &&
325 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
326 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
327 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000328 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
329 Ambiguity == AmbiguousBaseSubobjectTypes)));
Craig Topperc3ec1492014-05-26 06:22:03 +0000330 assert((Paths != nullptr) == (ResultKind == Ambiguous &&
331 (Ambiguity == AmbiguousBaseSubobjectTypes ||
332 Ambiguity == AmbiguousBaseSubobjects)));
Alp Tokerc1086762013-12-07 13:51:35 +0000333 return true;
John McCall19c1bfd2010-08-25 05:32:35 +0000334}
John McCall19c1bfd2010-08-25 05:32:35 +0000335
John McCall9f3059a2009-10-09 21:13:30 +0000336// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000337void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000338 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000339}
340
Richard Smith3876cc82013-10-30 01:02:04 +0000341/// Get a representative context for a declaration such that two declarations
342/// will have the same context if they were found within the same scope.
Benjamin Kramerfc58b042013-11-01 11:50:55 +0000343static DeclContext *getContextForScopeMatching(Decl *D) {
Richard Smith3876cc82013-10-30 01:02:04 +0000344 // For function-local declarations, use that function as the context. This
345 // doesn't account for scopes within the function; the caller must deal with
346 // those.
347 DeclContext *DC = D->getLexicalDeclContext();
348 if (DC->isFunctionOrMethod())
349 return DC;
350
351 // Otherwise, look at the semantic context of the declaration. The
352 // declaration must have been found there.
353 return D->getDeclContext()->getRedeclContext();
354}
355
Richard Smith826711d2015-07-29 23:38:25 +0000356/// \brief Determine whether \p D is a better lookup result than \p Existing,
357/// given that they declare the same entity.
Richard Smithcd31b852015-08-22 21:37:34 +0000358static bool isPreferredLookupResult(Sema &S, Sema::LookupNameKind Kind,
Richard Smith826711d2015-07-29 23:38:25 +0000359 NamedDecl *D, NamedDecl *Existing) {
360 // When looking up redeclarations of a using declaration, prefer a using
361 // shadow declaration over any other declaration of the same entity.
362 if (Kind == Sema::LookupUsingDeclName && isa<UsingShadowDecl>(D) &&
363 !isa<UsingShadowDecl>(Existing))
364 return true;
365
366 auto *DUnderlying = D->getUnderlyingDecl();
367 auto *EUnderlying = Existing->getUnderlyingDecl();
368
Richard Smith990668b2015-11-12 22:04:34 +0000369 // If they have different underlying declarations, prefer a typedef over the
370 // original type (this happens when two type declarations denote the same
371 // type), per a generous reading of C++ [dcl.typedef]p3 and p4. The typedef
372 // might carry additional semantic information, such as an alignment override.
373 // However, per C++ [dcl.typedef]p5, when looking up a tag name, prefer a tag
374 // declaration over a typedef.
Richard Smith826711d2015-07-29 23:38:25 +0000375 if (DUnderlying->getCanonicalDecl() != EUnderlying->getCanonicalDecl()) {
376 assert(isa<TypeDecl>(DUnderlying) && isa<TypeDecl>(EUnderlying));
Richard Smith990668b2015-11-12 22:04:34 +0000377 bool HaveTag = isa<TagDecl>(EUnderlying);
378 bool WantTag = Kind == Sema::LookupTagName;
379 return HaveTag != WantTag;
Richard Smith826711d2015-07-29 23:38:25 +0000380 }
381
Richard Smithcd31b852015-08-22 21:37:34 +0000382 // Pick the function with more default arguments.
383 // FIXME: In the presence of ambiguous default arguments, we should keep both,
384 // so we can diagnose the ambiguity if the default argument is needed.
385 // See C++ [over.match.best]p3.
386 if (auto *DFD = dyn_cast<FunctionDecl>(DUnderlying)) {
387 auto *EFD = cast<FunctionDecl>(EUnderlying);
388 unsigned DMin = DFD->getMinRequiredArguments();
389 unsigned EMin = EFD->getMinRequiredArguments();
390 // If D has more default arguments, it is preferred.
391 if (DMin != EMin)
392 return DMin < EMin;
Richard Smith535ff802015-09-11 22:39:35 +0000393 // FIXME: When we track visibility for default function arguments, check
394 // that we pick the declaration with more visible default arguments.
Richard Smithcd31b852015-08-22 21:37:34 +0000395 }
396
397 // Pick the template with more default template arguments.
398 if (auto *DTD = dyn_cast<TemplateDecl>(DUnderlying)) {
399 auto *ETD = cast<TemplateDecl>(EUnderlying);
400 unsigned DMin = DTD->getTemplateParameters()->getMinRequiredArguments();
401 unsigned EMin = ETD->getTemplateParameters()->getMinRequiredArguments();
Richard Smith535ff802015-09-11 22:39:35 +0000402 // If D has more default arguments, it is preferred. Note that default
403 // arguments (and their visibility) is monotonically increasing across the
404 // redeclaration chain, so this is a quick proxy for "is more recent".
Richard Smithcd31b852015-08-22 21:37:34 +0000405 if (DMin != EMin)
406 return DMin < EMin;
Richard Smith535ff802015-09-11 22:39:35 +0000407 // If D has more *visible* default arguments, it is preferred. Note, an
408 // earlier default argument being visible does not imply that a later
409 // default argument is visible, so we can't just check the first one.
410 for (unsigned I = DMin, N = DTD->getTemplateParameters()->size();
411 I != N; ++I) {
412 if (!S.hasVisibleDefaultArgument(
413 ETD->getTemplateParameters()->getParam(I)) &&
414 S.hasVisibleDefaultArgument(
415 DTD->getTemplateParameters()->getParam(I)))
416 return true;
417 }
Richard Smithcd31b852015-08-22 21:37:34 +0000418 }
419
Vassil Vassilev4d75e8d2016-02-28 19:08:24 +0000420 // VarDecl can have incomplete array types, prefer the one with more complete
421 // array type.
422 if (VarDecl *DVD = dyn_cast<VarDecl>(DUnderlying)) {
423 VarDecl *EVD = cast<VarDecl>(EUnderlying);
424 if (EVD->getType()->isIncompleteType() &&
425 !DVD->getType()->isIncompleteType()) {
426 // Prefer the decl with a more complete type if visible.
427 return S.isVisible(DVD);
428 }
429 return false; // Avoid picking up a newer decl, just because it was newer.
430 }
431
Richard Smithcd31b852015-08-22 21:37:34 +0000432 // For most kinds of declaration, it doesn't really matter which one we pick.
433 if (!isa<FunctionDecl>(DUnderlying) && !isa<VarDecl>(DUnderlying)) {
434 // If the existing declaration is hidden, prefer the new one. Otherwise,
435 // keep what we've got.
436 return !S.isVisible(Existing);
437 }
438
439 // Pick the newer declaration; it might have a more precise type.
Richard Smith826711d2015-07-29 23:38:25 +0000440 for (Decl *Prev = DUnderlying->getPreviousDecl(); Prev;
441 Prev = Prev->getPreviousDecl())
442 if (Prev == EUnderlying)
443 return true;
Richard Smith826711d2015-07-29 23:38:25 +0000444 return false;
445}
446
Richard Smith990668b2015-11-12 22:04:34 +0000447/// Determine whether \p D can hide a tag declaration.
448static bool canHideTag(NamedDecl *D) {
449 // C++ [basic.scope.declarative]p4:
450 // Given a set of declarations in a single declarative region [...]
451 // exactly one declaration shall declare a class name or enumeration name
452 // that is not a typedef name and the other declarations shall all refer to
Richard Smith4eeaec42016-12-18 22:01:46 +0000453 // the same variable, non-static data member, or enumerator, or all refer
454 // to functions and function templates; in this case the class name or
455 // enumeration name is hidden.
Richard Smith990668b2015-11-12 22:04:34 +0000456 // C++ [basic.scope.hiding]p2:
457 // A class name or enumeration name can be hidden by the name of a
458 // variable, data member, function, or enumerator declared in the same
459 // scope.
Richard Smith4eeaec42016-12-18 22:01:46 +0000460 // An UnresolvedUsingValueDecl always instantiates to one of these.
Richard Smith990668b2015-11-12 22:04:34 +0000461 D = D->getUnderlyingDecl();
462 return isa<VarDecl>(D) || isa<EnumConstantDecl>(D) || isa<FunctionDecl>(D) ||
Richard Smith4eeaec42016-12-18 22:01:46 +0000463 isa<FunctionTemplateDecl>(D) || isa<FieldDecl>(D) ||
464 isa<UnresolvedUsingValueDecl>(D);
Richard Smith990668b2015-11-12 22:04:34 +0000465}
466
John McCall283b9012009-11-22 00:44:51 +0000467/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000468void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000469 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000470
John McCall9f3059a2009-10-09 21:13:30 +0000471 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000472 if (N == 0) {
Richard Smith826711d2015-07-29 23:38:25 +0000473 assert(ResultKind == NotFound ||
474 ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000475 return;
476 }
477
John McCall283b9012009-11-22 00:44:51 +0000478 // If there's a single decl, we need to examine it to decide what
479 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000480 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000481 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
482 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000483 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000484 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000485 ResultKind = FoundUnresolvedValue;
486 return;
487 }
John McCall9f3059a2009-10-09 21:13:30 +0000488
John McCall6538c932009-10-10 05:48:19 +0000489 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000490 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000491
Richard Smitha534a312015-07-21 23:54:07 +0000492 llvm::SmallDenseMap<NamedDecl*, unsigned, 16> Unique;
Richard Smith826711d2015-07-29 23:38:25 +0000493 llvm::SmallDenseMap<QualType, unsigned, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000494
John McCall9f3059a2009-10-09 21:13:30 +0000495 bool Ambiguous = false;
Richard Smith2dbe4042015-11-04 19:26:32 +0000496 bool HasTag = false, HasFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000497 bool HasFunctionTemplate = false, HasUnresolved = false;
Richard Smith2dbe4042015-11-04 19:26:32 +0000498 NamedDecl *HasNonFunction = nullptr;
499
500 llvm::SmallVector<NamedDecl*, 4> EquivalentNonFunctions;
John McCall9f3059a2009-10-09 21:13:30 +0000501
502 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000503
John McCall9f3059a2009-10-09 21:13:30 +0000504 unsigned I = 0;
505 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000506 NamedDecl *D = Decls[I]->getUnderlyingDecl();
507 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000508
Argyrios Kyrtzidis1fcd7fd2013-02-22 06:58:37 +0000509 // Ignore an invalid declaration unless it's the only one left.
Richard Smith5cd86f82015-11-03 03:13:11 +0000510 if (D->isInvalidDecl() && !(I == 0 && N == 1)) {
Argyrios Kyrtzidis1fcd7fd2013-02-22 06:58:37 +0000511 Decls[I] = Decls[--N];
512 continue;
513 }
514
Richard Smith826711d2015-07-29 23:38:25 +0000515 llvm::Optional<unsigned> ExistingI;
516
Douglas Gregor13e65872010-08-11 14:45:53 +0000517 // Redeclarations of types via typedef can occur both within a scope
518 // and, through using declarations and directives, across scopes. There is
519 // no ambiguity if they all refer to the same type, so unique based on the
520 // canonical type.
521 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
Richard Smith990668b2015-11-12 22:04:34 +0000522 QualType T = getSema().Context.getTypeDeclType(TD);
523 auto UniqueResult = UniqueTypes.insert(
524 std::make_pair(getSema().Context.getCanonicalType(T), I));
525 if (!UniqueResult.second) {
526 // The type is not unique.
527 ExistingI = UniqueResult.first->second;
Douglas Gregor13e65872010-08-11 14:45:53 +0000528 }
529 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000530
Richard Smith826711d2015-07-29 23:38:25 +0000531 // For non-type declarations, check for a prior lookup result naming this
532 // canonical declaration.
533 if (!ExistingI) {
534 auto UniqueResult = Unique.insert(std::make_pair(D, I));
535 if (!UniqueResult.second) {
536 // We've seen this entity before.
537 ExistingI = UniqueResult.first->second;
Richard Smitha534a312015-07-21 23:54:07 +0000538 }
Richard Smith826711d2015-07-29 23:38:25 +0000539 }
540
541 if (ExistingI) {
542 // This is not a unique lookup result. Pick one of the results and
543 // discard the other.
Richard Smithcd31b852015-08-22 21:37:34 +0000544 if (isPreferredLookupResult(getSema(), getLookupKind(), Decls[I],
Richard Smith826711d2015-07-29 23:38:25 +0000545 Decls[*ExistingI]))
546 Decls[*ExistingI] = Decls[I];
547 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000548 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000549 }
550
Douglas Gregor13e65872010-08-11 14:45:53 +0000551 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000552
Douglas Gregor13e65872010-08-11 14:45:53 +0000553 if (isa<UnresolvedUsingValueDecl>(D)) {
554 HasUnresolved = true;
555 } else if (isa<TagDecl>(D)) {
556 if (HasTag)
557 Ambiguous = true;
558 UniqueTagIndex = I;
559 HasTag = true;
560 } else if (isa<FunctionTemplateDecl>(D)) {
561 HasFunction = true;
562 HasFunctionTemplate = true;
563 } else if (isa<FunctionDecl>(D)) {
564 HasFunction = true;
565 } else {
Richard Smith2dbe4042015-11-04 19:26:32 +0000566 if (HasNonFunction) {
567 // If we're about to create an ambiguity between two declarations that
568 // are equivalent, but one is an internal linkage declaration from one
569 // module and the other is an internal linkage declaration from another
570 // module, just skip it.
571 if (getSema().isEquivalentInternalLinkageDeclaration(HasNonFunction,
572 D)) {
573 EquivalentNonFunctions.push_back(D);
574 Decls[I] = Decls[--N];
575 continue;
576 }
577
Douglas Gregor13e65872010-08-11 14:45:53 +0000578 Ambiguous = true;
Richard Smith2dbe4042015-11-04 19:26:32 +0000579 }
580 HasNonFunction = D;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000581 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000582 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000583 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000584
John McCall9f3059a2009-10-09 21:13:30 +0000585 // C++ [basic.scope.hiding]p2:
586 // A class name or enumeration name can be hidden by the name of
587 // an object, function, or enumerator declared in the same
588 // scope. If a class or enumeration name and an object, function,
589 // or enumerator are declared in the same scope (in any order)
590 // with the same name, the class or enumeration name is hidden
591 // wherever the object, function, or enumerator name is visible.
592 // But it's still an error if there are distinct tag types found,
593 // even if they're not visible. (ref?)
Richard Smith990668b2015-11-12 22:04:34 +0000594 if (N > 1 && HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000595 (HasFunction || HasNonFunction || HasUnresolved)) {
Richard Smith990668b2015-11-12 22:04:34 +0000596 NamedDecl *OtherDecl = Decls[UniqueTagIndex ? 0 : N - 1];
597 if (isa<TagDecl>(Decls[UniqueTagIndex]->getUnderlyingDecl()) &&
598 getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
599 getContextForScopeMatching(OtherDecl)) &&
600 canHideTag(OtherDecl))
Douglas Gregore63d0872010-10-23 16:06:17 +0000601 Decls[UniqueTagIndex] = Decls[--N];
602 else
603 Ambiguous = true;
604 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000605
Richard Smith2dbe4042015-11-04 19:26:32 +0000606 // FIXME: This diagnostic should really be delayed until we're done with
607 // the lookup result, in case the ambiguity is resolved by the caller.
608 if (!EquivalentNonFunctions.empty() && !Ambiguous)
609 getSema().diagnoseEquivalentInternalLinkageDeclarations(
610 getNameLoc(), HasNonFunction, EquivalentNonFunctions);
611
John McCall9f3059a2009-10-09 21:13:30 +0000612 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000613
John McCall80053822009-12-03 00:58:24 +0000614 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000615 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000616
John McCall9f3059a2009-10-09 21:13:30 +0000617 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000618 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000619 else if (HasUnresolved)
620 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000621 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000622 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000623 else
John McCall27b18f82009-11-17 02:14:36 +0000624 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000625}
626
John McCall5cebab12009-11-18 07:57:50 +0000627void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000628 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000629 for (I = P.begin(), E = P.end(); I != E; ++I)
David Blaikieff7d47a2012-12-19 00:45:41 +0000630 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
631 DE = I->Decls.end(); DI != DE; ++DI)
John McCall9f3059a2009-10-09 21:13:30 +0000632 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000633}
634
John McCall5cebab12009-11-18 07:57:50 +0000635void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000636 Paths = new CXXBasePaths;
637 Paths->swap(P);
638 addDeclsFromBasePaths(*Paths);
639 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000640 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000641}
642
John McCall5cebab12009-11-18 07:57:50 +0000643void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000644 Paths = new CXXBasePaths;
645 Paths->swap(P);
646 addDeclsFromBasePaths(*Paths);
647 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000648 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000649}
650
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000651void LookupResult::print(raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000652 Out << Decls.size() << " result(s)";
653 if (isAmbiguous()) Out << ", ambiguous";
654 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000655
John McCall9f3059a2009-10-09 21:13:30 +0000656 for (iterator I = begin(), E = end(); I != E; ++I) {
657 Out << "\n";
658 (*I)->print(Out, 2);
659 }
660}
661
Richard Smithba3a4f92016-01-12 21:59:26 +0000662LLVM_DUMP_METHOD void LookupResult::dump() {
663 llvm::errs() << "lookup results for " << getLookupName().getAsString()
664 << ":\n";
665 for (NamedDecl *D : *this)
666 D->dump();
667}
668
Douglas Gregord3a59182010-02-12 05:48:04 +0000669/// \brief Lookup a builtin function, when name lookup would otherwise
670/// fail.
671static bool LookupBuiltin(Sema &S, LookupResult &R) {
672 Sema::LookupNameKind NameKind = R.getLookupKind();
673
674 // If we didn't find a use of this identifier, and if the identifier
675 // corresponds to a compiler builtin, create the decl object for the builtin
676 // now, injecting it into translation unit scope, and return it.
677 if (NameKind == Sema::LookupOrdinaryName ||
678 NameKind == Sema::LookupRedeclarationWithLinkage) {
679 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
680 if (II) {
Eric Fiselier6ad68552016-07-01 01:24:09 +0000681 if (S.getLangOpts().CPlusPlus && NameKind == Sema::LookupOrdinaryName) {
682 if (II == S.getASTContext().getMakeIntegerSeqName()) {
683 R.addDecl(S.getASTContext().getMakeIntegerSeqDecl());
684 return true;
685 } else if (II == S.getASTContext().getTypePackElementName()) {
686 R.addDecl(S.getASTContext().getTypePackElementDecl());
687 return true;
688 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000689 }
Nico Webere1687c52013-06-20 21:44:55 +0000690
Douglas Gregord3a59182010-02-12 05:48:04 +0000691 // If this is a builtin on this (or all) targets, create the decl.
692 if (unsigned BuiltinID = II->getBuiltinID()) {
Anastasia Stulovab607e0f2016-02-02 11:29:43 +0000693 // In C++ and OpenCL (spec v1.2 s6.9.f), we don't have any predefined
694 // library functions like 'malloc'. Instead, we'll just error.
695 if ((S.getLangOpts().CPlusPlus || S.getLangOpts().OpenCL) &&
Douglas Gregord3a59182010-02-12 05:48:04 +0000696 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
697 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000698
699 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
700 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000701 R.isForRedeclaration(),
702 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000703 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000704 return true;
705 }
Douglas Gregord3a59182010-02-12 05:48:04 +0000706 }
707 }
708 }
709
710 return false;
711}
712
Douglas Gregor7454c562010-07-02 20:37:36 +0000713/// \brief Determine whether we can declare a special member function within
714/// the class at this point.
Richard Smith7d125a12012-11-27 21:20:31 +0000715static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +0000716 // We need to have a definition for the class.
717 if (!Class->getDefinition() || Class->isDependentContext())
718 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000719
Douglas Gregor7454c562010-07-02 20:37:36 +0000720 // We can't be in the middle of defining the class.
Richard Smith7d125a12012-11-27 21:20:31 +0000721 return !Class->isBeingDefined();
Douglas Gregor7454c562010-07-02 20:37:36 +0000722}
723
724void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smith7d125a12012-11-27 21:20:31 +0000725 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregora6d69502010-07-02 23:41:54 +0000726 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000727
728 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000729 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000730 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000731
Douglas Gregora6d69502010-07-02 23:41:54 +0000732 // If the copy constructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000733 if (Class->needsImplicitCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +0000734 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000735
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000736 // If the copy assignment operator has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000737 if (Class->needsImplicitCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000738 DeclareImplicitCopyAssignment(Class);
739
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000740 if (getLangOpts().CPlusPlus11) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000741 // If the move constructor has not yet been declared, do so now.
742 if (Class->needsImplicitMoveConstructor())
Richard Smitha87b7662016-05-13 18:48:05 +0000743 DeclareImplicitMoveConstructor(Class);
Sebastian Redl22653ba2011-08-30 19:58:05 +0000744
745 // If the move assignment operator has not yet been declared, do so now.
746 if (Class->needsImplicitMoveAssignment())
Richard Smitha87b7662016-05-13 18:48:05 +0000747 DeclareImplicitMoveAssignment(Class);
Sebastian Redl22653ba2011-08-30 19:58:05 +0000748 }
749
Douglas Gregor7454c562010-07-02 20:37:36 +0000750 // If the destructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000751 if (Class->needsImplicitDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000752 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000753}
754
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000755/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000756/// special member function.
757static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
758 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000759 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000760 case DeclarationName::CXXDestructorName:
761 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000762
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000763 case DeclarationName::CXXOperatorName:
764 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000765
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000766 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000767 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000768 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000769
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000770 return false;
771}
772
773/// \brief If there are any implicit member functions with the given name
774/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000775static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000776 DeclarationName Name,
777 const DeclContext *DC) {
778 if (!DC)
779 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000780
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000781 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000782 case DeclarationName::CXXConstructorName:
783 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith7d125a12012-11-27 21:20:31 +0000784 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000785 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000786 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000787 S.DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +0000788 if (Record->needsImplicitCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000789 S.DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000790 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000791 Record->needsImplicitMoveConstructor())
792 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000793 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000794 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000795
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000796 case DeclarationName::CXXDestructorName:
797 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith2be35f52012-12-01 02:35:44 +0000798 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smith7d125a12012-11-27 21:20:31 +0000799 CanDeclareSpecialMemberFunction(Record))
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000800 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000801 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000802
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000803 case DeclarationName::CXXOperatorName:
804 if (Name.getCXXOverloadedOperator() != OO_Equal)
805 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000806
Sebastian Redl22653ba2011-08-30 19:58:05 +0000807 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smith7d125a12012-11-27 21:20:31 +0000808 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000809 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smith2be35f52012-12-01 02:35:44 +0000810 if (Record->needsImplicitCopyAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000811 S.DeclareImplicitCopyAssignment(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000812 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000813 Record->needsImplicitMoveAssignment())
814 S.DeclareImplicitMoveAssignment(Class);
815 }
816 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000817 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000818
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000819 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000820 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000821 }
822}
Douglas Gregor7454c562010-07-02 20:37:36 +0000823
John McCall9f3059a2009-10-09 21:13:30 +0000824// Adds all qualifying matches for a name within a decl context to the
825// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000826static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000827 bool Found = false;
828
Douglas Gregor7454c562010-07-02 20:37:36 +0000829 // Lazily declare C++ special member functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000830 if (S.getLangOpts().CPlusPlus)
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000831 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000832
Douglas Gregor7454c562010-07-02 20:37:36 +0000833 // Perform lookup into this declaration context.
Richard Smithcf4bdde2015-02-21 02:45:19 +0000834 DeclContext::lookup_result DR = DC->lookup(R.getLookupName());
835 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E;
David Blaikieff7d47a2012-12-19 00:45:41 +0000836 ++I) {
John McCall401982f2010-01-20 21:53:11 +0000837 NamedDecl *D = *I;
Douglas Gregor4a814562011-12-14 16:03:29 +0000838 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000839 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000840 Found = true;
841 }
842 }
John McCall9f3059a2009-10-09 21:13:30 +0000843
Douglas Gregord3a59182010-02-12 05:48:04 +0000844 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
845 return true;
846
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000847 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000848 != DeclarationName::CXXConversionFunctionName ||
849 R.getLookupName().getCXXNameType()->isDependentType() ||
850 !isa<CXXRecordDecl>(DC))
851 return Found;
852
853 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000854 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000855 // name lookup. Instead, any conversion function templates visible in the
856 // context of the use are considered. [...]
857 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000858 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000859 return Found;
860
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +0000861 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
862 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruth3a693b72010-01-31 11:44:02 +0000863 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
864 if (!ConvTemplate)
865 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000866
Chandler Carruth3a693b72010-01-31 11:44:02 +0000867 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000868 // add the conversion function template. When we deduce template
869 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000870 // type of the new declaration with the type of the function template.
871 if (R.isForRedeclaration()) {
872 R.addDecl(ConvTemplate);
873 Found = true;
874 continue;
875 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000876
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000877 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000878 // [...] For each such operator, if argument deduction succeeds
879 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000880 // name lookup.
881 //
882 // When referencing a conversion function for any purpose other than
883 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000884 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000885 // specialization into the result set. We do this to avoid forcing all
886 // callers to perform special deduction for conversion functions.
Craig Toppere6706e42012-09-19 02:26:47 +0000887 TemplateDeductionInfo Info(R.getNameLoc());
Craig Topperc3ec1492014-05-26 06:22:03 +0000888 FunctionDecl *Specialization = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000889
890 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000891 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
892 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000893
Chandler Carruth3a693b72010-01-31 11:44:02 +0000894 // Compute the type of the function that we would expect the conversion
895 // function to have, if it were to match the name given.
896 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000897 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
Reid Kleckner78af0702013-08-27 23:08:25 +0000898 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
Richard Smith8acb4282014-07-31 21:57:55 +0000899 EPI.ExceptionSpec = EST_None;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000900 QualType ExpectedType
901 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000902 None, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000903
Chandler Carruth3a693b72010-01-31 11:44:02 +0000904 // Perform template argument deduction against the type that we would
905 // expect the function to have.
Craig Topperc3ec1492014-05-26 06:22:03 +0000906 if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
Chandler Carruth3a693b72010-01-31 11:44:02 +0000907 Specialization, Info)
908 == Sema::TDK_Success) {
909 R.addDecl(Specialization);
910 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000911 }
912 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000913
John McCall9f3059a2009-10-09 21:13:30 +0000914 return Found;
915}
916
John McCallf6c8a4e2009-11-10 07:01:13 +0000917// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000918static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000919CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000920 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000921
922 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
923
John McCallf6c8a4e2009-11-10 07:01:13 +0000924 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000925 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000926
John McCallf6c8a4e2009-11-10 07:01:13 +0000927 // Perform direct name lookup into the namespaces nominated by the
928 // using directives whose common ancestor is this namespace.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000929 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
930 if (LookupDirect(S, R, UUE.getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000931 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000932
933 R.resolveKind();
934
935 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000936}
937
938static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000939 if (DeclContext *Ctx = S->getEntity())
Douglas Gregor700792c2009-02-05 19:25:20 +0000940 return Ctx->isFileContext();
941 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000942}
Douglas Gregored8f2882009-01-30 01:04:22 +0000943
Douglas Gregor66230062010-03-15 14:33:29 +0000944// Find the next outer declaration context from this scope. This
945// routine actually returns the semantic outer context, which may
946// differ from the lexical context (encoded directly in the Scope
947// stack) when we are parsing a member of a class template. In this
948// case, the second element of the pair will be true, to indicate that
949// name lookup should continue searching in this semantic context when
950// it leaves the current template parameter scope.
951static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000952 DeclContext *DC = S->getEntity();
Craig Topperc3ec1492014-05-26 06:22:03 +0000953 DeclContext *Lexical = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000954 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000955 OuterS = OuterS->getParent()) {
956 if (OuterS->getEntity()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000957 Lexical = OuterS->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +0000958 break;
959 }
960 }
961
962 // C++ [temp.local]p8:
963 // In the definition of a member of a class template that appears
964 // outside of the namespace containing the class template
965 // definition, the name of a template-parameter hides the name of
966 // a member of this namespace.
967 //
968 // Example:
969 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000970 // namespace N {
971 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000972 //
973 // template<class T> class B {
974 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000975 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000976 // }
977 //
978 // template<class C> void N::B<C>::f(C) {
979 // C b; // C is the template parameter, not N::C
980 // }
981 //
982 // In this example, the lexical context we return is the
983 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000984 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000985 !S->getParent()->isTemplateParamScope())
986 return std::make_pair(Lexical, false);
987
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000988 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000989 // For the example, this is the scope for the template parameters of
990 // template<class C>.
991 Scope *OutermostTemplateScope = S->getParent();
992 while (OutermostTemplateScope->getParent() &&
993 OutermostTemplateScope->getParent()->isTemplateParamScope())
994 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000995
Douglas Gregor66230062010-03-15 14:33:29 +0000996 // Find the namespace context in which the original scope occurs. In
997 // the example, this is namespace N.
998 DeclContext *Semantic = DC;
999 while (!Semantic->isFileContext())
1000 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001001
Douglas Gregor66230062010-03-15 14:33:29 +00001002 // Find the declaration context just outside of the template
1003 // parameter scope. This is the context in which the template is
1004 // being lexically declaration (a namespace context). In the
1005 // example, this is the global scope.
1006 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
1007 Lexical->Encloses(Semantic))
1008 return std::make_pair(Semantic, true);
1009
1010 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +00001011}
1012
Richard Smith541b38b2013-09-20 01:15:31 +00001013namespace {
1014/// An RAII object to specify that we want to find block scope extern
1015/// declarations.
1016struct FindLocalExternScope {
1017 FindLocalExternScope(LookupResult &R)
1018 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
1019 Decl::IDNS_LocalExtern) {
1020 R.setFindLocalExtern(R.getIdentifierNamespace() & Decl::IDNS_Ordinary);
1021 }
1022 void restore() {
1023 R.setFindLocalExtern(OldFindLocalExtern);
1024 }
1025 ~FindLocalExternScope() {
1026 restore();
1027 }
1028 LookupResult &R;
1029 bool OldFindLocalExtern;
1030};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001031} // end anonymous namespace
Richard Smith541b38b2013-09-20 01:15:31 +00001032
John McCall27b18f82009-11-17 02:14:36 +00001033bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001034 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +00001035
1036 DeclarationName Name = R.getLookupName();
Richard Smith1c34fb72013-08-13 18:18:50 +00001037 Sema::LookupNameKind NameKind = R.getLookupKind();
John McCall27b18f82009-11-17 02:14:36 +00001038
Douglas Gregor330b9cf2010-07-02 21:50:04 +00001039 // If this is the name of an implicitly-declared special member function,
1040 // go through the scope stack to implicitly declare
1041 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
1042 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +00001043 if (DeclContext *DC = PreS->getEntity())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00001044 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
1045 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001046
Douglas Gregor330b9cf2010-07-02 21:50:04 +00001047 // Implicitly declare member functions with the name we're looking for, if in
1048 // fact we are in a scope where it matters.
1049
Douglas Gregor889ceb72009-02-03 19:21:40 +00001050 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +00001051 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +00001052 I = IdResolver.begin(Name),
1053 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001054
Douglas Gregor889ceb72009-02-03 19:21:40 +00001055 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001056 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +00001057 // ...During unqualified name lookup (3.4.1), the names appear as if
1058 // they were declared in the nearest enclosing namespace which contains
1059 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +00001060 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +00001061 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +00001062 //
1063 // For example:
1064 // namespace A { int i; }
1065 // void foo() {
1066 // int i;
1067 // {
1068 // using namespace A;
1069 // ++i; // finds local 'i', A::i appears at global scope
1070 // }
1071 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +00001072 //
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001073 UnqualUsingDirectiveSet UDirs;
1074 bool VisitedUsingDirectives = false;
Richard Smith1c34fb72013-08-13 18:18:50 +00001075 bool LeftStartingScope = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00001076 DeclContext *OutsideOfTemplateParamDC = nullptr;
Richard Smith541b38b2013-09-20 01:15:31 +00001077
1078 // When performing a scope lookup, we want to find local extern decls.
1079 FindLocalExternScope FindLocals(R);
1080
Douglas Gregor700792c2009-02-05 19:25:20 +00001081 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +00001082 DeclContext *Ctx = S->getEntity();
Olivier Goffart12b221982016-06-16 21:39:46 +00001083 bool SearchNamespaceScope = true;
Douglas Gregor889ceb72009-02-03 19:21:40 +00001084 // Check whether the IdResolver has anything in this scope.
John McCall48871652010-08-21 09:40:31 +00001085 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001086 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Olivier Goffart12b221982016-06-16 21:39:46 +00001087 if (NameKind == LookupRedeclarationWithLinkage &&
1088 !(*I)->isTemplateParameter()) {
1089 // If it's a template parameter, we still find it, so we can diagnose
1090 // the invalid redeclaration.
1091
Richard Smith1c34fb72013-08-13 18:18:50 +00001092 // Determine whether this (or a previous) declaration is
1093 // out-of-scope.
1094 if (!LeftStartingScope && !Initial->isDeclScope(*I))
1095 LeftStartingScope = true;
1096
1097 // If we found something outside of our starting scope that
Olivier Goffart12b221982016-06-16 21:39:46 +00001098 // does not have linkage, skip it.
1099 if (LeftStartingScope && !((*I)->hasLinkage())) {
Richard Smith1c34fb72013-08-13 18:18:50 +00001100 R.setShadowed();
1101 continue;
1102 }
Olivier Goffart12b221982016-06-16 21:39:46 +00001103 } else {
1104 // We found something in this scope, we should not look at the
1105 // namespace scope
1106 SearchNamespaceScope = false;
Richard Smith1c34fb72013-08-13 18:18:50 +00001107 }
Douglas Gregor4a814562011-12-14 16:03:29 +00001108 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001109 }
1110 }
Olivier Goffart12b221982016-06-16 21:39:46 +00001111 if (!SearchNamespaceScope) {
John McCall9f3059a2009-10-09 21:13:30 +00001112 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +00001113 if (S->isClassScope())
1114 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
1115 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +00001116 return true;
1117 }
1118
Richard Smith1c34fb72013-08-13 18:18:50 +00001119 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
Richard Smith114394f2013-08-09 04:35:01 +00001120 // C++11 [class.friend]p11:
1121 // If a friend declaration appears in a local class and the name
1122 // specified is an unqualified name, a prior declaration is
1123 // looked up without considering scopes that are outside the
1124 // innermost enclosing non-class scope.
1125 return false;
1126 }
1127
Douglas Gregor66230062010-03-15 14:33:29 +00001128 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1129 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1130 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001131 // found nothing, so look into the contexts between the
Douglas Gregor66230062010-03-15 14:33:29 +00001132 // lexical and semantic declaration contexts returned by
1133 // findOuterContext(). This implements the name lookup behavior
1134 // of C++ [temp.local]p8.
1135 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +00001136 OutsideOfTemplateParamDC = nullptr;
Douglas Gregor66230062010-03-15 14:33:29 +00001137 }
1138
1139 if (Ctx) {
1140 DeclContext *OuterCtx;
1141 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001142 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregor66230062010-03-15 14:33:29 +00001143 if (SearchAfterTemplateScope)
1144 OutsideOfTemplateParamDC = OuterCtx;
1145
Douglas Gregorea166062010-03-15 15:26:48 +00001146 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +00001147 // We do not directly look into transparent contexts, since
1148 // those entities will be found in the nearest enclosing
1149 // non-transparent context.
1150 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +00001151 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +00001152
1153 // We do not look directly into function or method contexts,
1154 // since all of the local variables and parameters of the
1155 // function/method are present within the Scope.
1156 if (Ctx->isFunctionOrMethod()) {
1157 // If we have an Objective-C instance method, look for ivars
1158 // in the corresponding interface.
1159 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
1160 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1161 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1162 ObjCInterfaceDecl *ClassDeclared;
1163 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001164 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +00001165 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001166 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1167 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +00001168 R.resolveKind();
1169 return true;
1170 }
1171 }
1172 }
1173 }
1174
1175 continue;
1176 }
1177
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001178 // If this is a file context, we need to perform unqualified name
1179 // lookup considering using directives.
1180 if (Ctx->isFileContext()) {
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001181 // If we haven't handled using directives yet, do so now.
1182 if (!VisitedUsingDirectives) {
1183 // Add using directives from this context up to the top level.
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001184 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1185 if (UCtx->isTransparentContext())
1186 continue;
1187
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001188 UDirs.visit(UCtx, UCtx);
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001189 }
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001190
1191 // Find the innermost file scope, so we can add using directives
1192 // from local scopes.
1193 Scope *InnermostFileScope = S;
1194 while (InnermostFileScope &&
1195 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1196 InnermostFileScope = InnermostFileScope->getParent();
1197 UDirs.visitScopeChain(Initial, InnermostFileScope);
1198
1199 UDirs.done();
1200
1201 VisitedUsingDirectives = true;
1202 }
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001203
1204 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1205 R.resolveKind();
1206 return true;
1207 }
1208
1209 continue;
1210 }
1211
Douglas Gregor7f737c02009-09-10 16:57:35 +00001212 // Perform qualified name lookup into this context.
1213 // FIXME: In some cases, we know that every name that could be found by
1214 // this qualified name lookup will also be on the identifier chain. For
1215 // example, inside a class without any base classes, we never need to
1216 // perform qualified lookup because all of the members are on top of the
1217 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001218 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +00001219 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +00001220 }
Douglas Gregor700792c2009-02-05 19:25:20 +00001221 }
Douglas Gregored8f2882009-01-30 01:04:22 +00001222 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001223
John McCallf6c8a4e2009-11-10 07:01:13 +00001224 // Stop if we ran out of scopes.
1225 // FIXME: This really, really shouldn't be happening.
1226 if (!S) return false;
1227
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001228 // If we are looking for members, no need to look into global/namespace scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00001229 if (NameKind == LookupMemberName)
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001230 return false;
1231
Douglas Gregor700792c2009-02-05 19:25:20 +00001232 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +00001233 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +00001234 //
Mike Stump87c57ac2009-05-16 07:39:55 +00001235 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1236 // don't build it for each lookup!
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001237 if (!VisitedUsingDirectives) {
1238 UDirs.visitScopeChain(Initial, S);
1239 UDirs.done();
1240 }
Richard Smith541b38b2013-09-20 01:15:31 +00001241
1242 // If we're not performing redeclaration lookup, do not look for local
1243 // extern declarations outside of a function scope.
1244 if (!R.isForRedeclaration())
1245 FindLocals.restore();
1246
Douglas Gregor700792c2009-02-05 19:25:20 +00001247 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +00001248 // Unqualified name lookup in C++ requires looking into scopes
1249 // that aren't strictly lexical, and therefore we walk through the
1250 // context as well as walking through the scopes.
1251 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001252 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +00001253 bool Found = false;
John McCall48871652010-08-21 09:40:31 +00001254 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001255 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001256 // We found something. Look for anything else in our scope
1257 // with this same name and in an acceptable identifier
1258 // namespace, so that we can construct an overload set if we
1259 // need to.
John McCall9f3059a2009-10-09 21:13:30 +00001260 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +00001261 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001262 }
1263 }
1264
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001265 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +00001266 R.resolveKind();
1267 return true;
1268 }
1269
Ted Kremenekc37877d2013-10-08 17:08:03 +00001270 DeclContext *Ctx = S->getEntity();
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001271 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1272 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1273 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001274 // found nothing, so look into the contexts between the
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001275 // lexical and semantic declaration contexts returned by
1276 // findOuterContext(). This implements the name lookup behavior
1277 // of C++ [temp.local]p8.
1278 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +00001279 OutsideOfTemplateParamDC = nullptr;
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001280 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001281
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001282 if (Ctx) {
1283 DeclContext *OuterCtx;
1284 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001285 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001286 if (SearchAfterTemplateScope)
1287 OutsideOfTemplateParamDC = OuterCtx;
1288
1289 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1290 // We do not directly look into transparent contexts, since
1291 // those entities will be found in the nearest enclosing
1292 // non-transparent context.
1293 if (Ctx->isTransparentContext())
1294 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001295
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001296 // If we have a context, and it's not a context stashed in the
1297 // template parameter scope for an out-of-line definition, also
1298 // look into that context.
Chandler Carruth6232e4d2016-11-04 06:16:09 +00001299 if (!(Found && S->isTemplateParamScope())) {
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001300 assert(Ctx->isFileContext() &&
1301 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001302
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001303 // Look into context considering using-directives.
1304 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1305 Found = true;
1306 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001307
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001308 if (Found) {
1309 R.resolveKind();
1310 return true;
1311 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001312
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001313 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1314 return false;
1315 }
1316 }
1317
Douglas Gregor3ce74932010-02-05 07:07:10 +00001318 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001319 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001320 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001321
John McCall9f3059a2009-10-09 21:13:30 +00001322 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001323}
1324
Richard Smith0e5d7b82013-07-25 23:08:39 +00001325/// \brief Find the declaration that a class temploid member specialization was
1326/// instantiated from, or the member itself if it is an explicit specialization.
1327static Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) {
1328 return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom();
1329}
1330
Richard Smith42413142015-05-15 20:05:43 +00001331Module *Sema::getOwningModule(Decl *Entity) {
1332 // If it's imported, grab its owning module.
1333 Module *M = Entity->getImportedOwningModule();
1334 if (M || !isa<NamedDecl>(Entity) || !cast<NamedDecl>(Entity)->isHidden())
1335 return M;
1336 assert(!Entity->isFromASTFile() &&
1337 "hidden entity from AST file has no owning module");
1338
Richard Smith87bb5692015-06-09 00:35:49 +00001339 if (!getLangOpts().ModulesLocalVisibility) {
1340 // If we're not tracking visibility locally, the only way a declaration
1341 // can be hidden and local is if it's hidden because it's parent is (for
1342 // instance, maybe this is a lazily-declared special member of an imported
1343 // class).
1344 auto *Parent = cast<NamedDecl>(Entity->getDeclContext());
Vassil Vassilevb4829e42016-09-13 10:38:26 +00001345 assert(Parent->isHidden() && "unexpectedly hidden decl");
Richard Smith87bb5692015-06-09 00:35:49 +00001346 return getOwningModule(Parent);
1347 }
1348
Richard Smith42413142015-05-15 20:05:43 +00001349 // It's local and hidden; grab or compute its owning module.
1350 M = Entity->getLocalOwningModule();
1351 if (M)
1352 return M;
1353
1354 if (auto *Containing =
1355 PP.getModuleContainingLocation(Entity->getLocation())) {
1356 M = Containing;
1357 } else if (Entity->isInvalidDecl() || Entity->getLocation().isInvalid()) {
1358 // Don't bother tracking visibility for invalid declarations with broken
1359 // locations.
1360 cast<NamedDecl>(Entity)->setHidden(false);
1361 } else {
1362 // We need to assign a module to an entity that exists outside of any
1363 // module, so that we can hide it from modules that we textually enter.
1364 // Invent a fake module for all such entities.
1365 if (!CachedFakeTopLevelModule) {
1366 CachedFakeTopLevelModule =
1367 PP.getHeaderSearchInfo().getModuleMap().findOrCreateModule(
1368 "<top-level>", nullptr, false, false).first;
1369
1370 auto &SrcMgr = PP.getSourceManager();
1371 SourceLocation StartLoc =
1372 SrcMgr.getLocForStartOfFile(SrcMgr.getMainFileID());
Richard Smithdc1f0422016-07-20 19:10:16 +00001373 auto &TopLevel = ModuleScopes.empty()
1374 ? VisibleModules
1375 : ModuleScopes[0].OuterVisibleModules;
Richard Smith42413142015-05-15 20:05:43 +00001376 TopLevel.setVisible(CachedFakeTopLevelModule, StartLoc);
1377 }
1378
1379 M = CachedFakeTopLevelModule;
1380 }
1381
1382 if (M)
1383 Entity->setLocalOwningModule(M);
1384 return M;
1385}
1386
Richard Smithd9ba2242015-05-07 03:54:19 +00001387void Sema::makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc) {
Richard Smith87bb5692015-06-09 00:35:49 +00001388 if (auto *M = PP.getModuleContainingLocation(Loc))
1389 Context.mergeDefinitionIntoModule(ND, M);
1390 else
1391 // We're not building a module; just make the definition visible.
1392 ND->setHidden(false);
Richard Smith63e09bf2015-06-17 20:39:41 +00001393
1394 // If ND is a template declaration, make the template parameters
1395 // visible too. They're not (necessarily) within a mergeable DeclContext.
1396 if (auto *TD = dyn_cast<TemplateDecl>(ND))
1397 for (auto *Param : *TD->getTemplateParameters())
1398 makeMergedDefinitionVisible(Param, Loc);
Richard Smithd9ba2242015-05-07 03:54:19 +00001399}
1400
Richard Smith0e5d7b82013-07-25 23:08:39 +00001401/// \brief Find the module in which the given declaration was defined.
Richard Smith42413142015-05-15 20:05:43 +00001402static Module *getDefiningModule(Sema &S, Decl *Entity) {
Richard Smith0e5d7b82013-07-25 23:08:39 +00001403 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1404 // If this function was instantiated from a template, the defining module is
1405 // the module containing the pattern.
1406 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1407 Entity = Pattern;
1408 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
Reid Klecknere7367d62014-10-14 20:28:40 +00001409 if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
1410 Entity = Pattern;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001411 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1412 if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo())
1413 Entity = getInstantiatedFrom(ED, MSInfo);
1414 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1415 // FIXME: Map from variable template specializations back to the template.
1416 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo())
1417 Entity = getInstantiatedFrom(VD, MSInfo);
1418 }
1419
1420 // Walk up to the containing context. That might also have been instantiated
1421 // from a template.
1422 DeclContext *Context = Entity->getDeclContext();
1423 if (Context->isFileContext())
Richard Smith42413142015-05-15 20:05:43 +00001424 return S.getOwningModule(Entity);
1425 return getDefiningModule(S, cast<Decl>(Context));
Richard Smith0e5d7b82013-07-25 23:08:39 +00001426}
1427
1428llvm::DenseSet<Module*> &Sema::getLookupModules() {
1429 unsigned N = ActiveTemplateInstantiations.size();
1430 for (unsigned I = ActiveTemplateInstantiationLookupModules.size();
1431 I != N; ++I) {
Richard Smith42413142015-05-15 20:05:43 +00001432 Module *M =
1433 getDefiningModule(*this, ActiveTemplateInstantiations[I].Entity);
Richard Smith0e5d7b82013-07-25 23:08:39 +00001434 if (M && !LookupModulesCache.insert(M).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00001435 M = nullptr;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001436 ActiveTemplateInstantiationLookupModules.push_back(M);
1437 }
1438 return LookupModulesCache;
1439}
1440
Richard Smith42413142015-05-15 20:05:43 +00001441bool Sema::hasVisibleMergedDefinition(NamedDecl *Def) {
1442 for (Module *Merged : Context.getModulesWithMergedDefinition(Def))
1443 if (isModuleVisible(Merged))
1444 return true;
1445 return false;
1446}
1447
Richard Smithe7bd6de2015-06-10 20:30:23 +00001448template<typename ParmDecl>
Richard Smith35c1df52015-06-17 20:16:32 +00001449static bool
1450hasVisibleDefaultArgument(Sema &S, const ParmDecl *D,
1451 llvm::SmallVectorImpl<Module *> *Modules) {
Richard Smithe7bd6de2015-06-10 20:30:23 +00001452 if (!D->hasDefaultArgument())
1453 return false;
1454
1455 while (D) {
1456 auto &DefaultArg = D->getDefaultArgStorage();
1457 if (!DefaultArg.isInherited() && S.isVisible(D))
1458 return true;
1459
Richard Smith63e09bf2015-06-17 20:39:41 +00001460 if (!DefaultArg.isInherited() && Modules) {
1461 auto *NonConstD = const_cast<ParmDecl*>(D);
1462 Modules->push_back(S.getOwningModule(NonConstD));
1463 const auto &Merged = S.Context.getModulesWithMergedDefinition(NonConstD);
1464 Modules->insert(Modules->end(), Merged.begin(), Merged.end());
1465 }
Richard Smith35c1df52015-06-17 20:16:32 +00001466
Richard Smithe7bd6de2015-06-10 20:30:23 +00001467 // If there was a previous default argument, maybe its parameter is visible.
1468 D = DefaultArg.getInheritedFrom();
1469 }
1470 return false;
1471}
1472
Richard Smith35c1df52015-06-17 20:16:32 +00001473bool Sema::hasVisibleDefaultArgument(const NamedDecl *D,
1474 llvm::SmallVectorImpl<Module *> *Modules) {
Richard Smithe7bd6de2015-06-10 20:30:23 +00001475 if (auto *P = dyn_cast<TemplateTypeParmDecl>(D))
Richard Smith35c1df52015-06-17 20:16:32 +00001476 return ::hasVisibleDefaultArgument(*this, P, Modules);
Richard Smithe7bd6de2015-06-10 20:30:23 +00001477 if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))
Richard Smith35c1df52015-06-17 20:16:32 +00001478 return ::hasVisibleDefaultArgument(*this, P, Modules);
1479 return ::hasVisibleDefaultArgument(*this, cast<TemplateTemplateParmDecl>(D),
1480 Modules);
Richard Smithe7bd6de2015-06-10 20:30:23 +00001481}
1482
Richard Smith6739a102016-05-05 00:56:12 +00001483bool Sema::hasVisibleMemberSpecialization(
1484 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1485 assert(isa<CXXRecordDecl>(D->getDeclContext()) &&
1486 "not a member specialization");
1487 for (auto *Redecl : D->redecls()) {
1488 // If the specialization is declared at namespace scope, then it's a member
1489 // specialization declaration. If it's lexically inside the class
1490 // definition then it was instantiated.
1491 //
1492 // FIXME: This is a hack. There should be a better way to determine this.
1493 // FIXME: What about MS-style explicit specializations declared within a
1494 // class definition?
1495 if (Redecl->getLexicalDeclContext()->isFileContext()) {
1496 auto *NonConstR = const_cast<NamedDecl*>(cast<NamedDecl>(Redecl));
1497
1498 if (isVisible(NonConstR))
1499 return true;
1500
1501 if (Modules) {
1502 Modules->push_back(getOwningModule(NonConstR));
1503 const auto &Merged = Context.getModulesWithMergedDefinition(NonConstR);
1504 Modules->insert(Modules->end(), Merged.begin(), Merged.end());
1505 }
1506 }
1507 }
1508
1509 return false;
1510}
1511
Richard Smith0e5d7b82013-07-25 23:08:39 +00001512/// \brief Determine whether a declaration is visible to name lookup.
1513///
1514/// This routine determines whether the declaration D is visible in the current
1515/// lookup context, taking into account the current template instantiation
1516/// stack. During template instantiation, a declaration is visible if it is
1517/// visible from a module containing any entity on the template instantiation
1518/// path (by instantiating a template, you allow it to see the declarations that
1519/// your module can see, including those later on in your module).
1520bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001521 assert(D->isHidden() && "should not call this: not in slow case");
Richard Smith5196a172015-08-24 03:38:11 +00001522 Module *DeclModule = nullptr;
1523
1524 if (SemaRef.getLangOpts().ModulesLocalVisibility) {
1525 DeclModule = SemaRef.getOwningModule(D);
1526 if (!DeclModule) {
1527 // getOwningModule() may have decided the declaration should not be hidden.
1528 assert(!D->isHidden() && "hidden decl not from a module");
Richard Smith42413142015-05-15 20:05:43 +00001529 return true;
Richard Smith5196a172015-08-24 03:38:11 +00001530 }
1531
1532 // If the owning module is visible, and the decl is not module private,
1533 // then the decl is visible too. (Module private is ignored within the same
1534 // top-level module.)
1535 if ((!D->isFromASTFile() || !D->isModulePrivate()) &&
1536 (SemaRef.isModuleVisible(DeclModule) ||
1537 SemaRef.hasVisibleMergedDefinition(D)))
Richard Smith42413142015-05-15 20:05:43 +00001538 return true;
1539 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001540
Richard Smithbe3980b2015-03-27 00:41:57 +00001541 // If this declaration is not at namespace scope nor module-private,
1542 // then it is visible if its lexical parent has a visible definition.
1543 DeclContext *DC = D->getLexicalDeclContext();
Richard Smith8df390f2016-09-08 23:14:54 +00001544 if (!D->isModulePrivate() && DC && !DC->isFileContext() &&
1545 !isa<LinkageSpecDecl>(DC) && !isa<ExportDecl>(DC)) {
Richard Smithc7d48d12015-05-20 17:50:35 +00001546 // For a parameter, check whether our current template declaration's
1547 // lexical context is visible, not whether there's some other visible
1548 // definition of it, because parameters aren't "within" the definition.
Vassil Vassilev714b81c2016-09-08 20:34:41 +00001549 //
1550 // In C++ we need to check for a visible definition due to ODR merging,
1551 // and in C we must not because each declaration of a function gets its own
1552 // set of declarations for tags in prototype scope.
1553 if ((D->isTemplateParameter() || isa<ParmVarDecl>(D)
1554 || (isa<FunctionDecl>(DC) && !SemaRef.getLangOpts().CPlusPlus))
Richard Smithc7d48d12015-05-20 17:50:35 +00001555 ? isVisible(SemaRef, cast<NamedDecl>(DC))
1556 : SemaRef.hasVisibleDefinition(cast<NamedDecl>(DC))) {
Richard Smith42413142015-05-15 20:05:43 +00001557 if (SemaRef.ActiveTemplateInstantiations.empty() &&
1558 // FIXME: Do something better in this case.
1559 !SemaRef.getLangOpts().ModulesLocalVisibility) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001560 // Cache the fact that this declaration is implicitly visible because
1561 // its parent has a visible definition.
1562 D->setHidden(false);
1563 }
1564 return true;
1565 }
1566 return false;
1567 }
1568
Richard Smith0e5d7b82013-07-25 23:08:39 +00001569 // Find the extra places where we need to look.
1570 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
1571 if (LookupModules.empty())
1572 return false;
1573
Richard Smith5196a172015-08-24 03:38:11 +00001574 if (!DeclModule) {
1575 DeclModule = SemaRef.getOwningModule(D);
1576 assert(DeclModule && "hidden decl not from a module");
1577 }
1578
Richard Smith0e5d7b82013-07-25 23:08:39 +00001579 // If our lookup set contains the decl's module, it's visible.
1580 if (LookupModules.count(DeclModule))
1581 return true;
1582
1583 // If the declaration isn't exported, it's not visible in any other module.
1584 if (D->isModulePrivate())
1585 return false;
1586
1587 // Check whether DeclModule is transitively exported to an import of
1588 // the lookup set.
Yaron Keren941ad902015-11-23 19:28:42 +00001589 return std::any_of(LookupModules.begin(), LookupModules.end(),
Yaron Keren4c31fcf2015-11-24 20:18:24 +00001590 [&](Module *M) { return M->isModuleVisible(DeclModule); });
Richard Smith0e5d7b82013-07-25 23:08:39 +00001591}
1592
Richard Smith42413142015-05-15 20:05:43 +00001593bool Sema::isVisibleSlow(const NamedDecl *D) {
1594 return LookupResult::isVisible(*this, const_cast<NamedDecl*>(D));
1595}
1596
Richard Smith10568d82015-11-17 03:02:41 +00001597bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) {
1598 for (auto *D : R) {
1599 if (isVisible(D))
1600 return true;
1601 }
1602 return New->isExternallyVisible();
1603}
1604
Douglas Gregor4a814562011-12-14 16:03:29 +00001605/// \brief Retrieve the visible declaration corresponding to D, if any.
1606///
1607/// This routine determines whether the declaration D is visible in the current
1608/// module, with the current imports. If not, it checks whether any
1609/// redeclaration of D is visible, and if so, returns that declaration.
Richard Smith0e5d7b82013-07-25 23:08:39 +00001610///
Douglas Gregor4a814562011-12-14 16:03:29 +00001611/// \returns D, or a visible previous declaration of D, whichever is more recent
1612/// and visible. If no declaration of D is visible, returns null.
Richard Smithe156254d2013-08-20 20:35:18 +00001613static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
1614 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
Richard Smith0e5d7b82013-07-25 23:08:39 +00001615
Aaron Ballman86c93902014-03-06 23:45:36 +00001616 for (auto RD : D->redecls()) {
Richard Smith4083e032016-02-17 21:52:44 +00001617 // Don't bother with extra checks if we already know this one isn't visible.
1618 if (RD == D)
1619 continue;
1620
Richard Smith6739a102016-05-05 00:56:12 +00001621 auto ND = cast<NamedDecl>(RD);
1622 // FIXME: This is wrong in the case where the previous declaration is not
1623 // visible in the same scope as D. This needs to be done much more
1624 // carefully.
1625 if (LookupResult::isVisible(SemaRef, ND))
1626 return ND;
Douglas Gregor4a814562011-12-14 16:03:29 +00001627 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001628
Craig Topperc3ec1492014-05-26 06:22:03 +00001629 return nullptr;
Douglas Gregor4a814562011-12-14 16:03:29 +00001630}
1631
Richard Smith6739a102016-05-05 00:56:12 +00001632bool Sema::hasVisibleDeclarationSlow(const NamedDecl *D,
1633 llvm::SmallVectorImpl<Module *> *Modules) {
1634 assert(!isVisible(D) && "not in slow case");
1635
1636 for (auto *Redecl : D->redecls()) {
1637 auto *NonConstR = const_cast<NamedDecl*>(cast<NamedDecl>(Redecl));
1638 if (isVisible(NonConstR))
1639 return true;
1640
1641 if (Modules) {
1642 Modules->push_back(getOwningModule(NonConstR));
1643 const auto &Merged = Context.getModulesWithMergedDefinition(NonConstR);
1644 Modules->insert(Modules->end(), Merged.begin(), Merged.end());
1645 }
1646 }
1647
1648 return false;
1649}
1650
Richard Smithe156254d2013-08-20 20:35:18 +00001651NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
Richard Smith4083e032016-02-17 21:52:44 +00001652 if (auto *ND = dyn_cast<NamespaceDecl>(D)) {
1653 // Namespaces are a bit of a special case: we expect there to be a lot of
1654 // redeclarations of some namespaces, all declarations of a namespace are
1655 // essentially interchangeable, all declarations are found by name lookup
1656 // if any is, and namespaces are never looked up during template
1657 // instantiation. So we benefit from caching the check in this case, and
1658 // it is correct to do so.
1659 auto *Key = ND->getCanonicalDecl();
1660 if (auto *Acceptable = getSema().VisibleNamespaceCache.lookup(Key))
1661 return Acceptable;
1662 auto *Acceptable =
1663 isVisible(getSema(), Key) ? Key : findAcceptableDecl(getSema(), Key);
1664 if (Acceptable)
1665 getSema().VisibleNamespaceCache.insert(std::make_pair(Key, Acceptable));
1666 return Acceptable;
1667 }
1668
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +00001669 return findAcceptableDecl(getSema(), D);
Richard Smithe156254d2013-08-20 20:35:18 +00001670}
1671
Douglas Gregor34074322009-01-14 22:20:51 +00001672/// @brief Perform unqualified name lookup starting from a given
1673/// scope.
1674///
1675/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1676/// used to find names within the current scope. For example, 'x' in
1677/// @code
1678/// int x;
1679/// int f() {
1680/// return x; // unqualified name look finds 'x' in the global scope
1681/// }
1682/// @endcode
1683///
1684/// Different lookup criteria can find different names. For example, a
1685/// particular scope can have both a struct and a function of the same
1686/// name, and each can be found by certain lookup criteria. For more
1687/// information about lookup criteria, see the documentation for the
1688/// class LookupCriteria.
1689///
1690/// @param S The scope from which unqualified name lookup will
1691/// begin. If the lookup criteria permits, name lookup may also search
1692/// in the parent scopes.
1693///
James Dennett91738ff2012-06-22 10:32:46 +00001694/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1695/// look up and the lookup kind), and is updated with the results of lookup
1696/// including zero or more declarations and possibly additional information
1697/// used to diagnose ambiguities.
Douglas Gregor34074322009-01-14 22:20:51 +00001698///
James Dennett91738ff2012-06-22 10:32:46 +00001699/// @returns \c true if lookup succeeded and false otherwise.
John McCall27b18f82009-11-17 02:14:36 +00001700bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1701 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001702 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001703
John McCall27b18f82009-11-17 02:14:36 +00001704 LookupNameKind NameKind = R.getLookupKind();
1705
David Blaikiebbafb8a2012-03-11 07:00:24 +00001706 if (!getLangOpts().CPlusPlus) {
Douglas Gregor34074322009-01-14 22:20:51 +00001707 // Unqualified name lookup in C/Objective-C is purely lexical, so
1708 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001709 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001710 // Find the nearest non-transparent declaration scope.
1711 while (!(S->getFlags() & Scope::DeclScope) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001712 (S->getEntity() && S->getEntity()->isTransparentContext()))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001713 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001714 }
1715
Richard Smith541b38b2013-09-20 01:15:31 +00001716 // When performing a scope lookup, we want to find local extern decls.
1717 FindLocalExternScope FindLocals(R);
1718
Douglas Gregor34074322009-01-14 22:20:51 +00001719 // Scan up the scope chain looking for a decl that matches this
1720 // identifier that is in the appropriate namespace. This search
1721 // should not take long, as shadowing of names is uncommon, and
1722 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001723 bool LeftStartingScope = false;
1724
Douglas Gregored8f2882009-01-30 01:04:22 +00001725 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001726 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001727 I != IEnd; ++I)
Richard Smith0e5d7b82013-07-25 23:08:39 +00001728 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001729 if (NameKind == LookupRedeclarationWithLinkage) {
1730 // Determine whether this (or a previous) declaration is
1731 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001732 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001733 LeftStartingScope = true;
1734
1735 // If we found something outside of our starting scope that
1736 // does not have linkage, skip it.
Richard Smith1c34fb72013-08-13 18:18:50 +00001737 if (LeftStartingScope && !((*I)->hasLinkage())) {
1738 R.setShadowed();
Douglas Gregoreddf4332009-02-24 20:03:32 +00001739 continue;
Richard Smith1c34fb72013-08-13 18:18:50 +00001740 }
Douglas Gregoreddf4332009-02-24 20:03:32 +00001741 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001742 else if (NameKind == LookupObjCImplicitSelfParam &&
1743 !isa<ImplicitParamDecl>(*I))
1744 continue;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001745
Douglas Gregor4a814562011-12-14 16:03:29 +00001746 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001747
Douglas Gregorb59643b2012-01-03 23:26:26 +00001748 // Check whether there are any other declarations with the same name
1749 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001750 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001751 // Find the scope in which this declaration was declared (if it
1752 // actually exists in a Scope).
1753 while (S && !S->isDeclScope(D))
1754 S = S->getParent();
1755
1756 // If the scope containing the declaration is the translation unit,
1757 // then we'll need to perform our checks based on the matching
1758 // DeclContexts rather than matching scopes.
1759 if (S && isNamespaceOrTranslationUnitScope(S))
Craig Topperc3ec1492014-05-26 06:22:03 +00001760 S = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001761
1762 // Compute the DeclContext, if we need it.
Craig Topperc3ec1492014-05-26 06:22:03 +00001763 DeclContext *DC = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001764 if (!S)
1765 DC = (*I)->getDeclContext()->getRedeclContext();
1766
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001767 IdentifierResolver::iterator LastI = I;
1768 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001769 if (S) {
1770 // Match based on scope.
1771 if (!S->isDeclScope(*LastI))
1772 break;
1773 } else {
1774 // Match based on DeclContext.
1775 DeclContext *LastDC
1776 = (*LastI)->getDeclContext()->getRedeclContext();
1777 if (!LastDC->Equals(DC))
1778 break;
1779 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001780
1781 // If the declaration is in the right namespace and visible, add it.
1782 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1783 R.addDecl(LastD);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001784 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001785
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001786 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001787 }
Richard Smith541b38b2013-09-20 01:15:31 +00001788
John McCall9f3059a2009-10-09 21:13:30 +00001789 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001790 }
Douglas Gregor34074322009-01-14 22:20:51 +00001791 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001792 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001793 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001794 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001795 }
1796
1797 // If we didn't find a use of this identifier, and if the identifier
1798 // corresponds to a compiler builtin, create the decl object for the builtin
1799 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001800 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1801 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001802
Axel Naumann016538a2011-02-24 16:47:47 +00001803 // If we didn't find a use of this identifier, the ExternalSource
1804 // may be able to handle the situation.
1805 // Note: some lookup failures are expected!
1806 // See e.g. R.isForRedeclaration().
1807 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001808}
1809
John McCall6538c932009-10-10 05:48:19 +00001810/// @brief Perform qualified name lookup in the namespaces nominated by
1811/// using directives by the given context.
1812///
1813/// C++98 [namespace.qual]p2:
James Dennett51a8d8b2012-06-19 21:05:49 +00001814/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6538c932009-10-10 05:48:19 +00001815/// (where X is the global namespace), let S be the set of all
1816/// declarations of m in X and in the transitive closure of all
1817/// namespaces nominated by using-directives in X and its used
1818/// namespaces, except that using-directives are ignored in any
1819/// namespace, including X, directly containing one or more
1820/// declarations of m. No namespace is searched more than once in
1821/// the lookup of a name. If S is the empty set, the program is
1822/// ill-formed. Otherwise, if S has exactly one member, or if the
1823/// context of the reference is a using-declaration
1824/// (namespace.udecl), S is the required set of declarations of
1825/// m. Otherwise if the use of m is not one that allows a unique
1826/// declaration to be chosen from S, the program is ill-formed.
James Dennett51a8d8b2012-06-19 21:05:49 +00001827///
John McCall6538c932009-10-10 05:48:19 +00001828/// C++98 [namespace.qual]p5:
1829/// During the lookup of a qualified namespace member name, if the
1830/// lookup finds more than one declaration of the member, and if one
1831/// declaration introduces a class name or enumeration name and the
1832/// other declarations either introduce the same object, the same
1833/// enumerator or a set of functions, the non-type name hides the
1834/// class or enumeration name if and only if the declarations are
1835/// from the same namespace; otherwise (the declarations are from
1836/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001837static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001838 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001839 assert(StartDC->isFileContext() && "start context is not a file context");
1840
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001841 DeclContext::udir_range UsingDirectives = StartDC->using_directives();
1842 if (UsingDirectives.begin() == UsingDirectives.end()) return false;
John McCall6538c932009-10-10 05:48:19 +00001843
1844 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001845 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001846 Visited.insert(StartDC);
1847
1848 // We have not yet looked into these namespaces, much less added
1849 // their "using-children" to the queue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001850 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001851
1852 // We have already looked into the initial namespace; seed the queue
1853 // with its using-children.
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001854 for (auto *I : UsingDirectives) {
1855 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +00001856 if (Visited.insert(ND).second)
John McCall6538c932009-10-10 05:48:19 +00001857 Queue.push_back(ND);
1858 }
1859
1860 // The easiest way to implement the restriction in [namespace.qual]p5
1861 // is to check whether any of the individual results found a tag
1862 // and, if so, to declare an ambiguity if the final result is not
1863 // a tag.
1864 bool FoundTag = false;
1865 bool FoundNonTag = false;
1866
John McCall5cebab12009-11-18 07:57:50 +00001867 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001868
1869 bool Found = false;
1870 while (!Queue.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001871 NamespaceDecl *ND = Queue.pop_back_val();
John McCall6538c932009-10-10 05:48:19 +00001872
1873 // We go through some convolutions here to avoid copying results
1874 // between LookupResults.
1875 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001876 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001877 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001878
1879 if (FoundDirect) {
1880 // First do any local hiding.
1881 DirectR.resolveKind();
1882
1883 // If the local result is a tag, remember that.
1884 if (DirectR.isSingleTagDecl())
1885 FoundTag = true;
1886 else
1887 FoundNonTag = true;
1888
1889 // Append the local results to the total results if necessary.
1890 if (UseLocal) {
1891 R.addAllDecls(LocalR);
1892 LocalR.clear();
1893 }
1894 }
1895
1896 // If we find names in this namespace, ignore its using directives.
1897 if (FoundDirect) {
1898 Found = true;
1899 continue;
1900 }
1901
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001902 for (auto I : ND->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00001903 NamespaceDecl *Nom = I->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +00001904 if (Visited.insert(Nom).second)
John McCall6538c932009-10-10 05:48:19 +00001905 Queue.push_back(Nom);
1906 }
1907 }
1908
1909 if (Found) {
1910 if (FoundTag && FoundNonTag)
1911 R.setAmbiguousQualifiedTagHiding();
1912 else
1913 R.resolveKind();
1914 }
1915
1916 return Found;
1917}
1918
Douglas Gregor39982192010-08-15 06:18:01 +00001919/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001920static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00001921 CXXBasePath &Path, DeclarationName Name) {
Douglas Gregor39982192010-08-15 06:18:01 +00001922 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001923
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00001924 Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00001925 return !Path.Decls.empty();
Douglas Gregor39982192010-08-15 06:18:01 +00001926}
1927
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001928/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001929/// static members, nested types, and enumerators.
1930template<typename InputIterator>
1931static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1932 Decl *D = (*First)->getUnderlyingDecl();
1933 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1934 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001935
Douglas Gregorc0d24902010-10-22 22:08:47 +00001936 if (isa<CXXMethodDecl>(D)) {
1937 // Determine whether all of the methods are static.
1938 bool AllMethodsAreStatic = true;
1939 for(; First != Last; ++First) {
1940 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001941
Douglas Gregorc0d24902010-10-22 22:08:47 +00001942 if (!isa<CXXMethodDecl>(D)) {
1943 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1944 break;
1945 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001946
Douglas Gregorc0d24902010-10-22 22:08:47 +00001947 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1948 AllMethodsAreStatic = false;
1949 break;
1950 }
1951 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001952
Douglas Gregorc0d24902010-10-22 22:08:47 +00001953 if (AllMethodsAreStatic)
1954 return true;
1955 }
1956
1957 return false;
1958}
1959
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001960/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001961///
1962/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1963/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001964/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001965///
1966/// Different lookup criteria can find different names. For example, a
1967/// particular scope can have both a struct and a function of the same
1968/// name, and each can be found by certain lookup criteria. For more
1969/// information about lookup criteria, see the documentation for the
1970/// class LookupCriteria.
1971///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001972/// \param R captures both the lookup criteria and any lookup results found.
1973///
1974/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001975/// search. If the lookup criteria permits, name lookup may also search
1976/// in the parent contexts or (for C++ classes) base classes.
1977///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001978/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001979/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001980///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001981/// \returns true if lookup succeeded, false if it failed.
1982bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1983 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001984 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001985
John McCall27b18f82009-11-17 02:14:36 +00001986 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001987 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001988
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001989 // Make sure that the declaration context is complete.
1990 assert((!isa<TagDecl>(LookupCtx) ||
1991 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00001992 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith7d137e32012-03-23 03:33:32 +00001993 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001994 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001995
Eugene Leviant0d8103e2015-11-18 12:48:05 +00001996 struct QualifiedLookupInScope {
1997 bool oldVal;
1998 DeclContext *Context;
1999 // Set flag in DeclContext informing debugger that we're looking for qualified name
2000 QualifiedLookupInScope(DeclContext *ctx) : Context(ctx) {
2001 oldVal = ctx->setUseQualifiedLookup();
2002 }
2003 ~QualifiedLookupInScope() {
2004 Context->setUseQualifiedLookup(oldVal);
2005 }
2006 } QL(LookupCtx);
2007
Douglas Gregord3a59182010-02-12 05:48:04 +00002008 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00002009 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00002010 if (isa<CXXRecordDecl>(LookupCtx))
2011 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00002012 return true;
2013 }
Douglas Gregor34074322009-01-14 22:20:51 +00002014
John McCall6538c932009-10-10 05:48:19 +00002015 // Don't descend into implied contexts for redeclarations.
2016 // C++98 [namespace.qual]p6:
2017 // In a declaration for a namespace member in which the
2018 // declarator-id is a qualified-id, given that the qualified-id
2019 // for the namespace member has the form
2020 // nested-name-specifier unqualified-id
2021 // the unqualified-id shall name a member of the namespace
2022 // designated by the nested-name-specifier.
2023 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00002024 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00002025 return false;
2026
John McCall27b18f82009-11-17 02:14:36 +00002027 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00002028 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00002029 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00002030
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002031 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00002032 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002033 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00002034 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00002035 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002036
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002037 // If we're performing qualified name lookup into a dependent class,
2038 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002039 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00002040 // template instantiation time (at which point all bases will be available)
2041 // or we have to fail.
2042 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
2043 LookupRec->hasAnyDependentBases()) {
2044 R.setNotFoundInCurrentInstantiation();
2045 return false;
2046 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002047
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002048 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00002049 CXXBasePaths Paths;
2050 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002051
2052 // Look for this member in our base classes
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00002053 bool (*BaseCallback)(const CXXBaseSpecifier *Specifier, CXXBasePath &Path,
2054 DeclarationName Name) = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00002055 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00002056 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00002057 case LookupOrdinaryName:
2058 case LookupMemberName:
2059 case LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +00002060 case LookupLocalFriendName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00002061 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
2062 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002063
Douglas Gregor36d1b142009-10-06 17:59:45 +00002064 case LookupTagName:
2065 BaseCallback = &CXXRecordDecl::FindTagMember;
2066 break;
John McCall84d87672009-12-10 09:41:52 +00002067
Douglas Gregor39982192010-08-15 06:18:01 +00002068 case LookupAnyName:
2069 BaseCallback = &LookupAnyMember;
2070 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002071
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002072 case LookupOMPReductionName:
2073 BaseCallback = &CXXRecordDecl::FindOMPReductionMember;
2074 break;
2075
John McCall84d87672009-12-10 09:41:52 +00002076 case LookupUsingDeclName:
2077 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002078
Douglas Gregor36d1b142009-10-06 17:59:45 +00002079 case LookupOperatorName:
2080 case LookupNamespaceName:
2081 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002082 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00002083 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00002084 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002085
Douglas Gregor36d1b142009-10-06 17:59:45 +00002086 case LookupNestedNameSpecifierName:
2087 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
2088 break;
2089 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002090
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00002091 DeclarationName Name = R.getLookupName();
2092 if (!LookupRec->lookupInBases(
2093 [=](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
2094 return BaseCallback(Specifier, Path, Name);
2095 },
2096 Paths))
John McCall9f3059a2009-10-09 21:13:30 +00002097 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002098
John McCall553c0792010-01-23 00:46:32 +00002099 R.setNamingClass(LookupRec);
2100
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002101 // C++ [class.member.lookup]p2:
2102 // [...] If the resulting set of declarations are not all from
2103 // sub-objects of the same type, or the set has a nonstatic member
2104 // and includes members from distinct sub-objects, there is an
2105 // ambiguity and the program is ill-formed. Otherwise that set is
2106 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002107 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00002108 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00002109 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002110
Douglas Gregor36d1b142009-10-06 17:59:45 +00002111 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002112 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00002113 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002114
John McCall401982f2010-01-20 21:53:11 +00002115 // Pick the best (i.e. most permissive i.e. numerically lowest) access
2116 // across all paths.
2117 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002118
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002119 // Determine whether we're looking at a distinct sub-object or not.
2120 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00002121 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002122 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
2123 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00002124 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002125 }
2126
Douglas Gregorc0d24902010-10-22 22:08:47 +00002127 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002128 != Context.getCanonicalType(PathElement.Base->getType())) {
2129 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00002130 // different types. If the declaration sets aren't the same, this
Nikola Smiljanic1c125682014-07-09 05:42:35 +00002131 // lookup is ambiguous.
David Blaikieff7d47a2012-12-19 00:45:41 +00002132 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00002133 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikieff7d47a2012-12-19 00:45:41 +00002134 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
2135 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002136
David Blaikieff7d47a2012-12-19 00:45:41 +00002137 while (FirstD != FirstPath->Decls.end() &&
2138 CurrentD != Path->Decls.end()) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00002139 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
2140 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
2141 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002142
Douglas Gregorc0d24902010-10-22 22:08:47 +00002143 ++FirstD;
2144 ++CurrentD;
2145 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002146
David Blaikieff7d47a2012-12-19 00:45:41 +00002147 if (FirstD == FirstPath->Decls.end() &&
2148 CurrentD == Path->Decls.end())
Douglas Gregorc0d24902010-10-22 22:08:47 +00002149 continue;
2150 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002151
John McCall9f3059a2009-10-09 21:13:30 +00002152 R.setAmbiguousBaseSubobjectTypes(Paths);
2153 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002154 }
2155
Douglas Gregorc0d24902010-10-22 22:08:47 +00002156 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002157 // We have a different subobject of the same type.
2158
2159 // C++ [class.member.lookup]p5:
2160 // A static member, a nested type or an enumerator defined in
2161 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00002162 // has more than one base class subobject of type T.
David Blaikieff7d47a2012-12-19 00:45:41 +00002163 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002164 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002165
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002166 // We have found a nonstatic member name in multiple, distinct
2167 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00002168 R.setAmbiguousBaseSubobjects(Paths);
2169 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002170 }
2171 }
2172
2173 // Lookup in a base class succeeded; return these results.
2174
Aaron Ballman1e606f42014-07-15 22:03:49 +00002175 for (auto *D : Paths.front().Decls) {
John McCall553c0792010-01-23 00:46:32 +00002176 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
2177 D->getAccess());
2178 R.addDecl(D, AS);
2179 }
John McCall9f3059a2009-10-09 21:13:30 +00002180 R.resolveKind();
2181 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00002182}
2183
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00002184/// \brief Performs qualified name lookup or special type of lookup for
2185/// "__super::" scope specifier.
2186///
2187/// This routine is a convenience overload meant to be called from contexts
2188/// that need to perform a qualified name lookup with an optional C++ scope
2189/// specifier that might require special kind of lookup.
2190///
2191/// \param R captures both the lookup criteria and any lookup results found.
2192///
2193/// \param LookupCtx The context in which qualified name lookup will
2194/// search.
2195///
2196/// \param SS An optional C++ scope-specifier.
2197///
2198/// \returns true if lookup succeeded, false if it failed.
2199bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2200 CXXScopeSpec &SS) {
2201 auto *NNS = SS.getScopeRep();
2202 if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
2203 return LookupInSuper(R, NNS->getAsRecordDecl());
2204 else
2205
2206 return LookupQualifiedName(R, LookupCtx);
2207}
2208
Douglas Gregor34074322009-01-14 22:20:51 +00002209/// @brief Performs name lookup for a name that was parsed in the
2210/// source code, and may contain a C++ scope specifier.
2211///
2212/// This routine is a convenience routine meant to be called from
2213/// contexts that receive a name and an optional C++ scope specifier
2214/// (e.g., "N::M::x"). It will then perform either qualified or
2215/// unqualified name lookup (with LookupQualifiedName or LookupName,
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002216/// respectively) on the given name and return those results. It will
2217/// perform a special type of lookup for "__super::" scope specifier.
Douglas Gregor34074322009-01-14 22:20:51 +00002218///
2219/// @param S The scope from which unqualified name lookup will
2220/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00002221///
Douglas Gregore861bac2009-08-25 22:51:20 +00002222/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00002223///
Douglas Gregore861bac2009-08-25 22:51:20 +00002224/// @param EnteringContext Indicates whether we are going to enter the
2225/// context of the scope-specifier SS (if present).
2226///
John McCall9f3059a2009-10-09 21:13:30 +00002227/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002228bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00002229 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00002230 if (SS && SS->isInvalid()) {
2231 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002232 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00002233 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00002234 }
Mike Stump11289f42009-09-09 15:08:12 +00002235
Douglas Gregore861bac2009-08-25 22:51:20 +00002236 if (SS && SS->isSet()) {
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002237 NestedNameSpecifier *NNS = SS->getScopeRep();
2238 if (NNS->getKind() == NestedNameSpecifier::Super)
2239 return LookupInSuper(R, NNS->getAsRecordDecl());
2240
Douglas Gregore861bac2009-08-25 22:51:20 +00002241 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00002242 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00002243 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00002244 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00002245 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002246
John McCall27b18f82009-11-17 02:14:36 +00002247 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00002248 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00002249 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002250
Douglas Gregore861bac2009-08-25 22:51:20 +00002251 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00002252 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00002253 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00002254 R.setNotFoundInCurrentInstantiation();
2255 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00002256 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00002257 }
2258
Mike Stump11289f42009-09-09 15:08:12 +00002259 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00002260 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00002261}
2262
Nikola Smiljanic67860242014-09-26 00:28:20 +00002263/// \brief Perform qualified name lookup into all base classes of the given
2264/// class.
2265///
2266/// \param R captures both the lookup criteria and any lookup results found.
2267///
2268/// \param Class The context in which qualified name lookup will
2269/// search. Name lookup will search in all base classes merging the results.
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002270///
2271/// @returns True if any decls were found (but possibly ambiguous)
2272bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
John McCallf4a1b772015-09-09 23:04:17 +00002273 // The access-control rules we use here are essentially the rules for
2274 // doing a lookup in Class that just magically skipped the direct
2275 // members of Class itself. That is, the naming class is Class, and the
2276 // access includes the access of the base.
Nikola Smiljanic67860242014-09-26 00:28:20 +00002277 for (const auto &BaseSpec : Class->bases()) {
2278 CXXRecordDecl *RD = cast<CXXRecordDecl>(
2279 BaseSpec.getType()->castAs<RecordType>()->getDecl());
2280 LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
2281 Result.setBaseObjectType(Context.getRecordType(Class));
2282 LookupQualifiedName(Result, RD);
John McCallf4a1b772015-09-09 23:04:17 +00002283
2284 // Copy the lookup results into the target, merging the base's access into
2285 // the path access.
2286 for (auto I = Result.begin(), E = Result.end(); I != E; ++I) {
2287 R.addDecl(I.getDecl(),
2288 CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(),
2289 I.getAccess()));
2290 }
2291
2292 Result.suppressDiagnostics();
Nikola Smiljanic67860242014-09-26 00:28:20 +00002293 }
2294
2295 R.resolveKind();
John McCallf4a1b772015-09-09 23:04:17 +00002296 R.setNamingClass(Class);
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002297
2298 return !R.empty();
Nikola Smiljanic67860242014-09-26 00:28:20 +00002299}
Douglas Gregor889ceb72009-02-03 19:21:40 +00002300
James Dennett41725122012-06-22 10:16:05 +00002301/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002302/// from name lookup.
2303///
James Dennett41725122012-06-22 10:16:05 +00002304/// \param Result The result of the ambiguous lookup to be diagnosed.
Serge Pavlov99292092013-08-29 07:23:24 +00002305void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002306 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
2307
John McCall27b18f82009-11-17 02:14:36 +00002308 DeclarationName Name = Result.getLookupName();
2309 SourceLocation NameLoc = Result.getNameLoc();
2310 SourceRange LookupRange = Result.getContextRange();
2311
John McCall6538c932009-10-10 05:48:19 +00002312 switch (Result.getAmbiguityKind()) {
2313 case LookupResult::AmbiguousBaseSubobjects: {
2314 CXXBasePaths *Paths = Result.getBasePaths();
2315 QualType SubobjectType = Paths->front().back().Base->getType();
2316 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
2317 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
2318 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002319
David Blaikieff7d47a2012-12-19 00:45:41 +00002320 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6538c932009-10-10 05:48:19 +00002321 while (isa<CXXMethodDecl>(*Found) &&
2322 cast<CXXMethodDecl>(*Found)->isStatic())
2323 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002324
John McCall6538c932009-10-10 05:48:19 +00002325 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
Serge Pavlov99292092013-08-29 07:23:24 +00002326 break;
John McCall6538c932009-10-10 05:48:19 +00002327 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00002328
John McCall6538c932009-10-10 05:48:19 +00002329 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00002330 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
2331 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002332
John McCall6538c932009-10-10 05:48:19 +00002333 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002334 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00002335 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
2336 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002337 Path != PathEnd; ++Path) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002338 Decl *D = Path->Decls.front();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002339 if (DeclsPrinted.insert(D).second)
2340 Diag(D->getLocation(), diag::note_ambiguous_member_found);
2341 }
Serge Pavlov99292092013-08-29 07:23:24 +00002342 break;
Douglas Gregor1c846b02009-01-16 00:38:09 +00002343 }
2344
John McCall6538c932009-10-10 05:48:19 +00002345 case LookupResult::AmbiguousTagHiding: {
2346 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00002347
Nick Lewycky4b81fc872015-10-18 20:32:12 +00002348 llvm::SmallPtrSet<NamedDecl*, 8> TagDecls;
John McCall6538c932009-10-10 05:48:19 +00002349
Aaron Ballman1e606f42014-07-15 22:03:49 +00002350 for (auto *D : Result)
2351 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
John McCall6538c932009-10-10 05:48:19 +00002352 TagDecls.insert(TD);
2353 Diag(TD->getLocation(), diag::note_hidden_tag);
2354 }
2355
Aaron Ballman1e606f42014-07-15 22:03:49 +00002356 for (auto *D : Result)
2357 if (!isa<TagDecl>(D))
2358 Diag(D->getLocation(), diag::note_hiding_object);
John McCall6538c932009-10-10 05:48:19 +00002359
2360 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00002361 LookupResult::Filter F = Result.makeFilter();
2362 while (F.hasNext()) {
2363 if (TagDecls.count(F.next()))
2364 F.erase();
2365 }
2366 F.done();
Serge Pavlov99292092013-08-29 07:23:24 +00002367 break;
John McCall6538c932009-10-10 05:48:19 +00002368 }
2369
2370 case LookupResult::AmbiguousReference: {
2371 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002372
Aaron Ballman1e606f42014-07-15 22:03:49 +00002373 for (auto *D : Result)
2374 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
Serge Pavlov99292092013-08-29 07:23:24 +00002375 break;
John McCall6538c932009-10-10 05:48:19 +00002376 }
Serge Pavlov99292092013-08-29 07:23:24 +00002377 }
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002378}
Douglas Gregore254f902009-02-04 00:32:51 +00002379
John McCallf24d7bb2010-05-28 18:45:08 +00002380namespace {
2381 struct AssociatedLookup {
John McCall7d8b0412012-08-24 20:38:34 +00002382 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallf24d7bb2010-05-28 18:45:08 +00002383 Sema::AssociatedNamespaceSet &Namespaces,
2384 Sema::AssociatedClassSet &Classes)
John McCall7d8b0412012-08-24 20:38:34 +00002385 : S(S), Namespaces(Namespaces), Classes(Classes),
2386 InstantiationLoc(InstantiationLoc) {
John McCallf24d7bb2010-05-28 18:45:08 +00002387 }
2388
2389 Sema &S;
2390 Sema::AssociatedNamespaceSet &Namespaces;
2391 Sema::AssociatedClassSet &Classes;
John McCall7d8b0412012-08-24 20:38:34 +00002392 SourceLocation InstantiationLoc;
John McCallf24d7bb2010-05-28 18:45:08 +00002393 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002394} // end anonymous namespace
John McCallf24d7bb2010-05-28 18:45:08 +00002395
Mike Stump11289f42009-09-09 15:08:12 +00002396static void
John McCallf24d7bb2010-05-28 18:45:08 +00002397addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00002398
Douglas Gregor8b895222010-04-30 07:08:38 +00002399static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
2400 DeclContext *Ctx) {
2401 // Add the associated namespace for this class.
2402
2403 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
2404 // be a locally scoped record.
2405
Sebastian Redlbd595762010-08-31 20:53:31 +00002406 // We skip out of inline namespaces. The innermost non-inline namespace
2407 // contains all names of all its nested inline namespaces anyway, so we can
2408 // replace the entire inline namespace tree with its root.
2409 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
2410 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00002411 Ctx = Ctx->getParent();
2412
John McCallc7e8e792009-08-07 22:18:02 +00002413 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00002414 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00002415}
Douglas Gregor197e5f72009-07-08 07:51:57 +00002416
Mike Stump11289f42009-09-09 15:08:12 +00002417// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00002418// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00002419static void
John McCallf24d7bb2010-05-28 18:45:08 +00002420addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2421 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002422 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00002423 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00002424 switch (Arg.getKind()) {
2425 case TemplateArgument::Null:
2426 break;
Mike Stump11289f42009-09-09 15:08:12 +00002427
Douglas Gregor197e5f72009-07-08 07:51:57 +00002428 case TemplateArgument::Type:
2429 // [...] the namespaces and classes associated with the types of the
2430 // template arguments provided for template type parameters (excluding
2431 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00002432 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00002433 break;
Mike Stump11289f42009-09-09 15:08:12 +00002434
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002435 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002436 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00002437 // [...] the namespaces in which any template template arguments are
2438 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00002439 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002440 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00002441 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002442 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002443 DeclContext *Ctx = ClassTemplate->getDeclContext();
2444 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002445 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002446 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002447 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002448 }
2449 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002450 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002451
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002452 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00002453 case TemplateArgument::Integral:
2454 case TemplateArgument::Expression:
Eli Friedmanb826a002012-09-26 02:36:12 +00002455 case TemplateArgument::NullPtr:
Mike Stump11289f42009-09-09 15:08:12 +00002456 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00002457 // associated namespaces. ]
2458 break;
Mike Stump11289f42009-09-09 15:08:12 +00002459
Douglas Gregor197e5f72009-07-08 07:51:57 +00002460 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00002461 for (const auto &P : Arg.pack_elements())
2462 addAssociatedClassesAndNamespaces(Result, P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002463 break;
2464 }
2465}
2466
Douglas Gregore254f902009-02-04 00:32:51 +00002467// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00002468// argument-dependent lookup with an argument of class type
2469// (C++ [basic.lookup.koenig]p2).
2470static void
John McCallf24d7bb2010-05-28 18:45:08 +00002471addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2472 CXXRecordDecl *Class) {
2473
2474 // Just silently ignore anything whose name is __va_list_tag.
2475 if (Class->getDeclName() == Result.S.VAListTagName)
2476 return;
2477
Douglas Gregore254f902009-02-04 00:32:51 +00002478 // C++ [basic.lookup.koenig]p2:
2479 // [...]
2480 // -- If T is a class type (including unions), its associated
2481 // classes are: the class itself; the class of which it is a
2482 // member, if any; and its direct and indirect base
2483 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00002484 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00002485
2486 // Add the class of which it is a member, if any.
2487 DeclContext *Ctx = Class->getDeclContext();
2488 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002489 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002490 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002491 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002492
Douglas Gregore254f902009-02-04 00:32:51 +00002493 // Add the class itself. If we've already seen this class, we don't
2494 // need to visit base classes.
Richard Smith594461f2014-03-14 22:07:27 +00002495 //
2496 // FIXME: That's not correct, we may have added this class only because it
2497 // was the enclosing class of another class, and in that case we won't have
2498 // added its base classes yet.
Richard Smith6642bb32016-03-24 19:12:22 +00002499 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00002500 return;
2501
Mike Stump11289f42009-09-09 15:08:12 +00002502 // -- If T is a template-id, its associated namespaces and classes are
2503 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002504 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00002505 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00002506 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00002507 // namespaces in which any template template arguments are defined; and
2508 // the classes in which any member templates used as template template
2509 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00002510 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00002511 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00002512 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2513 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2514 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002515 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002516 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002517 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002518
Douglas Gregor197e5f72009-07-08 07:51:57 +00002519 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2520 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00002521 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002522 }
Mike Stump11289f42009-09-09 15:08:12 +00002523
John McCall67da35c2010-02-04 22:26:26 +00002524 // Only recurse into base classes for complete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00002525 if (!Result.S.isCompleteType(Result.InstantiationLoc,
2526 Result.S.Context.getRecordType(Class)))
Richard Smith594461f2014-03-14 22:07:27 +00002527 return;
John McCall67da35c2010-02-04 22:26:26 +00002528
Douglas Gregore254f902009-02-04 00:32:51 +00002529 // Add direct and indirect base classes along with their associated
2530 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002531 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00002532 Bases.push_back(Class);
2533 while (!Bases.empty()) {
2534 // Pop this class off the stack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002535 Class = Bases.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002536
2537 // Visit the base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +00002538 for (const auto &Base : Class->bases()) {
2539 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00002540 // In dependent contexts, we do ADL twice, and the first time around,
2541 // the base type might be a dependent TemplateSpecializationType, or a
2542 // TemplateTypeParmType. If that happens, simply ignore it.
2543 // FIXME: If we want to support export, we probably need to add the
2544 // namespace of the template in a TemplateSpecializationType, or even
2545 // the classes and namespaces of known non-dependent arguments.
2546 if (!BaseType)
2547 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002548 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6642bb32016-03-24 19:12:22 +00002549 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00002550 // Find the associated namespace for this base class.
2551 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00002552 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00002553
2554 // Make sure we visit the bases of this base class.
2555 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2556 Bases.push_back(BaseDecl);
2557 }
2558 }
2559 }
2560}
2561
2562// \brief Add the associated classes and namespaces for
2563// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00002564// (C++ [basic.lookup.koenig]p2).
2565static void
John McCallf24d7bb2010-05-28 18:45:08 +00002566addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00002567 // C++ [basic.lookup.koenig]p2:
2568 //
2569 // For each argument type T in the function call, there is a set
2570 // of zero or more associated namespaces and a set of zero or more
2571 // associated classes to be considered. The sets of namespaces and
2572 // classes is determined entirely by the types of the function
2573 // arguments (and the namespace of any template template
2574 // argument). Typedef names and using-declarations used to specify
2575 // the types do not contribute to this set. The sets of namespaces
2576 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00002577
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002578 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00002579 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2580
Douglas Gregore254f902009-02-04 00:32:51 +00002581 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00002582 switch (T->getTypeClass()) {
2583
2584#define TYPE(Class, Base)
2585#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2586#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2587#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2588#define ABSTRACT_TYPE(Class, Base)
2589#include "clang/AST/TypeNodes.def"
2590 // T is canonical. We can also ignore dependent types because
2591 // we don't need to do ADL at the definition point, but if we
2592 // wanted to implement template export (or if we find some other
2593 // use for associated classes and namespaces...) this would be
2594 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00002595 break;
Douglas Gregore254f902009-02-04 00:32:51 +00002596
John McCall0af3d3b2010-05-28 06:08:54 +00002597 // -- If T is a pointer to U or an array of U, its associated
2598 // namespaces and classes are those associated with U.
2599 case Type::Pointer:
2600 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2601 continue;
2602 case Type::ConstantArray:
2603 case Type::IncompleteArray:
2604 case Type::VariableArray:
2605 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2606 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002607
John McCall0af3d3b2010-05-28 06:08:54 +00002608 // -- If T is a fundamental type, its associated sets of
2609 // namespaces and classes are both empty.
2610 case Type::Builtin:
2611 break;
2612
2613 // -- If T is a class type (including unions), its associated
2614 // classes are: the class itself; the class of which it is a
2615 // member, if any; and its direct and indirect base
2616 // classes. Its associated namespaces are the namespaces in
2617 // which its associated classes are defined.
2618 case Type::Record: {
Richard Smith82b8d4e2015-12-18 22:19:11 +00002619 CXXRecordDecl *Class =
2620 cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002621 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00002622 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00002623 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00002624
John McCall0af3d3b2010-05-28 06:08:54 +00002625 // -- If T is an enumeration type, its associated namespace is
2626 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002627 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00002628 // it has no associated class.
2629 case Type::Enum: {
2630 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002631
John McCall0af3d3b2010-05-28 06:08:54 +00002632 DeclContext *Ctx = Enum->getDeclContext();
2633 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002634 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002635
John McCall0af3d3b2010-05-28 06:08:54 +00002636 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002637 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00002638
John McCall0af3d3b2010-05-28 06:08:54 +00002639 break;
2640 }
2641
2642 // -- If T is a function type, its associated namespaces and
2643 // classes are those associated with the function parameter
2644 // types and those associated with the return type.
2645 case Type::FunctionProto: {
2646 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002647 for (const auto &Arg : Proto->param_types())
2648 Queue.push_back(Arg.getTypePtr());
John McCall0af3d3b2010-05-28 06:08:54 +00002649 // fallthrough
2650 }
2651 case Type::FunctionNoProto: {
2652 const FunctionType *FnType = cast<FunctionType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00002653 T = FnType->getReturnType().getTypePtr();
John McCall0af3d3b2010-05-28 06:08:54 +00002654 continue;
2655 }
2656
2657 // -- If T is a pointer to a member function of a class X, its
2658 // associated namespaces and classes are those associated
2659 // with the function parameter types and return type,
2660 // together with those associated with X.
2661 //
2662 // -- If T is a pointer to a data member of class X, its
2663 // associated namespaces and classes are those associated
2664 // with the member type together with those associated with
2665 // X.
2666 case Type::MemberPointer: {
2667 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2668
2669 // Queue up the class type into which this points.
2670 Queue.push_back(MemberPtr->getClass());
2671
2672 // And directly continue with the pointee type.
2673 T = MemberPtr->getPointeeType().getTypePtr();
2674 continue;
2675 }
2676
2677 // As an extension, treat this like a normal pointer.
2678 case Type::BlockPointer:
2679 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2680 continue;
2681
2682 // References aren't covered by the standard, but that's such an
2683 // obvious defect that we cover them anyway.
2684 case Type::LValueReference:
2685 case Type::RValueReference:
2686 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2687 continue;
2688
2689 // These are fundamental types.
2690 case Type::Vector:
2691 case Type::ExtVector:
2692 case Type::Complex:
2693 break;
2694
Richard Smith27d807c2013-04-30 13:56:41 +00002695 // Non-deduced auto types only get here for error cases.
2696 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00002697 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00002698 break;
2699
Douglas Gregor8e936662011-04-12 01:02:45 +00002700 // If T is an Objective-C object or interface type, or a pointer to an
2701 // object or interface type, the associated namespace is the global
2702 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002703 case Type::ObjCObject:
2704 case Type::ObjCInterface:
2705 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002706 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002707 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002708
2709 // Atomic types are just wrappers; use the associations of the
2710 // contained type.
2711 case Type::Atomic:
2712 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2713 continue;
Xiuli Pan9c14e282016-01-09 12:53:17 +00002714 case Type::Pipe:
2715 T = cast<PipeType>(T)->getElementType().getTypePtr();
2716 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002717 }
2718
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002719 if (Queue.empty())
2720 break;
2721 T = Queue.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002722 }
Douglas Gregore254f902009-02-04 00:32:51 +00002723}
2724
2725/// \brief Find the associated classes and namespaces for
2726/// argument-dependent lookup for a call with the given set of
2727/// arguments.
2728///
2729/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002730/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002731/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00002732void Sema::FindAssociatedClassesAndNamespaces(
2733 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2734 AssociatedNamespaceSet &AssociatedNamespaces,
2735 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002736 AssociatedNamespaces.clear();
2737 AssociatedClasses.clear();
2738
John McCall7d8b0412012-08-24 20:38:34 +00002739 AssociatedLookup Result(*this, InstantiationLoc,
2740 AssociatedNamespaces, AssociatedClasses);
John McCallf24d7bb2010-05-28 18:45:08 +00002741
Douglas Gregore254f902009-02-04 00:32:51 +00002742 // C++ [basic.lookup.koenig]p2:
2743 // For each argument type T in the function call, there is a set
2744 // of zero or more associated namespaces and a set of zero or more
2745 // associated classes to be considered. The sets of namespaces and
2746 // classes is determined entirely by the types of the function
2747 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002748 // argument).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002749 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregore254f902009-02-04 00:32:51 +00002750 Expr *Arg = Args[ArgIdx];
2751
2752 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002753 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002754 continue;
2755 }
2756
2757 // [...] In addition, if the argument is the name or address of a
2758 // set of overloaded functions and/or function templates, its
2759 // associated classes and namespaces are the union of those
2760 // associated with each of the members of the set: the namespace
2761 // in which the function or function template is defined and the
2762 // classes and namespaces associated with its (non-dependent)
2763 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002764 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002765 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002766 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002767 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002768
John McCallf24d7bb2010-05-28 18:45:08 +00002769 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2770 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002771
Aaron Ballman1e606f42014-07-15 22:03:49 +00002772 for (const auto *D : ULE->decls()) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002773 // Look through any using declarations to find the underlying function.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002774 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
Douglas Gregore254f902009-02-04 00:32:51 +00002775
2776 // Add the classes and namespaces associated with the parameter
2777 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002778 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002779 }
2780 }
2781}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002782
John McCall5cebab12009-11-18 07:57:50 +00002783NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002784 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002785 LookupNameKind NameKind,
2786 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002787 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002788 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002789 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002790}
2791
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002792/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002793ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002794 SourceLocation IdLoc,
2795 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002796 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002797 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002798 return cast_or_null<ObjCProtocolDecl>(D);
2799}
2800
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002801void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002802 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002803 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002804 // C++ [over.match.oper]p3:
2805 // -- The set of non-member candidates is the result of the
2806 // unqualified lookup of operator@ in the context of the
2807 // expression according to the usual rules for name lookup in
2808 // unqualified function calls (3.4.2) except that all member
Richard Smith100b24a2014-04-17 01:52:14 +00002809 // functions are ignored.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002810 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002811 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2812 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002813
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002814 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
Richard Smith100b24a2014-04-17 01:52:14 +00002815 Functions.append(Operators.begin(), Operators.end());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002816}
2817
Alexis Hunt1da39282011-06-24 02:11:39 +00002818Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002819 CXXSpecialMember SM,
2820 bool ConstArg,
2821 bool VolatileArg,
2822 bool RValueThis,
2823 bool ConstThis,
2824 bool VolatileThis) {
Richard Smith7d125a12012-11-27 21:20:31 +00002825 assert(CanDeclareSpecialMemberFunction(RD) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002826 "doing special member lookup into record that isn't fully complete");
Richard Smith7d125a12012-11-27 21:20:31 +00002827 RD = RD->getDefinition();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002828 if (RValueThis || ConstThis || VolatileThis)
2829 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2830 "constructors and destructors always have unqualified lvalue this");
2831 if (ConstArg || VolatileArg)
2832 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2833 "parameter-less special members can't have qualified arguments");
2834
2835 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002836 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002837 ID.AddInteger(SM);
2838 ID.AddInteger(ConstArg);
2839 ID.AddInteger(VolatileArg);
2840 ID.AddInteger(RValueThis);
2841 ID.AddInteger(ConstThis);
2842 ID.AddInteger(VolatileThis);
2843
2844 void *InsertPoint;
2845 SpecialMemberOverloadResult *Result =
2846 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2847
2848 // This was already cached
2849 if (Result)
2850 return Result;
2851
Alexis Huntba8e18d2011-06-07 00:11:58 +00002852 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2853 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002854 SpecialMemberCache.InsertNode(Result, InsertPoint);
2855
2856 if (SM == CXXDestructor) {
Richard Smith2be35f52012-12-01 02:35:44 +00002857 if (RD->needsImplicitDestructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002858 DeclareImplicitDestructor(RD);
2859 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002860 assert(DD && "record without a destructor");
2861 Result->setMethod(DD);
Richard Smith852265f2012-03-30 20:53:28 +00002862 Result->setKind(DD->isDeleted() ?
2863 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith83c478d2012-04-20 18:46:14 +00002864 SpecialMemberOverloadResult::Success);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002865 return Result;
2866 }
2867
Alexis Hunteef8ee02011-06-10 03:50:41 +00002868 // Prepare for overload resolution. Here we construct a synthetic argument
2869 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002870 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002871 DeclarationName Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002872 Expr *Arg = nullptr;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002873 unsigned NumArgs;
2874
Richard Smith83c478d2012-04-20 18:46:14 +00002875 QualType ArgType = CanTy;
2876 ExprValueKind VK = VK_LValue;
2877
Alexis Hunteef8ee02011-06-10 03:50:41 +00002878 if (SM == CXXDefaultConstructor) {
2879 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2880 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002881 if (RD->needsImplicitDefaultConstructor())
2882 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002883 } else {
2884 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2885 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smith2be35f52012-12-01 02:35:44 +00002886 if (RD->needsImplicitCopyConstructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002887 DeclareImplicitCopyConstructor(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002888 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002889 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002890 } else {
2891 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smith2be35f52012-12-01 02:35:44 +00002892 if (RD->needsImplicitCopyAssignment())
Alexis Hunt1da39282011-06-24 02:11:39 +00002893 DeclareImplicitCopyAssignment(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002894 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002895 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002896 }
2897
Alexis Hunteef8ee02011-06-10 03:50:41 +00002898 if (ConstArg)
2899 ArgType.addConst();
2900 if (VolatileArg)
2901 ArgType.addVolatile();
2902
2903 // This isn't /really/ specified by the standard, but it's implied
2904 // we should be working from an RValue in the case of move to ensure
2905 // that we prefer to bind to rvalue references, and an LValue in the
2906 // case of copy to ensure we don't bind to rvalue references.
2907 // Possibly an XValue is actually correct in the case of move, but
2908 // there is no semantic difference for class types in this restricted
2909 // case.
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002910 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002911 VK = VK_LValue;
2912 else
2913 VK = VK_RValue;
Richard Smith83c478d2012-04-20 18:46:14 +00002914 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00002915
Richard Smith83c478d2012-04-20 18:46:14 +00002916 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2917
2918 if (SM != CXXDefaultConstructor) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002919 NumArgs = 1;
Richard Smith83c478d2012-04-20 18:46:14 +00002920 Arg = &FakeArg;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002921 }
2922
2923 // Create the object argument
2924 QualType ThisTy = CanTy;
2925 if (ConstThis)
2926 ThisTy.addConst();
2927 if (VolatileThis)
2928 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002929 Expr::Classification Classification =
Richard Smith83c478d2012-04-20 18:46:14 +00002930 OpaqueValueExpr(SourceLocation(), ThisTy,
2931 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002932
2933 // Now we perform lookup on the name we computed earlier and do overload
2934 // resolution. Lookup is only performed directly into the class since there
2935 // will always be a (possibly implicit) declaration to shadow any others.
Richard Smith100b24a2014-04-17 01:52:14 +00002936 OverloadCandidateSet OCS(RD->getLocation(), OverloadCandidateSet::CSK_Normal);
David Blaikieff7d47a2012-12-19 00:45:41 +00002937 DeclContext::lookup_result R = RD->lookup(Name);
Richard Smith8c37ab52015-02-11 01:48:47 +00002938
2939 if (R.empty()) {
2940 // We might have no default constructor because we have a lambda's closure
2941 // type, rather than because there's some other declared constructor.
2942 // Every class has a copy/move constructor, copy/move assignment, and
2943 // destructor.
2944 assert(SM == CXXDefaultConstructor &&
2945 "lookup for a constructor or assignment operator was empty");
2946 Result->setMethod(nullptr);
2947 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
2948 return Result;
2949 }
Chandler Carruth7deaae72013-08-18 07:20:52 +00002950
2951 // Copy the candidates as our processing of them may load new declarations
2952 // from an external source and invalidate lookup_result.
2953 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2954
Richard Smith5179eb72016-06-28 19:03:57 +00002955 for (NamedDecl *CandDecl : Candidates) {
2956 if (CandDecl->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002957 continue;
2958
Richard Smith5179eb72016-06-28 19:03:57 +00002959 DeclAccessPair Cand = DeclAccessPair::make(CandDecl, AS_public);
2960 auto CtorInfo = getConstructorInfo(Cand);
2961 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand->getUnderlyingDecl())) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002962 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Richard Smith5179eb72016-06-28 19:03:57 +00002963 AddMethodCandidate(M, Cand, RD, ThisTy, Classification,
2964 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
2965 else if (CtorInfo)
2966 AddOverloadCandidate(CtorInfo.Constructor, CtorInfo.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002967 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt080709f2011-06-23 00:26:20 +00002968 else
Richard Smith5179eb72016-06-28 19:03:57 +00002969 AddOverloadCandidate(M, Cand, llvm::makeArrayRef(&Arg, NumArgs), OCS,
2970 true);
2971 } else if (FunctionTemplateDecl *Tmpl =
2972 dyn_cast<FunctionTemplateDecl>(Cand->getUnderlyingDecl())) {
2973 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2974 AddMethodTemplateCandidate(
2975 Tmpl, Cand, RD, nullptr, ThisTy, Classification,
George Burgess IVce6284b2017-01-28 02:19:40 +00002976 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Richard Smith5179eb72016-06-28 19:03:57 +00002977 else if (CtorInfo)
2978 AddTemplateOverloadCandidate(
2979 CtorInfo.ConstructorTmpl, CtorInfo.FoundDecl, nullptr,
2980 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
2981 else
2982 AddTemplateOverloadCandidate(
2983 Tmpl, Cand, nullptr, llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002984 } else {
Richard Smith5179eb72016-06-28 19:03:57 +00002985 assert(isa<UsingDecl>(Cand.getDecl()) &&
2986 "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002987 }
2988 }
2989
2990 OverloadCandidateSet::iterator Best;
2991 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2992 case OR_Success:
2993 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith83c478d2012-04-20 18:46:14 +00002994 Result->setKind(SpecialMemberOverloadResult::Success);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002995 break;
2996
2997 case OR_Deleted:
2998 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith852265f2012-03-30 20:53:28 +00002999 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00003000 break;
3001
3002 case OR_Ambiguous:
Craig Topperc3ec1492014-05-26 06:22:03 +00003003 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00003004 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
3005 break;
3006
Alexis Hunteef8ee02011-06-10 03:50:41 +00003007 case OR_No_Viable_Function:
Craig Topperc3ec1492014-05-26 06:22:03 +00003008 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00003009 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00003010 break;
3011 }
3012
3013 return Result;
3014}
3015
3016/// \brief Look up the default constructor for the given class.
3017CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00003018 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00003019 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
3020 false, false);
3021
3022 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00003023}
3024
Alexis Hunt491ec602011-06-21 23:42:56 +00003025/// \brief Look up the copying constructor for the given class.
3026CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith83c478d2012-04-20 18:46:14 +00003027 unsigned Quals) {
Alexis Hunt899bd442011-06-10 04:44:37 +00003028 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3029 "non-const, non-volatile qualifiers for copy ctor arg");
3030 SpecialMemberOverloadResult *Result =
3031 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
3032 Quals & Qualifiers::Volatile, false, false, false);
3033
Alexis Hunt899bd442011-06-10 04:44:37 +00003034 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
3035}
3036
Sebastian Redl22653ba2011-08-30 19:58:05 +00003037/// \brief Look up the moving constructor for the given class.
Richard Smith1c6461e2012-07-18 03:36:00 +00003038CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
3039 unsigned Quals) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003040 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00003041 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
3042 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003043
3044 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
3045}
3046
Douglas Gregor52b72822010-07-02 23:12:18 +00003047/// \brief Look up the constructors for the given class.
3048DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00003049 // If the implicit constructors have not yet been declared, do so now.
Richard Smith7d125a12012-11-27 21:20:31 +00003050 if (CanDeclareSpecialMemberFunction(Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00003051 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00003052 DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +00003053 if (Class->needsImplicitCopyConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00003054 DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003055 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00003056 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00003057 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003058
Douglas Gregor52b72822010-07-02 23:12:18 +00003059 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
3060 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
3061 return Class->lookup(Name);
3062}
3063
Alexis Hunt491ec602011-06-21 23:42:56 +00003064/// \brief Look up the copying assignment operator for the given class.
3065CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
3066 unsigned Quals, bool RValueThis,
Richard Smith83c478d2012-04-20 18:46:14 +00003067 unsigned ThisQuals) {
Alexis Hunt491ec602011-06-21 23:42:56 +00003068 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3069 "non-const, non-volatile qualifiers for copy assignment arg");
3070 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3071 "non-const, non-volatile qualifiers for copy assignment this");
3072 SpecialMemberOverloadResult *Result =
3073 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
3074 Quals & Qualifiers::Volatile, RValueThis,
3075 ThisQuals & Qualifiers::Const,
3076 ThisQuals & Qualifiers::Volatile);
3077
Alexis Hunt491ec602011-06-21 23:42:56 +00003078 return Result->getMethod();
3079}
3080
Sebastian Redl22653ba2011-08-30 19:58:05 +00003081/// \brief Look up the moving assignment operator for the given class.
3082CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith1c6461e2012-07-18 03:36:00 +00003083 unsigned Quals,
Sebastian Redl22653ba2011-08-30 19:58:05 +00003084 bool RValueThis,
3085 unsigned ThisQuals) {
3086 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3087 "non-const, non-volatile qualifiers for copy assignment this");
3088 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00003089 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
3090 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl22653ba2011-08-30 19:58:05 +00003091 ThisQuals & Qualifiers::Const,
3092 ThisQuals & Qualifiers::Volatile);
3093
3094 return Result->getMethod();
3095}
3096
Douglas Gregore71edda2010-07-01 22:47:18 +00003097/// \brief Look for the destructor of the given class.
3098///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00003099/// During semantic analysis, this routine should be used in lieu of
3100/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00003101///
3102/// \returns The destructor for this class.
3103CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00003104 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
3105 false, false, false,
3106 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00003107}
3108
Richard Smithbcc22fc2012-03-09 08:00:36 +00003109/// LookupLiteralOperator - Determine which literal operator should be used for
3110/// a user-defined literal, per C++11 [lex.ext].
3111///
3112/// Normal overload resolution is not used to select which literal operator to
3113/// call for a user-defined literal. Look up the provided literal operator name,
3114/// and filter the results to the appropriate set for the given argument types.
3115Sema::LiteralOperatorLookupResult
3116Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
3117 ArrayRef<QualType> ArgTys,
Richard Smithb8b41d32013-10-07 19:57:58 +00003118 bool AllowRaw, bool AllowTemplate,
3119 bool AllowStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003120 LookupName(R, S);
3121 assert(R.getResultKind() != LookupResult::Ambiguous &&
3122 "literal operator lookup can't be ambiguous");
3123
3124 // Filter the lookup results appropriately.
3125 LookupResult::Filter F = R.makeFilter();
3126
Richard Smithbcc22fc2012-03-09 08:00:36 +00003127 bool FoundRaw = false;
Richard Smithb8b41d32013-10-07 19:57:58 +00003128 bool FoundTemplate = false;
3129 bool FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003130 bool FoundExactMatch = false;
3131
3132 while (F.hasNext()) {
3133 Decl *D = F.next();
3134 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
3135 D = USD->getTargetDecl();
3136
Douglas Gregorc1970572013-04-10 05:18:00 +00003137 // If the declaration we found is invalid, skip it.
3138 if (D->isInvalidDecl()) {
3139 F.erase();
3140 continue;
3141 }
3142
Richard Smithb8b41d32013-10-07 19:57:58 +00003143 bool IsRaw = false;
3144 bool IsTemplate = false;
3145 bool IsStringTemplate = false;
3146 bool IsExactMatch = false;
3147
Richard Smithbcc22fc2012-03-09 08:00:36 +00003148 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3149 if (FD->getNumParams() == 1 &&
3150 FD->getParamDecl(0)->getType()->getAs<PointerType>())
3151 IsRaw = true;
Richard Smith550de452013-01-15 07:12:59 +00003152 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003153 IsExactMatch = true;
3154 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
3155 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
3156 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
3157 IsExactMatch = false;
3158 break;
3159 }
3160 }
3161 }
3162 }
Richard Smithb8b41d32013-10-07 19:57:58 +00003163 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
3164 TemplateParameterList *Params = FD->getTemplateParameters();
3165 if (Params->size() == 1)
3166 IsTemplate = true;
3167 else
3168 IsStringTemplate = true;
3169 }
Richard Smithbcc22fc2012-03-09 08:00:36 +00003170
3171 if (IsExactMatch) {
3172 FoundExactMatch = true;
Richard Smithb8b41d32013-10-07 19:57:58 +00003173 AllowRaw = false;
3174 AllowTemplate = false;
3175 AllowStringTemplate = false;
3176 if (FoundRaw || FoundTemplate || FoundStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003177 // Go through again and remove the raw and template decls we've
3178 // already found.
3179 F.restart();
Richard Smithb8b41d32013-10-07 19:57:58 +00003180 FoundRaw = FoundTemplate = FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003181 }
Richard Smithb8b41d32013-10-07 19:57:58 +00003182 } else if (AllowRaw && IsRaw) {
3183 FoundRaw = true;
3184 } else if (AllowTemplate && IsTemplate) {
3185 FoundTemplate = true;
3186 } else if (AllowStringTemplate && IsStringTemplate) {
3187 FoundStringTemplate = true;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003188 } else {
3189 F.erase();
3190 }
3191 }
3192
3193 F.done();
3194
3195 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
3196 // parameter type, that is used in preference to a raw literal operator
3197 // or literal operator template.
3198 if (FoundExactMatch)
3199 return LOLR_Cooked;
3200
3201 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
3202 // operator template, but not both.
3203 if (FoundRaw && FoundTemplate) {
3204 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
Alp Tokera2794f92014-01-22 07:29:52 +00003205 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
Richard Smithc2bebe92016-05-11 20:37:46 +00003206 NoteOverloadCandidate(*I, (*I)->getUnderlyingDecl()->getAsFunction());
Richard Smithbcc22fc2012-03-09 08:00:36 +00003207 return LOLR_Error;
3208 }
3209
3210 if (FoundRaw)
3211 return LOLR_Raw;
3212
3213 if (FoundTemplate)
3214 return LOLR_Template;
3215
Richard Smithb8b41d32013-10-07 19:57:58 +00003216 if (FoundStringTemplate)
3217 return LOLR_StringTemplate;
3218
Richard Smithbcc22fc2012-03-09 08:00:36 +00003219 // Didn't find anything we could use.
3220 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
3221 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
Richard Smithb8b41d32013-10-07 19:57:58 +00003222 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
3223 << (AllowTemplate || AllowStringTemplate);
Richard Smithbcc22fc2012-03-09 08:00:36 +00003224 return LOLR_Error;
3225}
3226
John McCall8fe68082010-01-26 07:16:45 +00003227void ADLResult::insert(NamedDecl *New) {
3228 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
3229
3230 // If we haven't yet seen a decl for this key, or the last decl
3231 // was exactly this one, we're done.
Craig Topperc3ec1492014-05-26 06:22:03 +00003232 if (Old == nullptr || Old == New) {
John McCall8fe68082010-01-26 07:16:45 +00003233 Old = New;
3234 return;
3235 }
3236
3237 // Otherwise, decide which is a more recent redeclaration.
Alp Tokera2794f92014-01-22 07:29:52 +00003238 FunctionDecl *OldFD = Old->getAsFunction();
3239 FunctionDecl *NewFD = New->getAsFunction();
John McCall8fe68082010-01-26 07:16:45 +00003240
3241 FunctionDecl *Cursor = NewFD;
3242 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00003243 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00003244
3245 // If we got to the end without finding OldFD, OldFD is the newer
3246 // declaration; leave things as they are.
3247 if (!Cursor) return;
3248
3249 // If we do find OldFD, then NewFD is newer.
3250 if (Cursor == OldFD) break;
3251
3252 // Otherwise, keep looking.
3253 }
3254
3255 Old = New;
3256}
3257
Richard Smith100b24a2014-04-17 01:52:14 +00003258void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3259 ArrayRef<Expr *> Args, ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003260 // Find all of the associated namespaces and classes based on the
3261 // arguments we have.
3262 AssociatedNamespaceSet AssociatedNamespaces;
3263 AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00003264 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCallc7e8e792009-08-07 22:18:02 +00003265 AssociatedNamespaces,
3266 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003267
3268 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003269 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3270 // and let Y be the lookup set produced by argument dependent
3271 // lookup (defined as follows). If X contains [...] then Y is
3272 // empty. Otherwise Y is the set of declarations found in the
3273 // namespaces associated with the argument types as described
3274 // below. The set of declarations found by the lookup of the name
3275 // is the union of X and Y.
3276 //
3277 // Here, we compute Y and add its members to the overloaded
3278 // candidate set.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003279 for (auto *NS : AssociatedNamespaces) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003280 // When considering an associated namespace, the lookup is the
3281 // same as the lookup performed when the associated namespace is
3282 // used as a qualifier (3.4.3.2) except that:
3283 //
3284 // -- Any using-directives in the associated namespace are
3285 // ignored.
3286 //
John McCallc7e8e792009-08-07 22:18:02 +00003287 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003288 // associated classes are visible within their respective
3289 // namespaces even if they are not visible during an ordinary
3290 // lookup (11.4).
Aaron Ballman1e606f42014-07-15 22:03:49 +00003291 DeclContext::lookup_result R = NS->lookup(Name);
3292 for (auto *D : R) {
John McCallaa74a0c2009-08-28 07:59:38 +00003293 // If the only declaration here is an ordinary friend, consider
3294 // it only if it was declared in an associated classes.
Richard Smith541b38b2013-09-20 01:15:31 +00003295 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) {
3296 // If it's neither ordinarily visible nor a friend, we can't find it.
3297 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0)
3298 continue;
3299
Richard Smith64017682013-07-17 23:53:16 +00003300 bool DeclaredInAssociatedClass = false;
3301 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
3302 DeclContext *LexDC = DI->getLexicalDeclContext();
3303 if (isa<CXXRecordDecl>(LexDC) &&
Richard Smith82b8d4e2015-12-18 22:19:11 +00003304 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)) &&
3305 isVisible(cast<NamedDecl>(DI))) {
Richard Smith64017682013-07-17 23:53:16 +00003306 DeclaredInAssociatedClass = true;
3307 break;
3308 }
3309 }
3310 if (!DeclaredInAssociatedClass)
John McCalld1e9d832009-08-11 06:59:38 +00003311 continue;
3312 }
Mike Stump11289f42009-09-09 15:08:12 +00003313
John McCall91f61fc2010-01-26 06:04:06 +00003314 if (isa<UsingShadowDecl>(D))
3315 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00003316
Richard Smith100b24a2014-04-17 01:52:14 +00003317 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D))
John McCall8fe68082010-01-26 07:16:45 +00003318 continue;
3319
Richard Smitha1431072015-06-12 01:32:13 +00003320 if (!isVisible(D) && !(D = findAcceptableDecl(*this, D)))
3321 continue;
3322
John McCall8fe68082010-01-26 07:16:45 +00003323 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00003324 }
3325 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003326}
Douglas Gregor2d435302009-12-30 17:04:44 +00003327
3328//----------------------------------------------------------------------------
3329// Search for all visible declarations.
3330//----------------------------------------------------------------------------
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00003331VisibleDeclConsumer::~VisibleDeclConsumer() { }
Douglas Gregor2d435302009-12-30 17:04:44 +00003332
Richard Smithe156254d2013-08-20 20:35:18 +00003333bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
3334
Douglas Gregor2d435302009-12-30 17:04:44 +00003335namespace {
3336
3337class ShadowContextRAII;
3338
3339class VisibleDeclsRecord {
3340public:
3341 /// \brief An entry in the shadow map, which is optimized to store a
3342 /// single declaration (the common case) but can also store a list
3343 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00003344 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00003345
3346private:
3347 /// \brief A mapping from declaration names to the declarations that have
3348 /// this name within a particular scope.
3349 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
3350
3351 /// \brief A list of shadow maps, which is used to model name hiding.
3352 std::list<ShadowMap> ShadowMaps;
3353
3354 /// \brief The declaration contexts we have already visited.
3355 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
3356
3357 friend class ShadowContextRAII;
3358
3359public:
3360 /// \brief Determine whether we have already visited this context
3361 /// (and, if not, note that we are going to visit that context now).
3362 bool visitedContext(DeclContext *Ctx) {
David Blaikie82e95a32014-11-19 07:49:47 +00003363 return !VisitedContexts.insert(Ctx).second;
Douglas Gregor2d435302009-12-30 17:04:44 +00003364 }
3365
Douglas Gregor39982192010-08-15 06:18:01 +00003366 bool alreadyVisitedContext(DeclContext *Ctx) {
3367 return VisitedContexts.count(Ctx);
3368 }
3369
Douglas Gregor2d435302009-12-30 17:04:44 +00003370 /// \brief Determine whether the given declaration is hidden in the
3371 /// current scope.
3372 ///
3373 /// \returns the declaration that hides the given declaration, or
3374 /// NULL if no such declaration exists.
3375 NamedDecl *checkHidden(NamedDecl *ND);
3376
3377 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00003378 void add(NamedDecl *ND) {
3379 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
3380 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003381};
3382
3383/// \brief RAII object that records when we've entered a shadow context.
3384class ShadowContextRAII {
3385 VisibleDeclsRecord &Visible;
3386
3387 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
3388
3389public:
3390 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
Benjamin Kramer3204b152015-05-29 19:42:19 +00003391 Visible.ShadowMaps.emplace_back();
Douglas Gregor2d435302009-12-30 17:04:44 +00003392 }
3393
3394 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00003395 Visible.ShadowMaps.pop_back();
3396 }
3397};
3398
3399} // end anonymous namespace
3400
Douglas Gregor2d435302009-12-30 17:04:44 +00003401NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
3402 unsigned IDNS = ND->getIdentifierNamespace();
3403 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
3404 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3405 SM != SMEnd; ++SM) {
3406 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
3407 if (Pos == SM->end())
3408 continue;
3409
Aaron Ballman1e606f42014-07-15 22:03:49 +00003410 for (auto *D : Pos->second) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003411 // A tag declaration does not hide a non-tag declaration.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003412 if (D->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003413 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00003414 Decl::IDNS_ObjCProtocol)))
3415 continue;
3416
3417 // Protocols are in distinct namespaces from everything else.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003418 if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor2d435302009-12-30 17:04:44 +00003419 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Aaron Ballman1e606f42014-07-15 22:03:49 +00003420 D->getIdentifierNamespace() != IDNS)
Douglas Gregor2d435302009-12-30 17:04:44 +00003421 continue;
3422
Douglas Gregor09bbc652010-01-14 15:47:35 +00003423 // Functions and function templates in the same scope overload
3424 // rather than hide. FIXME: Look for hiding based on function
3425 // signatures!
Aaron Ballman1e606f42014-07-15 22:03:49 +00003426 if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Alp Tokera2794f92014-01-22 07:29:52 +00003427 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00003428 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00003429 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003430
Alex Lorenze7e8f802017-01-23 17:23:23 +00003431 // A shadow declaration that's created by a resolved using declaration
3432 // is not hidden by the same using declaration.
3433 if (isa<UsingShadowDecl>(ND) && isa<UsingDecl>(D) &&
3434 cast<UsingShadowDecl>(ND)->getUsingDecl() == D)
3435 continue;
3436
Douglas Gregor2d435302009-12-30 17:04:44 +00003437 // We've found a declaration that hides this one.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003438 return D;
Douglas Gregor2d435302009-12-30 17:04:44 +00003439 }
3440 }
3441
Craig Topperc3ec1492014-05-26 06:22:03 +00003442 return nullptr;
Douglas Gregor2d435302009-12-30 17:04:44 +00003443}
3444
3445static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
3446 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003447 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00003448 VisibleDeclConsumer &Consumer,
3449 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00003450 if (!Ctx)
3451 return;
3452
Douglas Gregor2d435302009-12-30 17:04:44 +00003453 // Make sure we don't visit the same context twice.
3454 if (Visited.visitedContext(Ctx->getPrimaryContext()))
3455 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003456
Richard Smith9e2341d2015-03-23 03:25:59 +00003457 // Outside C++, lookup results for the TU live on identifiers.
3458 if (isa<TranslationUnitDecl>(Ctx) &&
3459 !Result.getSema().getLangOpts().CPlusPlus) {
3460 auto &S = Result.getSema();
3461 auto &Idents = S.Context.Idents;
3462
3463 // Ensure all external identifiers are in the identifier table.
3464 if (IdentifierInfoLookup *External = Idents.getExternalIdentifierLookup()) {
3465 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
3466 for (StringRef Name = Iter->Next(); !Name.empty(); Name = Iter->Next())
3467 Idents.get(Name);
3468 }
3469
3470 // Walk all lookup results in the TU for each identifier.
3471 for (const auto &Ident : Idents) {
3472 for (auto I = S.IdResolver.begin(Ident.getValue()),
3473 E = S.IdResolver.end();
3474 I != E; ++I) {
3475 if (S.IdResolver.isDeclInScope(*I, Ctx)) {
3476 if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
3477 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3478 Visited.add(ND);
3479 }
3480 }
3481 }
3482 }
3483
3484 return;
3485 }
3486
Douglas Gregor7454c562010-07-02 20:37:36 +00003487 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3488 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3489
Douglas Gregor2d435302009-12-30 17:04:44 +00003490 // Enumerate all of the results in this context.
Richard Trieu20abd6b2015-04-15 03:48:48 +00003491 for (DeclContextLookupResult R : Ctx->lookups()) {
Richard Smith9e2341d2015-03-23 03:25:59 +00003492 for (auto *D : R) {
3493 if (auto *ND = Result.getAcceptableDecl(D)) {
3494 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3495 Visited.add(ND);
Douglas Gregora3b23b02010-12-09 21:44:02 +00003496 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003497 }
3498 }
3499
3500 // Traverse using directives for qualified name lookup.
3501 if (QualifiedNameLookup) {
3502 ShadowContextRAII Shadow(Visited);
Aaron Ballman804a7fb2014-03-17 17:14:12 +00003503 for (auto I : Ctx->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00003504 LookupVisibleDecls(I->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003505 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003506 }
3507 }
3508
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003509 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00003510 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00003511 if (!Record->hasDefinition())
3512 return;
3513
Aaron Ballman574705e2014-03-13 15:41:46 +00003514 for (const auto &B : Record->bases()) {
3515 QualType BaseType = B.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003516
Douglas Gregor2d435302009-12-30 17:04:44 +00003517 // Don't look into dependent bases, because name lookup can't look
3518 // there anyway.
3519 if (BaseType->isDependentType())
3520 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003521
Douglas Gregor2d435302009-12-30 17:04:44 +00003522 const RecordType *Record = BaseType->getAs<RecordType>();
3523 if (!Record)
3524 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003525
Douglas Gregor2d435302009-12-30 17:04:44 +00003526 // FIXME: It would be nice to be able to determine whether referencing
3527 // a particular member would be ambiguous. For example, given
3528 //
3529 // struct A { int member; };
3530 // struct B { int member; };
3531 // struct C : A, B { };
3532 //
3533 // void f(C *c) { c->### }
3534 //
3535 // accessing 'member' would result in an ambiguity. However, we
3536 // could be smart enough to qualify the member with the base
3537 // class, e.g.,
3538 //
3539 // c->B::member
3540 //
3541 // or
3542 //
3543 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003544
Douglas Gregor2d435302009-12-30 17:04:44 +00003545 // Find results in this base class (and its bases).
3546 ShadowContextRAII Shadow(Visited);
3547 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003548 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003549 }
3550 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003551
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003552 // Traverse the contexts of Objective-C classes.
3553 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3554 // Traverse categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003555 for (auto *Cat : IFace->visible_categories()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003556 ShadowContextRAII Shadow(Visited);
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003557 LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003558 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003559 }
3560
3561 // Traverse protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003562 for (auto *I : IFace->all_referenced_protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003563 ShadowContextRAII Shadow(Visited);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003564 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003565 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003566 }
3567
3568 // Traverse the superclass.
3569 if (IFace->getSuperClass()) {
3570 ShadowContextRAII Shadow(Visited);
3571 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003572 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003573 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003574
Douglas Gregor0b59e802010-04-19 18:02:19 +00003575 // If there is an implementation, traverse it. We do this to find
3576 // synthesized ivars.
3577 if (IFace->getImplementation()) {
3578 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003579 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky13668f22012-04-03 20:26:45 +00003580 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor0b59e802010-04-19 18:02:19 +00003581 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003582 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003583 for (auto *I : Protocol->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003584 ShadowContextRAII Shadow(Visited);
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003585 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003586 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003587 }
3588 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003589 for (auto *I : Category->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003590 ShadowContextRAII Shadow(Visited);
Aaron Ballman19a41762014-03-14 12:55:57 +00003591 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003592 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003593 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003594
Douglas Gregor0b59e802010-04-19 18:02:19 +00003595 // If there is an implementation, traverse it.
3596 if (Category->getImplementation()) {
3597 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003598 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00003599 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003600 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003601 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003602}
3603
3604static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3605 UnqualUsingDirectiveSet &UDirs,
3606 VisibleDeclConsumer &Consumer,
3607 VisibleDeclsRecord &Visited) {
3608 if (!S)
3609 return;
3610
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003611 if (!S->getEntity() ||
3612 (!S->getParent() &&
Ted Kremenekc37877d2013-10-08 17:08:03 +00003613 !Visited.alreadyVisitedContext(S->getEntity())) ||
3614 (S->getEntity())->isFunctionOrMethod()) {
Richard Smith541b38b2013-09-20 01:15:31 +00003615 FindLocalExternScope FindLocals(Result);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003616 // Walk through the declarations in this Scope.
Aaron Ballman35c54952014-03-17 16:55:25 +00003617 for (auto *D : S->decls()) {
3618 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Douglas Gregor4a814562011-12-14 16:03:29 +00003619 if ((ND = Result.getAcceptableDecl(ND))) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003620 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003621 Visited.add(ND);
3622 }
3623 }
3624 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003625
Douglas Gregor66230062010-03-15 14:33:29 +00003626 // FIXME: C++ [temp.local]p8
Craig Topperc3ec1492014-05-26 06:22:03 +00003627 DeclContext *Entity = nullptr;
Douglas Gregor4f248632010-01-01 17:44:25 +00003628 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003629 // Look into this scope's declaration context, along with any of its
3630 // parent lookup contexts (e.g., enclosing classes), up to the point
3631 // where we hit the context stored in the next outer scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00003632 Entity = S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00003633 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003634
Douglas Gregorea166062010-03-15 15:26:48 +00003635 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00003636 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003637 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3638 if (Method->isInstanceMethod()) {
3639 // For instance methods, look for ivars in the method's interface.
3640 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3641 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003642 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003643 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Richard Smithe156254d2013-08-20 20:35:18 +00003644 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003645 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003646 }
3647
3648 // We've already performed all of the name lookup that we need
3649 // to for Objective-C methods; the next context will be the
3650 // outer scope.
3651 break;
3652 }
3653
Douglas Gregor2d435302009-12-30 17:04:44 +00003654 if (Ctx->isFunctionOrMethod())
3655 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003656
3657 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003658 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003659 }
3660 } else if (!S->getParent()) {
3661 // Look into the translation unit scope. We walk through the translation
3662 // unit's declaration context, because the Scope itself won't have all of
3663 // the declarations if we loaded a precompiled header.
3664 // FIXME: We would like the translation unit's Scope object to point to the
3665 // translation unit, so we don't need this special "if" branch. However,
3666 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003667 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00003668 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003669 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00003670 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003671 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003672 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003673 }
3674
Douglas Gregor2d435302009-12-30 17:04:44 +00003675 if (Entity) {
3676 // Lookup visible declarations in any namespaces found by using
3677 // directives.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003678 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
3679 LookupVisibleDecls(const_cast<DeclContext *>(UUE.getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003680 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003681 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003682 }
3683
3684 // Lookup names in the parent scope.
3685 ShadowContextRAII Shadow(Visited);
3686 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3687}
3688
3689void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003690 VisibleDeclConsumer &Consumer,
3691 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003692 // Determine the set of using directives available during
3693 // unqualified name lookup.
3694 Scope *Initial = S;
3695 UnqualUsingDirectiveSet UDirs;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003696 if (getLangOpts().CPlusPlus) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003697 // Find the first namespace or translation-unit scope.
3698 while (S && !isNamespaceOrTranslationUnitScope(S))
3699 S = S->getParent();
3700
3701 UDirs.visitScopeChain(Initial, S);
3702 }
3703 UDirs.done();
3704
3705 // Look for visible declarations.
3706 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003707 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003708 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003709 if (!IncludeGlobalScope)
3710 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003711 ShadowContextRAII Shadow(Visited);
3712 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3713}
3714
3715void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003716 VisibleDeclConsumer &Consumer,
3717 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003718 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003719 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003720 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003721 if (!IncludeGlobalScope)
3722 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003723 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003724 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003725 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003726}
3727
Chris Lattner43e7f312011-02-18 02:08:43 +00003728/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003729/// If GnuLabelLoc is a valid source location, then this is a definition
3730/// of an __label__ label name, otherwise it is a normal label definition
3731/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003732LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003733 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003734 // Do a lookup to see if we have a label with this name already.
Craig Topperc3ec1492014-05-26 06:22:03 +00003735 NamedDecl *Res = nullptr;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003736
3737 if (GnuLabelLoc.isValid()) {
3738 // Local label definitions always shadow existing labels.
3739 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3740 Scope *S = CurScope;
3741 PushOnScopeChains(Res, S, true);
3742 return cast<LabelDecl>(Res);
3743 }
3744
3745 // Not a GNU local label.
3746 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3747 // If we found a label, check to see if it is in the same context as us.
3748 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003749 if (Res && Res->getDeclContext() != CurContext)
Craig Topperc3ec1492014-05-26 06:22:03 +00003750 Res = nullptr;
3751 if (!Res) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003752 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003753 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3754 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003755 assert(S && "Not in a function?");
3756 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003757 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003758 return cast<LabelDecl>(Res);
3759}
3760
3761//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003762// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003763//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003764
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003765static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3766 TypoCorrection &Candidate) {
3767 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3768 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3769}
3770
3771static void LookupPotentialTypoResult(Sema &SemaRef,
3772 LookupResult &Res,
3773 IdentifierInfo *Name,
3774 Scope *S, CXXScopeSpec *SS,
3775 DeclContext *MemberContext,
3776 bool EnteringContext,
3777 bool isObjCIvarLookup,
3778 bool FindHidden);
3779
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003780/// \brief Check whether the declarations found for a typo correction are
3781/// visible, and if none of them are, convert the correction to an 'import
3782/// a module' correction.
3783static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
3784 if (TC.begin() == TC.end())
3785 return;
3786
3787 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3788
3789 for (/**/; DI != DE; ++DI)
3790 if (!LookupResult::isVisible(SemaRef, *DI))
3791 break;
3792 // Nothing to do if all decls are visible.
3793 if (DI == DE)
3794 return;
3795
3796 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3797 bool AnyVisibleDecls = !NewDecls.empty();
3798
3799 for (/**/; DI != DE; ++DI) {
3800 NamedDecl *VisibleDecl = *DI;
3801 if (!LookupResult::isVisible(SemaRef, *DI))
3802 VisibleDecl = findAcceptableDecl(SemaRef, *DI);
3803
3804 if (VisibleDecl) {
3805 if (!AnyVisibleDecls) {
3806 // Found a visible decl, discard all hidden ones.
3807 AnyVisibleDecls = true;
3808 NewDecls.clear();
3809 }
3810 NewDecls.push_back(VisibleDecl);
3811 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
3812 NewDecls.push_back(*DI);
3813 }
3814
3815 if (NewDecls.empty())
3816 TC = TypoCorrection();
3817 else {
3818 TC.setCorrectionDecls(NewDecls);
3819 TC.setRequiresImport(!AnyVisibleDecls);
3820 }
3821}
3822
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003823// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3824// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3825// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3826static void getNestedNameSpecifierIdentifiers(
3827 NestedNameSpecifier *NNS,
3828 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3829 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3830 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3831 else
3832 Identifiers.clear();
3833
3834 const IdentifierInfo *II = nullptr;
3835
3836 switch (NNS->getKind()) {
3837 case NestedNameSpecifier::Identifier:
3838 II = NNS->getAsIdentifier();
3839 break;
3840
3841 case NestedNameSpecifier::Namespace:
3842 if (NNS->getAsNamespace()->isAnonymousNamespace())
3843 return;
3844 II = NNS->getAsNamespace()->getIdentifier();
3845 break;
3846
3847 case NestedNameSpecifier::NamespaceAlias:
3848 II = NNS->getAsNamespaceAlias()->getIdentifier();
3849 break;
3850
3851 case NestedNameSpecifier::TypeSpecWithTemplate:
3852 case NestedNameSpecifier::TypeSpec:
3853 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3854 break;
3855
3856 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00003857 case NestedNameSpecifier::Super:
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003858 return;
3859 }
3860
3861 if (II)
3862 Identifiers.push_back(II);
3863}
3864
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003865void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003866 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003867 // Don't consider hidden names for typo correction.
3868 if (Hiding)
3869 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003870
Douglas Gregor2d435302009-12-30 17:04:44 +00003871 // Only consider entities with identifiers for names, ignoring
3872 // special names (constructors, overloaded operators, selectors,
3873 // etc.).
3874 IdentifierInfo *Name = ND->getIdentifier();
3875 if (!Name)
3876 return;
3877
Richard Smithe156254d2013-08-20 20:35:18 +00003878 // Only consider visible declarations and declarations from modules with
3879 // names that exactly match.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003880 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo &&
Richard Smithe156254d2013-08-20 20:35:18 +00003881 !findAcceptableDecl(SemaRef, ND))
3882 return;
3883
Douglas Gregor57756ea2010-10-14 22:11:03 +00003884 FoundName(Name->getName());
3885}
3886
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003887void TypoCorrectionConsumer::FoundName(StringRef Name) {
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003888 // Compute the edit distance between the typo and the name of this
3889 // entity, and add the identifier to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003890 addName(Name, nullptr);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003891}
3892
3893void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3894 // Compute the edit distance between the typo and this keyword,
3895 // and add the keyword to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003896 addName(Keyword, nullptr, nullptr, true);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003897}
3898
3899void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
3900 NestedNameSpecifier *NNS, bool isKeyword) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003901 // Use a simple length-based heuristic to determine the minimum possible
3902 // edit distance. If the minimum isn't good enough, bail out early.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003903 StringRef TypoStr = Typo->getName();
3904 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
3905 if (MinED && TypoStr.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00003906 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003907
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003908 // Compute an upper bound on the allowable edit distance, so that the
3909 // edit-distance algorithm can short-circuit.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003910 unsigned UpperBound = (TypoStr.size() + 2) / 3 + 1;
3911 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003912 if (ED >= UpperBound) return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003913
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003914 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003915 if (isKeyword) TC.makeKeyword();
Kaelyn Takata0a313022014-11-20 22:06:26 +00003916 TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003917 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003918}
3919
Kaelyn Takatad2287c32014-10-27 18:07:13 +00003920static const unsigned MaxTypoDistanceResultSets = 5;
3921
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003922void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003923 StringRef TypoStr = Typo->getName();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003924 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003925
3926 // For very short typos, ignore potential corrections that have a different
3927 // base identifier from the typo or which have a normalized edit distance
3928 // longer than the typo itself.
3929 if (TypoStr.size() < 3 &&
3930 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
3931 return;
3932
3933 // If the correction is resolved but is not viable, ignore it.
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003934 if (Correction.isResolved()) {
3935 checkCorrectionVisibility(SemaRef, Correction);
3936 if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
3937 return;
3938 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003939
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003940 TypoResultList &CList =
3941 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003942
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003943 if (!CList.empty() && !CList.back().isResolved())
3944 CList.pop_back();
3945 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3946 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3947 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3948 RI != RIEnd; ++RI) {
3949 // If the Correction refers to a decl already in the result list,
3950 // replace the existing result if the string representation of Correction
3951 // comes before the current result alphabetically, then stop as there is
3952 // nothing more to be done to add Correction to the candidate set.
3953 if (RI->getCorrectionDecl() == NewND) {
3954 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3955 *RI = Correction;
3956 return;
3957 }
3958 }
3959 }
3960 if (CList.empty() || Correction.isResolved())
3961 CList.push_back(Correction);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003962
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003963 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003964 CorrectionResults.erase(std::prev(CorrectionResults.end()));
3965}
3966
3967void TypoCorrectionConsumer::addNamespaces(
3968 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
3969 SearchNamespaces = true;
3970
3971 for (auto KNPair : KnownNamespaces)
3972 Namespaces.addNameSpecifier(KNPair.first);
3973
3974 bool SSIsTemplate = false;
3975 if (NestedNameSpecifier *NNS =
3976 (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
3977 if (const Type *T = NNS->getAsType())
3978 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
3979 }
Richard Smith2a40fb72015-11-18 01:19:02 +00003980 // Do not transform this into an iterator-based loop. The loop body can
3981 // trigger the creation of further types (through lazy deserialization) and
3982 // invalide iterators into this list.
3983 auto &Types = SemaRef.getASTContext().getTypes();
3984 for (unsigned I = 0; I != Types.size(); ++I) {
3985 const auto *TI = Types[I];
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003986 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
3987 CD = CD->getCanonicalDecl();
3988 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
3989 !CD->isUnion() && CD->getIdentifier() &&
3990 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
3991 (CD->isBeingDefined() || CD->isCompleteDefinition()))
3992 Namespaces.addNameSpecifier(CD);
3993 }
3994 }
3995}
3996
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003997const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
3998 if (++CurrentTCIndex < ValidatedCorrections.size())
3999 return ValidatedCorrections[CurrentTCIndex];
4000
4001 CurrentTCIndex = ValidatedCorrections.size();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004002 while (!CorrectionResults.empty()) {
4003 auto DI = CorrectionResults.begin();
4004 if (DI->second.empty()) {
4005 CorrectionResults.erase(DI);
4006 continue;
4007 }
4008
4009 auto RI = DI->second.begin();
4010 if (RI->second.empty()) {
4011 DI->second.erase(RI);
4012 performQualifiedLookups();
4013 continue;
4014 }
4015
4016 TypoCorrection TC = RI->second.pop_back_val();
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00004017 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00004018 ValidatedCorrections.push_back(TC);
4019 return ValidatedCorrections[CurrentTCIndex];
4020 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004021 }
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00004022 return ValidatedCorrections[0]; // The empty correction.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004023}
4024
4025bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
4026 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
4027 DeclContext *TempMemberContext = MemberContext;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004028 CXXScopeSpec *TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004029retry_lookup:
4030 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
4031 EnteringContext,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004032 CorrectionValidator->IsObjCIvarLookup,
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004033 Name == Typo && !Candidate.WillReplaceSpecifier());
4034 switch (Result.getResultKind()) {
4035 case LookupResult::NotFound:
4036 case LookupResult::NotFoundInCurrentInstantiation:
4037 case LookupResult::FoundUnresolvedValue:
4038 if (TempSS) {
4039 // Immediately retry the lookup without the given CXXScopeSpec
4040 TempSS = nullptr;
4041 Candidate.WillReplaceSpecifier(true);
4042 goto retry_lookup;
4043 }
4044 if (TempMemberContext) {
4045 if (SS && !TempSS)
Kaelyn Takata6c759512014-10-27 18:07:37 +00004046 TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004047 TempMemberContext = nullptr;
4048 goto retry_lookup;
4049 }
4050 if (SearchNamespaces)
4051 QualifiedResults.push_back(Candidate);
4052 break;
4053
4054 case LookupResult::Ambiguous:
4055 // We don't deal with ambiguities.
4056 break;
4057
4058 case LookupResult::Found:
4059 case LookupResult::FoundOverloaded:
4060 // Store all of the Decls for overloaded symbols
4061 for (auto *TRD : Result)
4062 Candidate.addCorrectionDecl(TRD);
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00004063 checkCorrectionVisibility(SemaRef, Candidate);
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004064 if (!isCandidateViable(*CorrectionValidator, Candidate)) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004065 if (SearchNamespaces)
4066 QualifiedResults.push_back(Candidate);
4067 break;
4068 }
Kaelyn Takata20deb1d2015-01-28 00:46:09 +00004069 Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004070 return true;
4071 }
4072 return false;
4073}
4074
4075void TypoCorrectionConsumer::performQualifiedLookups() {
4076 unsigned TypoLen = Typo->getName().size();
Benjamin Kramer2e018ef2016-05-27 13:36:58 +00004077 for (const TypoCorrection &QR : QualifiedResults) {
4078 for (const auto &NSI : Namespaces) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004079 DeclContext *Ctx = NSI.DeclCtx;
4080 const Type *NSType = NSI.NameSpecifier->getAsType();
4081
4082 // If the current NestedNameSpecifier refers to a class and the
4083 // current correction candidate is the name of that class, then skip
4084 // it as it is unlikely a qualified version of the class' constructor
4085 // is an appropriate correction.
Hans Wennborgdcfba332015-10-06 23:40:43 +00004086 if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() :
4087 nullptr) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004088 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
4089 continue;
4090 }
4091
4092 TypoCorrection TC(QR);
4093 TC.ClearCorrectionDecls();
4094 TC.setCorrectionSpecifier(NSI.NameSpecifier);
4095 TC.setQualifierDistance(NSI.EditDistance);
4096 TC.setCallbackDistance(0); // Reset the callback distance
4097
4098 // If the current correction candidate and namespace combination are
4099 // too far away from the original typo based on the normalized edit
4100 // distance, then skip performing a qualified name lookup.
4101 unsigned TmpED = TC.getEditDistance(true);
4102 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
4103 TypoLen / TmpED < 3)
4104 continue;
4105
4106 Result.clear();
4107 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
4108 if (!SemaRef.LookupQualifiedName(Result, Ctx))
4109 continue;
4110
4111 // Any corrections added below will be validated in subsequent
4112 // iterations of the main while() loop over the Consumer's contents.
4113 switch (Result.getResultKind()) {
4114 case LookupResult::Found:
4115 case LookupResult::FoundOverloaded: {
4116 if (SS && SS->isValid()) {
4117 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
4118 std::string OldQualified;
4119 llvm::raw_string_ostream OldOStream(OldQualified);
4120 SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
4121 OldOStream << Typo->getName();
4122 // If correction candidate would be an identical written qualified
4123 // identifer, then the existing CXXScopeSpec probably included a
4124 // typedef that didn't get accounted for properly.
4125 if (OldOStream.str() == NewQualified)
4126 break;
4127 }
4128 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
4129 TRD != TRDEnd; ++TRD) {
4130 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4131 NSType ? NSType->getAsCXXRecordDecl()
4132 : nullptr,
4133 TRD.getPair()) == Sema::AR_accessible)
4134 TC.addCorrectionDecl(*TRD);
4135 }
Kaelyn Takata0a313022014-11-20 22:06:26 +00004136 if (TC.isResolved()) {
4137 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004138 addCorrection(TC);
Kaelyn Takata0a313022014-11-20 22:06:26 +00004139 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004140 break;
4141 }
4142 case LookupResult::NotFound:
4143 case LookupResult::NotFoundInCurrentInstantiation:
4144 case LookupResult::Ambiguous:
4145 case LookupResult::FoundUnresolvedValue:
4146 break;
4147 }
4148 }
4149 }
4150 QualifiedResults.clear();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004151}
4152
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004153TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
4154 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
Benjamin Kramer15537272015-03-13 16:10:42 +00004155 : Context(Context), CurContextChain(buildContextChain(CurContext)) {
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004156 if (NestedNameSpecifier *NNS =
4157 CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
4158 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
4159 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4160
4161 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
4162 }
4163 // Build the list of identifiers that would be used for an absolute
4164 // (from the global context) NestedNameSpecifier referring to the current
4165 // context.
David Majnemerf7e36092016-06-23 00:15:04 +00004166 for (DeclContext *C : llvm::reverse(CurContextChain)) {
4167 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C))
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004168 CurContextIdentifiers.push_back(ND->getIdentifier());
4169 }
4170
4171 // Add the global context as a NestedNameSpecifier
Hans Wennborg66010132014-06-11 21:24:13 +00004172 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
4173 NestedNameSpecifier::GlobalSpecifier(Context), 1};
4174 DistanceMap[1].push_back(SI);
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00004175}
4176
Kaelyn Takata7dcc0e62014-06-11 18:07:08 +00004177auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
4178 DeclContext *Start) -> DeclContextList {
Nick Lewycky0d9b3192013-04-08 21:55:21 +00004179 assert(Start && "Building a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004180 DeclContextList Chain;
Craig Topperc3ec1492014-05-26 06:22:03 +00004181 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004182 DC = DC->getLookupParent()) {
4183 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
4184 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
4185 !(ND && ND->isAnonymousNamespace()))
4186 Chain.push_back(DC->getPrimaryContext());
4187 }
4188 return Chain;
4189}
4190
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004191unsigned
4192TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
4193 DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004194 unsigned NumSpecifiers = 0;
David Majnemerf7e36092016-06-23 00:15:04 +00004195 for (DeclContext *C : llvm::reverse(DeclChain)) {
4196 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004197 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
4198 ++NumSpecifiers;
David Majnemerf7e36092016-06-23 00:15:04 +00004199 } else if (auto *RD = dyn_cast_or_null<RecordDecl>(C)) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004200 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
4201 RD->getTypeForDecl());
4202 ++NumSpecifiers;
4203 }
4204 }
4205 return NumSpecifiers;
4206}
4207
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004208void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
4209 DeclContext *Ctx) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004210 NestedNameSpecifier *NNS = nullptr;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004211 unsigned NumSpecifiers = 0;
Kaelyn Takata0fc75192014-06-11 18:06:56 +00004212 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004213 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
4214
4215 // Eliminate common elements from the two DeclContext chains.
David Majnemerf7e36092016-06-23 00:15:04 +00004216 for (DeclContext *C : llvm::reverse(CurContextChain)) {
4217 if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() != C)
4218 break;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004219 NamespaceDeclChain.pop_back();
4220 }
4221
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004222 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004223 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004224
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004225 // Add an explicit leading '::' specifier if needed.
4226 if (NamespaceDeclChain.empty()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004227 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004228 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004229 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004230 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004231 } else if (NamedDecl *ND =
4232 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004233 IdentifierInfo *Name = ND->getIdentifier();
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004234 bool SameNameSpecifier = false;
4235 if (std::find(CurNameSpecifierIdentifiers.begin(),
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004236 CurNameSpecifierIdentifiers.end(),
4237 Name) != CurNameSpecifierIdentifiers.end()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004238 std::string NewNameSpecifier;
4239 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
4240 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
4241 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4242 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4243 SpecifierOStream.flush();
4244 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004245 }
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004246 if (SameNameSpecifier ||
4247 std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
4248 Name) != CurContextIdentifiers.end()) {
4249 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4250 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4251 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004252 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004253 }
4254 }
4255
4256 // If the built NestedNameSpecifier would be replacing an existing
4257 // NestedNameSpecifier, use the number of component identifiers that
4258 // would need to be changed as the edit distance instead of the number
4259 // of components in the built NestedNameSpecifier.
4260 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
4261 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
4262 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4263 NumSpecifiers = llvm::ComputeEditDistance(
Craig Topper8c2a2a02014-08-30 16:55:39 +00004264 llvm::makeArrayRef(CurNameSpecifierIdentifiers),
4265 llvm::makeArrayRef(NewNameSpecifierIdentifiers));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004266 }
4267
Hans Wennborg66010132014-06-11 21:24:13 +00004268 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
4269 DistanceMap[NumSpecifiers].push_back(SI);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004270}
4271
Douglas Gregord507d772010-10-20 03:06:34 +00004272/// \brief Perform name lookup for a possible result for typo correction.
4273static void LookupPotentialTypoResult(Sema &SemaRef,
4274 LookupResult &Res,
4275 IdentifierInfo *Name,
4276 Scope *S, CXXScopeSpec *SS,
4277 DeclContext *MemberContext,
4278 bool EnteringContext,
Richard Smithe156254d2013-08-20 20:35:18 +00004279 bool isObjCIvarLookup,
4280 bool FindHidden) {
Douglas Gregord507d772010-10-20 03:06:34 +00004281 Res.suppressDiagnostics();
4282 Res.clear();
4283 Res.setLookupName(Name);
Richard Smithe156254d2013-08-20 20:35:18 +00004284 Res.setAllowHidden(FindHidden);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004285 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00004286 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004287 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00004288 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
4289 Res.addDecl(Ivar);
4290 Res.resolveKind();
4291 return;
4292 }
4293 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004294
Manman Ren5b786402016-01-28 18:49:28 +00004295 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(
4296 Name, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Douglas Gregord507d772010-10-20 03:06:34 +00004297 Res.addDecl(Prop);
4298 Res.resolveKind();
4299 return;
4300 }
4301 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004302
Douglas Gregord507d772010-10-20 03:06:34 +00004303 SemaRef.LookupQualifiedName(Res, MemberContext);
4304 return;
4305 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004306
4307 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00004308 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004309
Douglas Gregord507d772010-10-20 03:06:34 +00004310 // Fake ivar lookup; this should really be part of
4311 // LookupParsedName.
4312 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
4313 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004314 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00004315 (Res.isSingleResult() &&
4316 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004317 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00004318 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
4319 Res.addDecl(IV);
4320 Res.resolveKind();
4321 }
4322 }
4323 }
4324}
4325
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004326/// \brief Add keywords to the consumer as possible typo corrections.
4327static void AddKeywordsToConsumer(Sema &SemaRef,
4328 TypoCorrectionConsumer &Consumer,
Richard Smithb3a1df02012-06-08 21:35:42 +00004329 Scope *S, CorrectionCandidateCallback &CCC,
4330 bool AfterNestedNameSpecifier) {
4331 if (AfterNestedNameSpecifier) {
4332 // For 'X::', we know exactly which keywords can appear next.
4333 Consumer.addKeywordResult("template");
4334 if (CCC.WantExpressionKeywords)
4335 Consumer.addKeywordResult("operator");
4336 return;
4337 }
4338
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004339 if (CCC.WantObjCSuper)
4340 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004341
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004342 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004343 // Add type-specifier keywords to the set of results.
Craig Topperd6d31ac2013-07-15 08:24:27 +00004344 static const char *const CTypeSpecs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004345 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00004346 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004347 "_Complex", "_Imaginary",
4348 // storage-specifiers as well
4349 "extern", "inline", "static", "typedef"
4350 };
4351
Craig Toppere5ce8312013-07-15 03:38:40 +00004352 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004353 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
4354 Consumer.addKeywordResult(CTypeSpecs[I]);
4355
David Blaikiebbafb8a2012-03-11 07:00:24 +00004356 if (SemaRef.getLangOpts().C99)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004357 Consumer.addKeywordResult("restrict");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004358 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004359 Consumer.addKeywordResult("bool");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004360 else if (SemaRef.getLangOpts().C99)
Douglas Gregor3b22a882011-07-01 21:27:45 +00004361 Consumer.addKeywordResult("_Bool");
4362
David Blaikiebbafb8a2012-03-11 07:00:24 +00004363 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004364 Consumer.addKeywordResult("class");
4365 Consumer.addKeywordResult("typename");
4366 Consumer.addKeywordResult("wchar_t");
4367
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004368 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004369 Consumer.addKeywordResult("char16_t");
4370 Consumer.addKeywordResult("char32_t");
4371 Consumer.addKeywordResult("constexpr");
4372 Consumer.addKeywordResult("decltype");
4373 Consumer.addKeywordResult("thread_local");
4374 }
4375 }
4376
David Blaikiebbafb8a2012-03-11 07:00:24 +00004377 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004378 Consumer.addKeywordResult("typeof");
Kaelyn Takatab04846b2014-07-28 18:14:02 +00004379 } else if (CCC.WantFunctionLikeCasts) {
4380 static const char *const CastableTypeSpecs[] = {
4381 "char", "double", "float", "int", "long", "short",
4382 "signed", "unsigned", "void"
4383 };
4384 for (auto *kw : CastableTypeSpecs)
4385 Consumer.addKeywordResult(kw);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004386 }
4387
David Blaikiebbafb8a2012-03-11 07:00:24 +00004388 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004389 Consumer.addKeywordResult("const_cast");
4390 Consumer.addKeywordResult("dynamic_cast");
4391 Consumer.addKeywordResult("reinterpret_cast");
4392 Consumer.addKeywordResult("static_cast");
4393 }
4394
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004395 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004396 Consumer.addKeywordResult("sizeof");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004397 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004398 Consumer.addKeywordResult("false");
4399 Consumer.addKeywordResult("true");
4400 }
4401
David Blaikiebbafb8a2012-03-11 07:00:24 +00004402 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topperd6d31ac2013-07-15 08:24:27 +00004403 static const char *const CXXExprs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004404 "delete", "new", "operator", "throw", "typeid"
4405 };
Craig Toppere5ce8312013-07-15 03:38:40 +00004406 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004407 for (unsigned I = 0; I != NumCXXExprs; ++I)
4408 Consumer.addKeywordResult(CXXExprs[I]);
4409
4410 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
4411 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
4412 Consumer.addKeywordResult("this");
4413
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004414 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004415 Consumer.addKeywordResult("alignof");
4416 Consumer.addKeywordResult("nullptr");
4417 }
4418 }
Jordan Rose58d54722012-06-30 21:33:57 +00004419
4420 if (SemaRef.getLangOpts().C11) {
4421 // FIXME: We should not suggest _Alignof if the alignof macro
4422 // is present.
4423 Consumer.addKeywordResult("_Alignof");
4424 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004425 }
4426
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004427 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004428 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
4429 // Statements.
Craig Topperd6d31ac2013-07-15 08:24:27 +00004430 static const char *const CStmts[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004431 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Toppere5ce8312013-07-15 03:38:40 +00004432 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004433 for (unsigned I = 0; I != NumCStmts; ++I)
4434 Consumer.addKeywordResult(CStmts[I]);
4435
David Blaikiebbafb8a2012-03-11 07:00:24 +00004436 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004437 Consumer.addKeywordResult("catch");
4438 Consumer.addKeywordResult("try");
4439 }
4440
4441 if (S && S->getBreakParent())
4442 Consumer.addKeywordResult("break");
4443
4444 if (S && S->getContinueParent())
4445 Consumer.addKeywordResult("continue");
4446
4447 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
4448 Consumer.addKeywordResult("case");
4449 Consumer.addKeywordResult("default");
4450 }
4451 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004452 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004453 Consumer.addKeywordResult("namespace");
4454 Consumer.addKeywordResult("template");
4455 }
4456
4457 if (S && S->isClassScope()) {
4458 Consumer.addKeywordResult("explicit");
4459 Consumer.addKeywordResult("friend");
4460 Consumer.addKeywordResult("mutable");
4461 Consumer.addKeywordResult("private");
4462 Consumer.addKeywordResult("protected");
4463 Consumer.addKeywordResult("public");
4464 Consumer.addKeywordResult("virtual");
4465 }
4466 }
4467
David Blaikiebbafb8a2012-03-11 07:00:24 +00004468 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004469 Consumer.addKeywordResult("using");
4470
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004471 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004472 Consumer.addKeywordResult("static_assert");
4473 }
4474 }
4475}
4476
Kaelyn Takata6c759512014-10-27 18:07:37 +00004477std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
4478 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4479 Scope *S, CXXScopeSpec *SS,
4480 std::unique_ptr<CorrectionCandidateCallback> CCC,
4481 DeclContext *MemberContext, bool EnteringContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004482 const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00004483
4484 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4485 DisableTypoCorrection)
4486 return nullptr;
4487
4488 // In Microsoft mode, don't perform typo correction in a template member
4489 // function dependent context because it interferes with the "lookup into
4490 // dependent bases of class templates" feature.
4491 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
4492 isa<CXXMethodDecl>(CurContext))
4493 return nullptr;
4494
4495 // We only attempt to correct typos for identifiers.
4496 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4497 if (!Typo)
4498 return nullptr;
4499
4500 // If the scope specifier itself was invalid, don't try to correct
4501 // typos.
4502 if (SS && SS->isInvalid())
4503 return nullptr;
4504
4505 // Never try to correct typos during template deduction or
4506 // instantiation.
4507 if (!ActiveTemplateInstantiations.empty())
4508 return nullptr;
4509
4510 // Don't try to correct 'super'.
4511 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4512 return nullptr;
4513
4514 // Abort if typo correction already failed for this specific typo.
4515 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4516 if (locs != TypoCorrectionFailures.end() &&
4517 locs->second.count(TypoName.getLoc()))
4518 return nullptr;
4519
4520 // Don't try to correct the identifier "vector" when in AltiVec mode.
4521 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4522 // remove this workaround.
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00004523 if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector"))
Kaelyn Takata6c759512014-10-27 18:07:37 +00004524 return nullptr;
4525
Nick Lewycky24653262014-12-16 21:39:02 +00004526 // Provide a stop gap for files that are just seriously broken. Trying
4527 // to correct all typos can turn into a HUGE performance penalty, causing
4528 // some files to take minutes to get rejected by the parser.
4529 unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
4530 if (Limit && TyposCorrected >= Limit)
4531 return nullptr;
4532 ++TyposCorrected;
4533
Kaelyn Takata6c759512014-10-27 18:07:37 +00004534 // If we're handling a missing symbol error, using modules, and the
4535 // special search all modules option is used, look for a missing import.
4536 if (ErrorRecovery && getLangOpts().Modules &&
4537 getLangOpts().ModulesSearchAll) {
4538 // The following has the side effect of loading the missing module.
4539 getModuleLoader().lookupMissingImports(Typo->getName(),
4540 TypoName.getLocStart());
4541 }
4542
4543 CorrectionCandidateCallback &CCCRef = *CCC;
4544 auto Consumer = llvm::make_unique<TypoCorrectionConsumer>(
4545 *this, TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
4546 EnteringContext);
4547
Kaelyn Takata6c759512014-10-27 18:07:37 +00004548 // Perform name lookup to find visible, similarly-named entities.
Nick Lewycky24653262014-12-16 21:39:02 +00004549 bool IsUnqualifiedLookup = false;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004550 DeclContext *QualifiedDC = MemberContext;
4551 if (MemberContext) {
4552 LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
4553
4554 // Look in qualified interfaces.
4555 if (OPT) {
4556 for (auto *I : OPT->quals())
4557 LookupVisibleDecls(I, LookupKind, *Consumer);
4558 }
4559 } else if (SS && SS->isSet()) {
4560 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4561 if (!QualifiedDC)
4562 return nullptr;
4563
Kaelyn Takata6c759512014-10-27 18:07:37 +00004564 LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
4565 } else {
4566 IsUnqualifiedLookup = true;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004567 }
4568
4569 // Determine whether we are going to search in the various namespaces for
4570 // corrections.
4571 bool SearchNamespaces
4572 = getLangOpts().CPlusPlus &&
4573 (IsUnqualifiedLookup || (SS && SS->isSet()));
4574
4575 if (IsUnqualifiedLookup || SearchNamespaces) {
4576 // For unqualified lookup, look through all of the names that we have
4577 // seen in this translation unit.
4578 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4579 for (const auto &I : Context.Idents)
4580 Consumer->FoundName(I.getKey());
4581
4582 // Walk through identifiers in external identifier sources.
4583 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4584 if (IdentifierInfoLookup *External
4585 = Context.Idents.getExternalIdentifierLookup()) {
4586 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4587 do {
4588 StringRef Name = Iter->Next();
4589 if (Name.empty())
4590 break;
4591
4592 Consumer->FoundName(Name);
4593 } while (true);
4594 }
4595 }
4596
4597 AddKeywordsToConsumer(*this, *Consumer, S, CCCRef, SS && SS->isNotEmpty());
4598
4599 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4600 // to search those namespaces.
4601 if (SearchNamespaces) {
4602 // Load any externally-known namespaces.
4603 if (ExternalSource && !LoadedExternalKnownNamespaces) {
4604 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
4605 LoadedExternalKnownNamespaces = true;
4606 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4607 for (auto *N : ExternalKnownNamespaces)
4608 KnownNamespaces[N] = true;
4609 }
4610
4611 Consumer->addNamespaces(KnownNamespaces);
4612 }
4613
4614 return Consumer;
4615}
4616
Douglas Gregor2d435302009-12-30 17:04:44 +00004617/// \brief Try to "correct" a typo in the source code by finding
4618/// visible declarations whose names are similar to the name that was
4619/// present in the source code.
4620///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004621/// \param TypoName the \c DeclarationNameInfo structure that contains
4622/// the name that was present in the source code along with its location.
4623///
4624/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00004625///
4626/// \param S the scope in which name lookup occurs.
4627///
4628/// \param SS the nested-name-specifier that precedes the name we're
4629/// looking for, if present.
4630///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004631/// \param CCC A CorrectionCandidateCallback object that provides further
4632/// validation of typo correction candidates. It also provides flags for
4633/// determining the set of keywords permitted.
4634///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00004635/// \param MemberContext if non-NULL, the context in which to look for
4636/// a member access expression.
4637///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004638/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00004639/// the nested-name-specifier SS.
4640///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004641/// \param OPT when non-NULL, the search for visible declarations will
4642/// also walk the protocols in the qualified interfaces of \p OPT.
4643///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004644/// \returns a \c TypoCorrection containing the corrected name if the typo
4645/// along with information such as the \c NamedDecl where the corrected name
4646/// was declared, and any additional \c NestedNameSpecifier needed to access
4647/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
4648TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
4649 Sema::LookupNameKind LookupKind,
4650 Scope *S, CXXScopeSpec *SS,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004651 std::unique_ptr<CorrectionCandidateCallback> CCC,
John Thompson2255f2c2014-04-23 12:57:01 +00004652 CorrectTypoKind Mode,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004653 DeclContext *MemberContext,
4654 bool EnteringContext,
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004655 const ObjCObjectPointerType *OPT,
4656 bool RecordFailure) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004657 assert(CCC && "CorrectTypo requires a CorrectionCandidateCallback");
4658
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004659 // Always let the ExternalSource have the first chance at correction, even
4660 // if we would otherwise have given up.
4661 if (ExternalSource) {
4662 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004663 TypoName, LookupKind, S, SS, *CCC, MemberContext, EnteringContext, OPT))
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004664 return Correction;
4665 }
4666
Kaelyn Takata6c759512014-10-27 18:07:37 +00004667 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4668 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4669 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4670 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
4671 bool ObjCMessageReceiver = CCC->WantObjCSuper && !CCC->WantRemainingKeywords;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004672
Kaelyn Takata6c759512014-10-27 18:07:37 +00004673 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Kaelyn Takata6c759512014-10-27 18:07:37 +00004674 auto Consumer = makeTypoCorrectionConsumer(
4675 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004676 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004677
Kaelyn Takata6c759512014-10-27 18:07:37 +00004678 if (!Consumer)
4679 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004680
Douglas Gregor280e1ee2010-04-14 20:04:41 +00004681 // If we haven't found anything, we're done.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004682 if (Consumer->empty())
Nick Lewycky24653262014-12-16 21:39:02 +00004683 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregor2d435302009-12-30 17:04:44 +00004684
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004685 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4686 // is not more that about a third of the length of the typo's identifier.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004687 unsigned ED = Consumer->getBestEditDistance(true);
4688 unsigned TypoLen = Typo->getName().size();
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004689 if (ED > 0 && TypoLen / ED < 3)
Nick Lewycky24653262014-12-16 21:39:02 +00004690 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004691
Kaelyn Takata6c759512014-10-27 18:07:37 +00004692 TypoCorrection BestTC = Consumer->getNextCorrection();
4693 TypoCorrection SecondBestTC = Consumer->getNextCorrection();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004694 if (!BestTC)
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004695 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004696
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004697 ED = BestTC.getEditDistance();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004698
Kaelyn Takata6c759512014-10-27 18:07:37 +00004699 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004700 // If this was an unqualified lookup and we believe the callback
4701 // object wouldn't have filtered out possible corrections, note
4702 // that no correction was found.
Nick Lewycky24653262014-12-16 21:39:02 +00004703 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004704 }
4705
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004706 // If only a single name remains, return that result.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004707 if (!SecondBestTC ||
4708 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
4709 const TypoCorrection &Result = BestTC;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004710
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00004711 // Don't correct to a keyword that's the same as the typo; the keyword
4712 // wasn't actually in scope.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004713 if (ED == 0 && Result.isKeyword())
4714 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004715
David Blaikie04ea41c2012-10-12 20:00:44 +00004716 TypoCorrection TC = Result;
4717 TC.setCorrectionRange(SS, TypoName);
Kaelyn Takataa95ebc62014-06-17 23:47:29 +00004718 checkCorrectionVisibility(*this, TC);
David Blaikie04ea41c2012-10-12 20:00:44 +00004719 return TC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004720 } else if (SecondBestTC && ObjCMessageReceiver) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004721 // Prefer 'super' when we're completing in a message-receiver
4722 // context.
4723
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004724 if (BestTC.getCorrection().getAsString() != "super") {
4725 if (SecondBestTC.getCorrection().getAsString() == "super")
4726 BestTC = SecondBestTC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004727 else if ((*Consumer)["super"].front().isKeyword())
4728 BestTC = (*Consumer)["super"].front();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004729 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004730 // Don't correct to a keyword that's the same as the typo; the keyword
4731 // wasn't actually in scope.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004732 if (BestTC.getEditDistance() == 0 ||
4733 BestTC.getCorrection().getAsString() != "super")
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004734 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004735
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004736 BestTC.setCorrectionRange(SS, TypoName);
4737 return BestTC;
Douglas Gregoraf9eb592010-10-15 13:35:25 +00004738 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004739
Kaelyn Takata73429fd2014-06-10 21:03:49 +00004740 // Record the failure's location if needed and return an empty correction. If
4741 // this was an unqualified lookup and we believe the callback object did not
4742 // filter out possible corrections, also cache the failure for the typo.
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004743 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004744}
4745
Kaelyn Takata6c759512014-10-27 18:07:37 +00004746/// \brief Try to "correct" a typo in the source code by finding
4747/// visible declarations whose names are similar to the name that was
4748/// present in the source code.
4749///
4750/// \param TypoName the \c DeclarationNameInfo structure that contains
4751/// the name that was present in the source code along with its location.
4752///
4753/// \param LookupKind the name-lookup criteria used to search for the name.
4754///
4755/// \param S the scope in which name lookup occurs.
4756///
4757/// \param SS the nested-name-specifier that precedes the name we're
4758/// looking for, if present.
4759///
4760/// \param CCC A CorrectionCandidateCallback object that provides further
4761/// validation of typo correction candidates. It also provides flags for
4762/// determining the set of keywords permitted.
4763///
4764/// \param TDG A TypoDiagnosticGenerator functor that will be used to print
4765/// diagnostics when the actual typo correction is attempted.
4766///
Kaelyn Takata8363f042014-10-27 18:07:42 +00004767/// \param TRC A TypoRecoveryCallback functor that will be used to build an
4768/// Expr from a typo correction candidate.
4769///
Kaelyn Takata6c759512014-10-27 18:07:37 +00004770/// \param MemberContext if non-NULL, the context in which to look for
4771/// a member access expression.
4772///
4773/// \param EnteringContext whether we're entering the context described by
4774/// the nested-name-specifier SS.
4775///
4776/// \param OPT when non-NULL, the search for visible declarations will
4777/// also walk the protocols in the qualified interfaces of \p OPT.
4778///
4779/// \returns a new \c TypoExpr that will later be replaced in the AST with an
4780/// Expr representing the result of performing typo correction, or nullptr if
4781/// typo correction is not possible. If nullptr is returned, no diagnostics will
4782/// be emitted and it is the responsibility of the caller to emit any that are
4783/// needed.
4784TypoExpr *Sema::CorrectTypoDelayed(
4785 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4786 Scope *S, CXXScopeSpec *SS,
4787 std::unique_ptr<CorrectionCandidateCallback> CCC,
Kaelyn Takata8363f042014-10-27 18:07:42 +00004788 TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,
Kaelyn Takata6c759512014-10-27 18:07:37 +00004789 DeclContext *MemberContext, bool EnteringContext,
4790 const ObjCObjectPointerType *OPT) {
4791 assert(CCC && "CorrectTypoDelayed requires a CorrectionCandidateCallback");
4792
Kaelyn Takata6c759512014-10-27 18:07:37 +00004793 auto Consumer = makeTypoCorrectionConsumer(
4794 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004795 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Kaelyn Takata6c759512014-10-27 18:07:37 +00004796
Benjamin Kramerb8727332016-05-19 10:46:10 +00004797 // Give the external sema source a chance to correct the typo.
4798 TypoCorrection ExternalTypo;
4799 if (ExternalSource && Consumer) {
4800 ExternalTypo = ExternalSource->CorrectTypo(
Benjamin Kramer97d7a662016-05-19 21:53:33 +00004801 TypoName, LookupKind, S, SS, *Consumer->getCorrectionValidator(),
4802 MemberContext, EnteringContext, OPT);
Benjamin Kramerb8727332016-05-19 10:46:10 +00004803 if (ExternalTypo)
4804 Consumer->addCorrection(ExternalTypo);
4805 }
4806
Kaelyn Takata6c759512014-10-27 18:07:37 +00004807 if (!Consumer || Consumer->empty())
4808 return nullptr;
4809
4810 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4811 // is not more that about a third of the length of the typo's identifier.
4812 unsigned ED = Consumer->getBestEditDistance(true);
4813 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Benjamin Kramerb8727332016-05-19 10:46:10 +00004814 if (!ExternalTypo && ED > 0 && Typo->getName().size() / ED < 3)
Kaelyn Takata6c759512014-10-27 18:07:37 +00004815 return nullptr;
4816
4817 ExprEvalContexts.back().NumTypos++;
Kaelyn Takata8363f042014-10-27 18:07:42 +00004818 return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC));
Kaelyn Takata6c759512014-10-27 18:07:37 +00004819}
4820
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004821void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4822 if (!CDecl) return;
4823
4824 if (isKeyword())
4825 CorrectionDecls.clear();
4826
Richard Smithde6d6c42015-12-29 19:43:10 +00004827 CorrectionDecls.push_back(CDecl);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004828
4829 if (!CorrectionName)
4830 CorrectionName = CDecl->getDeclName();
4831}
4832
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004833std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4834 if (CorrectionNameSpec) {
4835 std::string tmpBuffer;
4836 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4837 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikied4da8722013-05-14 21:04:00 +00004838 PrefixOStream << CorrectionName;
Benjamin Kramer73faad62012-04-14 08:26:28 +00004839 return PrefixOStream.str();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004840 }
4841
4842 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00004843}
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004844
Nico Weberb58e51c2014-11-19 05:21:39 +00004845bool CorrectionCandidateCallback::ValidateCandidate(
4846 const TypoCorrection &candidate) {
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004847 if (!candidate.isResolved())
4848 return true;
4849
4850 if (candidate.isKeyword())
4851 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4852 WantRemainingKeywords || WantObjCSuper;
4853
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004854 bool HasNonType = false;
4855 bool HasStaticMethod = false;
4856 bool HasNonStaticMethod = false;
4857 for (Decl *D : candidate) {
4858 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
4859 D = FTD->getTemplatedDecl();
4860 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4861 if (Method->isStatic())
4862 HasStaticMethod = true;
4863 else
4864 HasNonStaticMethod = true;
4865 }
4866 if (!isa<TypeDecl>(D))
4867 HasNonType = true;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004868 }
4869
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004870 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
4871 !candidate.getCorrectionSpecifier())
4872 return false;
4873
4874 return WantTypeSpecifiers || HasNonType;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004875}
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004876
4877FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004878 bool HasExplicitTemplateArgs,
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004879 MemberExpr *ME)
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004880 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004881 CurContext(SemaRef.CurContext), MemberFn(ME) {
Kaelyn Takatab04846b2014-07-28 18:14:02 +00004882 WantTypeSpecifiers = false;
4883 WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus && NumArgs == 1;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004884 WantRemainingKeywords = false;
4885}
4886
4887bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4888 if (!candidate.getCorrectionDecl())
4889 return candidate.isKeyword();
4890
Aaron Ballman1e606f42014-07-15 22:03:49 +00004891 for (auto *C : candidate) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004892 FunctionDecl *FD = nullptr;
Aaron Ballman1e606f42014-07-15 22:03:49 +00004893 NamedDecl *ND = C->getUnderlyingDecl();
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004894 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4895 FD = FTD->getTemplatedDecl();
4896 if (!HasExplicitTemplateArgs && !FD) {
4897 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4898 // If the Decl is neither a function nor a template function,
4899 // determine if it is a pointer or reference to a function. If so,
4900 // check against the number of arguments expected for the pointee.
4901 QualType ValType = cast<ValueDecl>(ND)->getType();
4902 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4903 ValType = ValType->getPointeeType();
4904 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
Alp Toker9cacbab2014-01-20 20:26:09 +00004905 if (FPT->getNumParams() == NumArgs)
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004906 return true;
4907 }
4908 }
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004909
4910 // Skip the current candidate if it is not a FunctionDecl or does not accept
4911 // the current number of arguments.
4912 if (!FD || !(FD->getNumParams() >= NumArgs &&
4913 FD->getMinRequiredArguments() <= NumArgs))
4914 continue;
4915
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004916 // If the current candidate is a non-static C++ method, skip the candidate
4917 // unless the method being corrected--or the current DeclContext, if the
4918 // function being corrected is not a method--is a method in the same class
4919 // or a descendent class of the candidate's parent class.
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004920 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004921 if (MemberFn || !MD->isStatic()) {
4922 CXXMethodDecl *CurMD =
4923 MemberFn
4924 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
4925 : dyn_cast_or_null<CXXMethodDecl>(CurContext);
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004926 CXXRecordDecl *CurRD =
Craig Topperc3ec1492014-05-26 06:22:03 +00004927 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004928 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
4929 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
4930 continue;
4931 }
4932 }
4933 return true;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004934 }
4935 return false;
4936}
Richard Smithf9b15102013-08-17 00:46:16 +00004937
4938void Sema::diagnoseTypo(const TypoCorrection &Correction,
4939 const PartialDiagnostic &TypoDiag,
4940 bool ErrorRecovery) {
4941 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
4942 ErrorRecovery);
4943}
4944
Richard Smithe156254d2013-08-20 20:35:18 +00004945/// Find which declaration we should import to provide the definition of
4946/// the given declaration.
Richard Smith42413142015-05-15 20:05:43 +00004947static NamedDecl *getDefinitionToImport(NamedDecl *D) {
4948 if (VarDecl *VD = dyn_cast<VarDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004949 return VD->getDefinition();
Yaron Keren18c3d062016-07-13 19:04:51 +00004950 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4951 return FD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00004952 if (TagDecl *TD = dyn_cast<TagDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004953 return TD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00004954 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004955 return ID->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00004956 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004957 return PD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00004958 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004959 return getDefinitionToImport(TD->getTemplatedDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004960 return nullptr;
Richard Smithe156254d2013-08-20 20:35:18 +00004961}
4962
Richard Smithf2b1eb92015-06-15 20:15:48 +00004963void Sema::diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
Richard Smith6739a102016-05-05 00:56:12 +00004964 MissingImportKind MIK, bool Recover) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00004965 assert(!isVisible(Decl) && "missing import for non-hidden decl?");
4966
4967 // Suggest importing a module providing the definition of this entity, if
4968 // possible.
4969 NamedDecl *Def = getDefinitionToImport(Decl);
4970 if (!Def)
4971 Def = Decl;
4972
Richard Smithf2b1eb92015-06-15 20:15:48 +00004973 Module *Owner = getOwningModule(Decl);
4974 assert(Owner && "definition of hidden declaration is not in a module");
4975
Richard Smith35c1df52015-06-17 20:16:32 +00004976 llvm::SmallVector<Module*, 8> OwningModules;
4977 OwningModules.push_back(Owner);
Richard Smithf2b1eb92015-06-15 20:15:48 +00004978 auto Merged = Context.getModulesWithMergedDefinition(Decl);
Richard Smith35c1df52015-06-17 20:16:32 +00004979 OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end());
4980
Richard Smith6739a102016-05-05 00:56:12 +00004981 diagnoseMissingImport(Loc, Decl, Decl->getLocation(), OwningModules, MIK,
Richard Smith35c1df52015-06-17 20:16:32 +00004982 Recover);
4983}
4984
Richard Smith4eb83932016-04-27 21:57:05 +00004985/// \brief Get a "quoted.h" or <angled.h> include path to use in a diagnostic
4986/// suggesting the addition of a #include of the specified file.
4987static std::string getIncludeStringForHeader(Preprocessor &PP,
4988 const FileEntry *E) {
4989 bool IsSystem;
4990 auto Path =
4991 PP.getHeaderSearchInfo().suggestPathToFileForDiagnostics(E, &IsSystem);
4992 return (IsSystem ? '<' : '"') + Path + (IsSystem ? '>' : '"');
4993}
4994
Richard Smith35c1df52015-06-17 20:16:32 +00004995void Sema::diagnoseMissingImport(SourceLocation UseLoc, NamedDecl *Decl,
4996 SourceLocation DeclLoc,
4997 ArrayRef<Module *> Modules,
4998 MissingImportKind MIK, bool Recover) {
4999 assert(!Modules.empty());
5000
5001 if (Modules.size() > 1) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00005002 std::string ModuleList;
Richard Smithf2b1eb92015-06-15 20:15:48 +00005003 unsigned N = 0;
Richard Smith35c1df52015-06-17 20:16:32 +00005004 for (Module *M : Modules) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00005005 ModuleList += "\n ";
Richard Smith35c1df52015-06-17 20:16:32 +00005006 if (++N == 5 && N != Modules.size()) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00005007 ModuleList += "[...]";
5008 break;
5009 }
5010 ModuleList += M->getFullModuleName();
5011 }
5012
Richard Smith35c1df52015-06-17 20:16:32 +00005013 Diag(UseLoc, diag::err_module_unimported_use_multiple)
5014 << (int)MIK << Decl << ModuleList;
Richard Smith4eb83932016-04-27 21:57:05 +00005015 } else if (const FileEntry *E =
5016 PP.getModuleHeaderToIncludeForDiagnostics(UseLoc, DeclLoc)) {
5017 // The right way to make the declaration visible is to include a header;
5018 // suggest doing so.
5019 //
5020 // FIXME: Find a smart place to suggest inserting a #include, and add
5021 // a FixItHint there.
5022 Diag(UseLoc, diag::err_module_unimported_use_header)
5023 << (int)MIK << Decl << Modules[0]->getFullModuleName()
5024 << getIncludeStringForHeader(PP, E);
Richard Smithf2b1eb92015-06-15 20:15:48 +00005025 } else {
Richard Smithacef17a2016-05-05 02:14:06 +00005026 // FIXME: Add a FixItHint that imports the corresponding module.
Richard Smith35c1df52015-06-17 20:16:32 +00005027 Diag(UseLoc, diag::err_module_unimported_use)
5028 << (int)MIK << Decl << Modules[0]->getFullModuleName();
Richard Smithf2b1eb92015-06-15 20:15:48 +00005029 }
Richard Smith35c1df52015-06-17 20:16:32 +00005030
5031 unsigned DiagID;
5032 switch (MIK) {
5033 case MissingImportKind::Declaration:
5034 DiagID = diag::note_previous_declaration;
5035 break;
5036 case MissingImportKind::Definition:
5037 DiagID = diag::note_previous_definition;
5038 break;
5039 case MissingImportKind::DefaultArgument:
5040 DiagID = diag::note_default_argument_declared_here;
5041 break;
Richard Smith6739a102016-05-05 00:56:12 +00005042 case MissingImportKind::ExplicitSpecialization:
5043 DiagID = diag::note_explicit_specialization_declared_here;
5044 break;
5045 case MissingImportKind::PartialSpecialization:
5046 DiagID = diag::note_partial_specialization_declared_here;
5047 break;
Richard Smith35c1df52015-06-17 20:16:32 +00005048 }
5049 Diag(DeclLoc, DiagID);
Richard Smithf2b1eb92015-06-15 20:15:48 +00005050
5051 // Try to recover by implicitly importing this module.
5052 if (Recover)
Richard Smith35c1df52015-06-17 20:16:32 +00005053 createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
Richard Smithf2b1eb92015-06-15 20:15:48 +00005054}
5055
Richard Smithf9b15102013-08-17 00:46:16 +00005056/// \brief Diagnose a successfully-corrected typo. Separated from the correction
5057/// itself to allow external validation of the result, etc.
5058///
5059/// \param Correction The result of performing typo correction.
5060/// \param TypoDiag The diagnostic to produce. This will have the corrected
5061/// string added to it (and usually also a fixit).
5062/// \param PrevNote A note to use when indicating the location of the entity to
5063/// which we are correcting. Will have the correction string added to it.
5064/// \param ErrorRecovery If \c true (the default), the caller is going to
5065/// recover from the typo as if the corrected string had been typed.
5066/// In this case, \c PDiag must be an error, and we will attach a fixit
5067/// to it.
5068void Sema::diagnoseTypo(const TypoCorrection &Correction,
5069 const PartialDiagnostic &TypoDiag,
5070 const PartialDiagnostic &PrevNote,
5071 bool ErrorRecovery) {
5072 std::string CorrectedStr = Correction.getAsString(getLangOpts());
5073 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
5074 FixItHint FixTypo = FixItHint::CreateReplacement(
5075 Correction.getCorrectionRange(), CorrectedStr);
5076
Richard Smithe156254d2013-08-20 20:35:18 +00005077 // Maybe we're just missing a module import.
5078 if (Correction.requiresImport()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00005079 NamedDecl *Decl = Correction.getFoundDecl();
Richard Smithe156254d2013-08-20 20:35:18 +00005080 assert(Decl && "import required but no declaration to import");
5081
Richard Smithf2b1eb92015-06-15 20:15:48 +00005082 diagnoseMissingImport(Correction.getCorrectionRange().getBegin(), Decl,
Richard Smith6739a102016-05-05 00:56:12 +00005083 MissingImportKind::Declaration, ErrorRecovery);
Richard Smithe156254d2013-08-20 20:35:18 +00005084 return;
5085 }
5086
Richard Smithf9b15102013-08-17 00:46:16 +00005087 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
5088 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
5089
5090 NamedDecl *ChosenDecl =
Richard Smithde6d6c42015-12-29 19:43:10 +00005091 Correction.isKeyword() ? nullptr : Correction.getFoundDecl();
Richard Smithf9b15102013-08-17 00:46:16 +00005092 if (PrevNote.getDiagID() && ChosenDecl)
5093 Diag(ChosenDecl->getLocation(), PrevNote)
5094 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
Benjamin Kramer7de99692016-11-16 18:15:26 +00005095
5096 // Add any extra diagnostics.
5097 for (const PartialDiagnostic &PD : Correction.getExtraDiagnostics())
5098 Diag(Correction.getCorrectionRange().getBegin(), PD);
Richard Smithf9b15102013-08-17 00:46:16 +00005099}
Kaelyn Takata6c759512014-10-27 18:07:37 +00005100
Kaelyn Takata8363f042014-10-27 18:07:42 +00005101TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
5102 TypoDiagnosticGenerator TDG,
5103 TypoRecoveryCallback TRC) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00005104 assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
5105 auto TE = new (Context) TypoExpr(Context.DependentTy);
5106 auto &State = DelayedTypos[TE];
5107 State.Consumer = std::move(TCC);
5108 State.DiagHandler = std::move(TDG);
Kaelyn Takata8363f042014-10-27 18:07:42 +00005109 State.RecoveryHandler = std::move(TRC);
Kaelyn Takata6c759512014-10-27 18:07:37 +00005110 return TE;
5111}
5112
5113const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
5114 auto Entry = DelayedTypos.find(TE);
5115 assert(Entry != DelayedTypos.end() &&
5116 "Failed to get the state for a TypoExpr!");
5117 return Entry->second;
5118}
5119
5120void Sema::clearDelayedTypo(TypoExpr *TE) {
5121 DelayedTypos.erase(TE);
5122}
Richard Smithba3a4f92016-01-12 21:59:26 +00005123
5124void Sema::ActOnPragmaDump(Scope *S, SourceLocation IILoc, IdentifierInfo *II) {
5125 DeclarationNameInfo Name(II, IILoc);
5126 LookupResult R(*this, Name, LookupAnyName, Sema::NotForRedeclaration);
5127 R.suppressDiagnostics();
5128 R.setHideTags(false);
5129 LookupName(R, S);
5130 R.dump();
5131}