blob: 5e7e34a89287e3faa2a7ed94ae0b41ae76035aa2 [file] [log] [blame]
Douglas Gregor34074322009-01-14 22:20:51 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2//
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//===----------------------------------------------------------------------===//
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000014#include "clang/Sema/Lookup.h"
Douglas Gregor960b5bc2009-01-15 00:26:24 +000015#include "clang/AST/ASTContext.h"
Richard Smithd9ba2242015-05-07 03:54:19 +000016#include "clang/AST/ASTMutationListener.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000018#include "clang/AST/Decl.h"
19#include "clang/AST/DeclCXX.h"
Nick Lewyckyc3921482012-04-03 21:44:08 +000020#include "clang/AST/DeclLookups.h"
Douglas Gregor34074322009-01-14 22:20:51 +000021#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000022#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000023#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000024#include "clang/AST/ExprCXX.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Douglas Gregor34074322009-01-14 22:20:51 +000026#include "clang/Basic/LangOptions.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"
30#include "clang/Sema/ExternalSemaSource.h"
31#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"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "llvm/ADT/SetVector.h"
Douglas Gregore254f902009-02-04 00:32:51 +000040#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0afa7f62010-10-14 20:34:08 +000041#include "llvm/ADT/StringMap.h"
Chris Lattner83cfc7c2011-07-18 01:54:02 +000042#include "llvm/ADT/TinyPtrVector.h"
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +000043#include "llvm/ADT/edit_distance.h"
John McCall6538c932009-10-10 05:48:19 +000044#include "llvm/Support/ErrorHandling.h"
Nick Lewycky13668f22012-04-03 20:26:45 +000045#include <algorithm>
46#include <iterator>
Douglas Gregor0afa7f62010-10-14 20:34:08 +000047#include <limits>
Douglas Gregor2d435302009-12-30 17:04:44 +000048#include <list>
Douglas Gregorc2fa1692011-06-28 16:20:02 +000049#include <map>
Nick Lewycky13668f22012-04-03 20:26:45 +000050#include <set>
51#include <utility>
52#include <vector>
Douglas Gregor34074322009-01-14 22:20:51 +000053
54using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000055using namespace sema;
Douglas Gregor34074322009-01-14 22:20:51 +000056
John McCallf6c8a4e2009-11-10 07:01:13 +000057namespace {
58 class UnqualUsingEntry {
59 const DeclContext *Nominated;
60 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000061
John McCallf6c8a4e2009-11-10 07:01:13 +000062 public:
63 UnqualUsingEntry(const DeclContext *Nominated,
64 const DeclContext *CommonAncestor)
65 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
66 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000067
John McCallf6c8a4e2009-11-10 07:01:13 +000068 const DeclContext *getCommonAncestor() const {
69 return CommonAncestor;
70 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000071
John McCallf6c8a4e2009-11-10 07:01:13 +000072 const DeclContext *getNominatedNamespace() const {
73 return Nominated;
74 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000075
John McCallf6c8a4e2009-11-10 07:01:13 +000076 // Sort by the pointer value of the common ancestor.
77 struct Comparator {
78 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
79 return L.getCommonAncestor() < R.getCommonAncestor();
80 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000081
John McCallf6c8a4e2009-11-10 07:01:13 +000082 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
83 return E.getCommonAncestor() < DC;
84 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000085
John McCallf6c8a4e2009-11-10 07:01:13 +000086 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
87 return DC < E.getCommonAncestor();
88 }
89 };
90 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000091
John McCallf6c8a4e2009-11-10 07:01:13 +000092 /// A collection of using directives, as used by C++ unqualified
93 /// lookup.
94 class UnqualUsingDirectiveSet {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000095 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000096
John McCallf6c8a4e2009-11-10 07:01:13 +000097 ListTy list;
98 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000099
John McCallf6c8a4e2009-11-10 07:01:13 +0000100 public:
101 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +0000102
John McCallf6c8a4e2009-11-10 07:01:13 +0000103 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000104 // C++ [namespace.udir]p1:
John McCallf6c8a4e2009-11-10 07:01:13 +0000105 // During unqualified name lookup, the names appear as if they
106 // were declared in the nearest enclosing namespace which contains
107 // both the using-directive and the nominated namespace.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000108 DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
John McCallf6c8a4e2009-11-10 07:01:13 +0000109 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +0000110
John McCallf6c8a4e2009-11-10 07:01:13 +0000111 for (; S; S = S->getParent()) {
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000112 // C++ [namespace.udir]p1:
113 // A using-directive shall not appear in class scope, but may
114 // appear in namespace scope or in block scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000115 DeclContext *Ctx = S->getEntity();
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000116 if (Ctx && Ctx->isFileContext()) {
117 visit(Ctx, Ctx);
118 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
Aaron Ballman5df6aa42014-03-17 17:03:37 +0000119 for (auto *I : S->using_directives())
120 visit(I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000121 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000122 }
123 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000124
125 // Visits a context and collect all of its using directives
126 // recursively. Treats all using directives as if they were
127 // declared in the context.
128 //
129 // A given context is only every visited once, so it is important
130 // that contexts be visited from the inside out in order to get
131 // the effective DCs right.
132 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
David Blaikie82e95a32014-11-19 07:49:47 +0000133 if (!visited.insert(DC).second)
John McCallf6c8a4e2009-11-10 07:01:13 +0000134 return;
135
136 addUsingDirectives(DC, EffectiveDC);
137 }
138
139 // Visits a using directive and collects all of its using
140 // directives recursively. Treats all using directives as if they
141 // were declared in the effective DC.
142 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
143 DeclContext *NS = UD->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +0000144 if (!visited.insert(NS).second)
John McCallf6c8a4e2009-11-10 07:01:13 +0000145 return;
146
147 addUsingDirective(UD, EffectiveDC);
148 addUsingDirectives(NS, EffectiveDC);
149 }
150
151 // Adds all the using directives in a context (and those nominated
152 // by its using directives, transitively) as if they appeared in
153 // the given effective context.
154 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000155 SmallVector<DeclContext*,4> queue;
John McCallf6c8a4e2009-11-10 07:01:13 +0000156 while (true) {
Aaron Ballman804a7fb2014-03-17 17:14:12 +0000157 for (auto UD : DC->using_directives()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000158 DeclContext *NS = UD->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +0000159 if (visited.insert(NS).second) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000160 addUsingDirective(UD, EffectiveDC);
161 queue.push_back(NS);
162 }
163 }
164
165 if (queue.empty())
166 return;
167
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000168 DC = queue.pop_back_val();
John McCallf6c8a4e2009-11-10 07:01:13 +0000169 }
170 }
171
172 // Add a using directive as if it had been declared in the given
173 // context. This helps implement C++ [namespace.udir]p3:
174 // The using-directive is transitive: if a scope contains a
175 // using-directive that nominates a second namespace that itself
176 // contains using-directives, the effect is as if the
177 // using-directives from the second namespace also appeared in
178 // the first.
179 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
180 // Find the common ancestor between the effective context and
181 // the nominated namespace.
182 DeclContext *Common = UD->getNominatedNamespace();
183 while (!Common->Encloses(EffectiveDC))
184 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000185 Common = Common->getPrimaryContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000186
John McCallf6c8a4e2009-11-10 07:01:13 +0000187 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
188 }
189
190 void done() {
191 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
192 }
193
John McCallf6c8a4e2009-11-10 07:01:13 +0000194 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000195
John McCallf6c8a4e2009-11-10 07:01:13 +0000196 const_iterator begin() const { return list.begin(); }
197 const_iterator end() const { return list.end(); }
198
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000199 llvm::iterator_range<const_iterator>
John McCallf6c8a4e2009-11-10 07:01:13 +0000200 getNamespacesFor(DeclContext *DC) const {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000201 return llvm::make_range(std::equal_range(begin(), end(),
202 DC->getPrimaryContext(),
203 UnqualUsingEntry::Comparator()));
John McCallf6c8a4e2009-11-10 07:01:13 +0000204 }
205 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000206}
207
Douglas Gregor889ceb72009-02-03 19:21:40 +0000208// Retrieve the set of identifier namespaces that correspond to a
209// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000210static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
211 bool CPlusPlus,
212 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000213 unsigned IDNS = 0;
214 switch (NameKind) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +0000215 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000216 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000217 case Sema::LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +0000218 case Sema::LookupLocalFriendName:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000219 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000220 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000221 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000222 if (Redeclaration)
223 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCallea305ed2009-12-18 10:40:03 +0000224 }
Richard Smith541b38b2013-09-20 01:15:31 +0000225 if (Redeclaration)
226 IDNS |= Decl::IDNS_LocalExtern;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000227 break;
228
John McCallb9467b62010-04-24 01:30:58 +0000229 case Sema::LookupOperatorName:
230 // Operator lookup is its own crazy thing; it is not the same
231 // as (e.g.) looking up an operator name for redeclaration.
232 assert(!Redeclaration && "cannot do redeclaration operator lookup");
233 IDNS = Decl::IDNS_NonMemberOperator;
234 break;
235
Douglas Gregor889ceb72009-02-03 19:21:40 +0000236 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000237 if (CPlusPlus) {
238 IDNS = Decl::IDNS_Type;
239
240 // When looking for a redeclaration of a tag name, we add:
241 // 1) TagFriend to find undeclared friend decls
242 // 2) Namespace because they can't "overload" with tag decls.
243 // 3) Tag because it includes class templates, which can't
244 // "overload" with tag decls.
245 if (Redeclaration)
246 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
247 } else {
248 IDNS = Decl::IDNS_Tag;
249 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000250 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000251
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000252 case Sema::LookupLabel:
253 IDNS = Decl::IDNS_Label;
254 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000255
Douglas Gregor889ceb72009-02-03 19:21:40 +0000256 case Sema::LookupMemberName:
257 IDNS = Decl::IDNS_Member;
258 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000259 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000260 break;
261
262 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000263 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
264 break;
265
Douglas Gregor889ceb72009-02-03 19:21:40 +0000266 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000267 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000268 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000269
John McCall84d87672009-12-10 09:41:52 +0000270 case Sema::LookupUsingDeclName:
Richard Smith83e78f52014-04-11 01:03:38 +0000271 assert(Redeclaration && "should only be used for redecl lookup");
272 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |
273 Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend |
274 Decl::IDNS_LocalExtern;
John McCall84d87672009-12-10 09:41:52 +0000275 break;
276
Douglas Gregor79947a22009-04-24 00:11:27 +0000277 case Sema::LookupObjCProtocolName:
278 IDNS = Decl::IDNS_ObjCProtocol;
279 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000280
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
John McCall283b9012009-11-22 00:44:51 +0000356/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000357void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000358 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000359
John McCall9f3059a2009-10-09 21:13:30 +0000360 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000361 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000362 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000363 return;
364 }
365
John McCall283b9012009-11-22 00:44:51 +0000366 // If there's a single decl, we need to examine it to decide what
367 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000368 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000369 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
370 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000371 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000372 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000373 ResultKind = FoundUnresolvedValue;
374 return;
375 }
John McCall9f3059a2009-10-09 21:13:30 +0000376
John McCall6538c932009-10-10 05:48:19 +0000377 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000378 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000379
John McCall9f3059a2009-10-09 21:13:30 +0000380 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor13e65872010-08-11 14:45:53 +0000381 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000382
John McCall9f3059a2009-10-09 21:13:30 +0000383 bool Ambiguous = false;
384 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000385 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000386
387 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000388
John McCall9f3059a2009-10-09 21:13:30 +0000389 unsigned I = 0;
390 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000391 NamedDecl *D = Decls[I]->getUnderlyingDecl();
392 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000393
Argyrios Kyrtzidis1fcd7fd2013-02-22 06:58:37 +0000394 // Ignore an invalid declaration unless it's the only one left.
395 if (D->isInvalidDecl() && I < N-1) {
396 Decls[I] = Decls[--N];
397 continue;
398 }
399
Douglas Gregor13e65872010-08-11 14:45:53 +0000400 // Redeclarations of types via typedef can occur both within a scope
401 // and, through using declarations and directives, across scopes. There is
402 // no ambiguity if they all refer to the same type, so unique based on the
403 // canonical type.
404 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
405 if (!TD->getDeclContext()->isRecord()) {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000406 QualType T = getSema().Context.getTypeDeclType(TD);
David Blaikie82e95a32014-11-19 07:49:47 +0000407 if (!UniqueTypes.insert(getSema().Context.getCanonicalType(T)).second) {
Douglas Gregor13e65872010-08-11 14:45:53 +0000408 // The type is not unique; pull something off the back and continue
409 // at this index.
410 Decls[I] = Decls[--N];
411 continue;
412 }
413 }
414 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000415
David Blaikie82e95a32014-11-19 07:49:47 +0000416 if (!Unique.insert(D).second) {
John McCall9f3059a2009-10-09 21:13:30 +0000417 // If it's not unique, pull something off the back (and
418 // continue at this index).
Richard Smithe8292b12015-02-10 03:28:10 +0000419 // FIXME: This is wrong. We need to take the more recent declaration in
Richard Smithfe620d22015-03-05 23:24:12 +0000420 // order to get the right type, default arguments, etc. We also need to
421 // prefer visible declarations to hidden ones (for redeclaration lookup
422 // in modules builds).
John McCall9f3059a2009-10-09 21:13:30 +0000423 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000424 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000425 }
426
Douglas Gregor13e65872010-08-11 14:45:53 +0000427 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000428
Douglas Gregor13e65872010-08-11 14:45:53 +0000429 if (isa<UnresolvedUsingValueDecl>(D)) {
430 HasUnresolved = true;
431 } else if (isa<TagDecl>(D)) {
432 if (HasTag)
433 Ambiguous = true;
434 UniqueTagIndex = I;
435 HasTag = true;
436 } else if (isa<FunctionTemplateDecl>(D)) {
437 HasFunction = true;
438 HasFunctionTemplate = true;
439 } else if (isa<FunctionDecl>(D)) {
440 HasFunction = true;
441 } else {
442 if (HasNonFunction)
443 Ambiguous = true;
444 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000445 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000446 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000447 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000448
John McCall9f3059a2009-10-09 21:13:30 +0000449 // C++ [basic.scope.hiding]p2:
450 // A class name or enumeration name can be hidden by the name of
451 // an object, function, or enumerator declared in the same
452 // scope. If a class or enumeration name and an object, function,
453 // or enumerator are declared in the same scope (in any order)
454 // with the same name, the class or enumeration name is hidden
455 // wherever the object, function, or enumerator name is visible.
456 // But it's still an error if there are distinct tag types found,
457 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000458 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000459 (HasFunction || HasNonFunction || HasUnresolved)) {
Richard Smith3876cc82013-10-30 01:02:04 +0000460 if (getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
461 getContextForScopeMatching(Decls[UniqueTagIndex ? 0 : N - 1])))
Douglas Gregore63d0872010-10-23 16:06:17 +0000462 Decls[UniqueTagIndex] = Decls[--N];
463 else
464 Ambiguous = true;
465 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000466
John McCall9f3059a2009-10-09 21:13:30 +0000467 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000468
John McCall80053822009-12-03 00:58:24 +0000469 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000470 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000471
John McCall9f3059a2009-10-09 21:13:30 +0000472 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000473 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000474 else if (HasUnresolved)
475 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000476 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000477 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000478 else
John McCall27b18f82009-11-17 02:14:36 +0000479 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000480}
481
John McCall5cebab12009-11-18 07:57:50 +0000482void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000483 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000484 for (I = P.begin(), E = P.end(); I != E; ++I)
David Blaikieff7d47a2012-12-19 00:45:41 +0000485 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
486 DE = I->Decls.end(); DI != DE; ++DI)
John McCall9f3059a2009-10-09 21:13:30 +0000487 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000488}
489
John McCall5cebab12009-11-18 07:57:50 +0000490void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000491 Paths = new CXXBasePaths;
492 Paths->swap(P);
493 addDeclsFromBasePaths(*Paths);
494 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000495 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000496}
497
John McCall5cebab12009-11-18 07:57:50 +0000498void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000499 Paths = new CXXBasePaths;
500 Paths->swap(P);
501 addDeclsFromBasePaths(*Paths);
502 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000503 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000504}
505
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000506void LookupResult::print(raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000507 Out << Decls.size() << " result(s)";
508 if (isAmbiguous()) Out << ", ambiguous";
509 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000510
John McCall9f3059a2009-10-09 21:13:30 +0000511 for (iterator I = begin(), E = end(); I != E; ++I) {
512 Out << "\n";
513 (*I)->print(Out, 2);
514 }
515}
516
Douglas Gregord3a59182010-02-12 05:48:04 +0000517/// \brief Lookup a builtin function, when name lookup would otherwise
518/// fail.
519static bool LookupBuiltin(Sema &S, LookupResult &R) {
520 Sema::LookupNameKind NameKind = R.getLookupKind();
521
522 // If we didn't find a use of this identifier, and if the identifier
523 // corresponds to a compiler builtin, create the decl object for the builtin
524 // now, injecting it into translation unit scope, and return it.
525 if (NameKind == Sema::LookupOrdinaryName ||
526 NameKind == Sema::LookupRedeclarationWithLinkage) {
527 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
528 if (II) {
Nico Webere1687c52013-06-20 21:44:55 +0000529 if (S.getLangOpts().CPlusPlus11 && S.getLangOpts().GNUMode &&
530 II == S.getFloat128Identifier()) {
531 // libstdc++4.7's type_traits expects type __float128 to exist, so
532 // insert a dummy type to make that header build in gnu++11 mode.
533 R.addDecl(S.getASTContext().getFloat128StubType());
534 return true;
535 }
536
Douglas Gregord3a59182010-02-12 05:48:04 +0000537 // If this is a builtin on this (or all) targets, create the decl.
538 if (unsigned BuiltinID = II->getBuiltinID()) {
539 // In C++, we don't have any predefined library functions like
540 // 'malloc'. Instead, we'll just error.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000541 if (S.getLangOpts().CPlusPlus &&
Douglas Gregord3a59182010-02-12 05:48:04 +0000542 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
543 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000544
545 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
546 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000547 R.isForRedeclaration(),
548 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000549 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000550 return true;
551 }
Douglas Gregord3a59182010-02-12 05:48:04 +0000552 }
553 }
554 }
555
556 return false;
557}
558
Douglas Gregor7454c562010-07-02 20:37:36 +0000559/// \brief Determine whether we can declare a special member function within
560/// the class at this point.
Richard Smith7d125a12012-11-27 21:20:31 +0000561static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +0000562 // We need to have a definition for the class.
563 if (!Class->getDefinition() || Class->isDependentContext())
564 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000565
Douglas Gregor7454c562010-07-02 20:37:36 +0000566 // We can't be in the middle of defining the class.
Richard Smith7d125a12012-11-27 21:20:31 +0000567 return !Class->isBeingDefined();
Douglas Gregor7454c562010-07-02 20:37:36 +0000568}
569
570void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smith7d125a12012-11-27 21:20:31 +0000571 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregora6d69502010-07-02 23:41:54 +0000572 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000573
574 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000575 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000576 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000577
Douglas Gregora6d69502010-07-02 23:41:54 +0000578 // If the copy constructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000579 if (Class->needsImplicitCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +0000580 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000581
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000582 // If the copy assignment operator has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000583 if (Class->needsImplicitCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000584 DeclareImplicitCopyAssignment(Class);
585
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000586 if (getLangOpts().CPlusPlus11) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000587 // If the move constructor has not yet been declared, do so now.
588 if (Class->needsImplicitMoveConstructor())
589 DeclareImplicitMoveConstructor(Class); // might not actually do it
590
591 // If the move assignment operator has not yet been declared, do so now.
592 if (Class->needsImplicitMoveAssignment())
593 DeclareImplicitMoveAssignment(Class); // might not actually do it
594 }
595
Douglas Gregor7454c562010-07-02 20:37:36 +0000596 // If the destructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000597 if (Class->needsImplicitDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000598 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000599}
600
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000601/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000602/// special member function.
603static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
604 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000605 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000606 case DeclarationName::CXXDestructorName:
607 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000608
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000609 case DeclarationName::CXXOperatorName:
610 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000611
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000612 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000613 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000614 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000615
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000616 return false;
617}
618
619/// \brief If there are any implicit member functions with the given name
620/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000621static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000622 DeclarationName Name,
623 const DeclContext *DC) {
624 if (!DC)
625 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000626
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000627 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000628 case DeclarationName::CXXConstructorName:
629 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith7d125a12012-11-27 21:20:31 +0000630 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000631 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000632 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000633 S.DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +0000634 if (Record->needsImplicitCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000635 S.DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000636 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000637 Record->needsImplicitMoveConstructor())
638 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000639 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000640 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000641
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000642 case DeclarationName::CXXDestructorName:
643 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith2be35f52012-12-01 02:35:44 +0000644 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smith7d125a12012-11-27 21:20:31 +0000645 CanDeclareSpecialMemberFunction(Record))
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000646 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000647 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000648
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000649 case DeclarationName::CXXOperatorName:
650 if (Name.getCXXOverloadedOperator() != OO_Equal)
651 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000652
Sebastian Redl22653ba2011-08-30 19:58:05 +0000653 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smith7d125a12012-11-27 21:20:31 +0000654 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000655 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smith2be35f52012-12-01 02:35:44 +0000656 if (Record->needsImplicitCopyAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000657 S.DeclareImplicitCopyAssignment(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000658 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000659 Record->needsImplicitMoveAssignment())
660 S.DeclareImplicitMoveAssignment(Class);
661 }
662 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000663 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000664
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000665 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000666 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000667 }
668}
Douglas Gregor7454c562010-07-02 20:37:36 +0000669
John McCall9f3059a2009-10-09 21:13:30 +0000670// Adds all qualifying matches for a name within a decl context to the
671// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000672static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000673 bool Found = false;
674
Douglas Gregor7454c562010-07-02 20:37:36 +0000675 // Lazily declare C++ special member functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000676 if (S.getLangOpts().CPlusPlus)
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000677 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000678
Douglas Gregor7454c562010-07-02 20:37:36 +0000679 // Perform lookup into this declaration context.
Richard Smithcf4bdde2015-02-21 02:45:19 +0000680 DeclContext::lookup_result DR = DC->lookup(R.getLookupName());
681 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E;
David Blaikieff7d47a2012-12-19 00:45:41 +0000682 ++I) {
John McCall401982f2010-01-20 21:53:11 +0000683 NamedDecl *D = *I;
Douglas Gregor4a814562011-12-14 16:03:29 +0000684 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000685 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000686 Found = true;
687 }
688 }
John McCall9f3059a2009-10-09 21:13:30 +0000689
Douglas Gregord3a59182010-02-12 05:48:04 +0000690 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
691 return true;
692
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000693 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000694 != DeclarationName::CXXConversionFunctionName ||
695 R.getLookupName().getCXXNameType()->isDependentType() ||
696 !isa<CXXRecordDecl>(DC))
697 return Found;
698
699 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000700 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000701 // name lookup. Instead, any conversion function templates visible in the
702 // context of the use are considered. [...]
703 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000704 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000705 return Found;
706
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +0000707 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
708 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruth3a693b72010-01-31 11:44:02 +0000709 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
710 if (!ConvTemplate)
711 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000712
Chandler Carruth3a693b72010-01-31 11:44:02 +0000713 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000714 // add the conversion function template. When we deduce template
715 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000716 // type of the new declaration with the type of the function template.
717 if (R.isForRedeclaration()) {
718 R.addDecl(ConvTemplate);
719 Found = true;
720 continue;
721 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000722
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000723 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000724 // [...] For each such operator, if argument deduction succeeds
725 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000726 // name lookup.
727 //
728 // When referencing a conversion function for any purpose other than
729 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000730 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000731 // specialization into the result set. We do this to avoid forcing all
732 // callers to perform special deduction for conversion functions.
Craig Toppere6706e42012-09-19 02:26:47 +0000733 TemplateDeductionInfo Info(R.getNameLoc());
Craig Topperc3ec1492014-05-26 06:22:03 +0000734 FunctionDecl *Specialization = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000735
736 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000737 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
738 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000739
Chandler Carruth3a693b72010-01-31 11:44:02 +0000740 // Compute the type of the function that we would expect the conversion
741 // function to have, if it were to match the name given.
742 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000743 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
Reid Kleckner78af0702013-08-27 23:08:25 +0000744 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
Richard Smith8acb4282014-07-31 21:57:55 +0000745 EPI.ExceptionSpec = EST_None;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000746 QualType ExpectedType
747 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000748 None, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000749
Chandler Carruth3a693b72010-01-31 11:44:02 +0000750 // Perform template argument deduction against the type that we would
751 // expect the function to have.
Craig Topperc3ec1492014-05-26 06:22:03 +0000752 if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
Chandler Carruth3a693b72010-01-31 11:44:02 +0000753 Specialization, Info)
754 == Sema::TDK_Success) {
755 R.addDecl(Specialization);
756 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000757 }
758 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000759
John McCall9f3059a2009-10-09 21:13:30 +0000760 return Found;
761}
762
John McCallf6c8a4e2009-11-10 07:01:13 +0000763// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000764static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000765CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000766 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000767
768 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
769
John McCallf6c8a4e2009-11-10 07:01:13 +0000770 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000771 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000772
John McCallf6c8a4e2009-11-10 07:01:13 +0000773 // Perform direct name lookup into the namespaces nominated by the
774 // using directives whose common ancestor is this namespace.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000775 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
776 if (LookupDirect(S, R, UUE.getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000777 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000778
779 R.resolveKind();
780
781 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000782}
783
784static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000785 if (DeclContext *Ctx = S->getEntity())
Douglas Gregor700792c2009-02-05 19:25:20 +0000786 return Ctx->isFileContext();
787 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000788}
Douglas Gregored8f2882009-01-30 01:04:22 +0000789
Douglas Gregor66230062010-03-15 14:33:29 +0000790// Find the next outer declaration context from this scope. This
791// routine actually returns the semantic outer context, which may
792// differ from the lexical context (encoded directly in the Scope
793// stack) when we are parsing a member of a class template. In this
794// case, the second element of the pair will be true, to indicate that
795// name lookup should continue searching in this semantic context when
796// it leaves the current template parameter scope.
797static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000798 DeclContext *DC = S->getEntity();
Craig Topperc3ec1492014-05-26 06:22:03 +0000799 DeclContext *Lexical = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000800 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000801 OuterS = OuterS->getParent()) {
802 if (OuterS->getEntity()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000803 Lexical = OuterS->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +0000804 break;
805 }
806 }
807
808 // C++ [temp.local]p8:
809 // In the definition of a member of a class template that appears
810 // outside of the namespace containing the class template
811 // definition, the name of a template-parameter hides the name of
812 // a member of this namespace.
813 //
814 // Example:
815 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000816 // namespace N {
817 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000818 //
819 // template<class T> class B {
820 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000821 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000822 // }
823 //
824 // template<class C> void N::B<C>::f(C) {
825 // C b; // C is the template parameter, not N::C
826 // }
827 //
828 // In this example, the lexical context we return is the
829 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000830 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000831 !S->getParent()->isTemplateParamScope())
832 return std::make_pair(Lexical, false);
833
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000834 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000835 // For the example, this is the scope for the template parameters of
836 // template<class C>.
837 Scope *OutermostTemplateScope = S->getParent();
838 while (OutermostTemplateScope->getParent() &&
839 OutermostTemplateScope->getParent()->isTemplateParamScope())
840 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000841
Douglas Gregor66230062010-03-15 14:33:29 +0000842 // Find the namespace context in which the original scope occurs. In
843 // the example, this is namespace N.
844 DeclContext *Semantic = DC;
845 while (!Semantic->isFileContext())
846 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000847
Douglas Gregor66230062010-03-15 14:33:29 +0000848 // Find the declaration context just outside of the template
849 // parameter scope. This is the context in which the template is
850 // being lexically declaration (a namespace context). In the
851 // example, this is the global scope.
852 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
853 Lexical->Encloses(Semantic))
854 return std::make_pair(Semantic, true);
855
856 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000857}
858
Richard Smith541b38b2013-09-20 01:15:31 +0000859namespace {
860/// An RAII object to specify that we want to find block scope extern
861/// declarations.
862struct FindLocalExternScope {
863 FindLocalExternScope(LookupResult &R)
864 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
865 Decl::IDNS_LocalExtern) {
866 R.setFindLocalExtern(R.getIdentifierNamespace() & Decl::IDNS_Ordinary);
867 }
868 void restore() {
869 R.setFindLocalExtern(OldFindLocalExtern);
870 }
871 ~FindLocalExternScope() {
872 restore();
873 }
874 LookupResult &R;
875 bool OldFindLocalExtern;
876};
877}
878
John McCall27b18f82009-11-17 02:14:36 +0000879bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000880 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000881
882 DeclarationName Name = R.getLookupName();
Richard Smith1c34fb72013-08-13 18:18:50 +0000883 Sema::LookupNameKind NameKind = R.getLookupKind();
John McCall27b18f82009-11-17 02:14:36 +0000884
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000885 // If this is the name of an implicitly-declared special member function,
886 // go through the scope stack to implicitly declare
887 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
888 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +0000889 if (DeclContext *DC = PreS->getEntity())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000890 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
891 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000892
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000893 // Implicitly declare member functions with the name we're looking for, if in
894 // fact we are in a scope where it matters.
895
Douglas Gregor889ceb72009-02-03 19:21:40 +0000896 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000897 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000898 I = IdResolver.begin(Name),
899 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000900
Douglas Gregor889ceb72009-02-03 19:21:40 +0000901 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000902 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000903 // ...During unqualified name lookup (3.4.1), the names appear as if
904 // they were declared in the nearest enclosing namespace which contains
905 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000906 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000907 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000908 //
909 // For example:
910 // namespace A { int i; }
911 // void foo() {
912 // int i;
913 // {
914 // using namespace A;
915 // ++i; // finds local 'i', A::i appears at global scope
916 // }
917 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000918 //
Douglas Gregorcc9406c2013-04-08 23:11:25 +0000919 UnqualUsingDirectiveSet UDirs;
920 bool VisitedUsingDirectives = false;
Richard Smith1c34fb72013-08-13 18:18:50 +0000921 bool LeftStartingScope = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000922 DeclContext *OutsideOfTemplateParamDC = nullptr;
Richard Smith541b38b2013-09-20 01:15:31 +0000923
924 // When performing a scope lookup, we want to find local extern decls.
925 FindLocalExternScope FindLocals(R);
926
Douglas Gregor700792c2009-02-05 19:25:20 +0000927 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000928 DeclContext *Ctx = S->getEntity();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000929
Douglas Gregor889ceb72009-02-03 19:21:40 +0000930 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000931 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000932 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000933 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Richard Smith1c34fb72013-08-13 18:18:50 +0000934 if (NameKind == LookupRedeclarationWithLinkage) {
935 // Determine whether this (or a previous) declaration is
936 // out-of-scope.
937 if (!LeftStartingScope && !Initial->isDeclScope(*I))
938 LeftStartingScope = true;
939
940 // If we found something outside of our starting scope that
Richard Smith9a00bbf2013-10-16 21:12:00 +0000941 // does not have linkage, skip it. If it's a template parameter,
942 // we still find it, so we can diagnose the invalid redeclaration.
943 if (LeftStartingScope && !((*I)->hasLinkage()) &&
944 !(*I)->isTemplateParameter()) {
Richard Smith1c34fb72013-08-13 18:18:50 +0000945 R.setShadowed();
946 continue;
947 }
948 }
949
John McCall9f3059a2009-10-09 21:13:30 +0000950 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +0000951 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000952 }
953 }
John McCall9f3059a2009-10-09 21:13:30 +0000954 if (Found) {
955 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000956 if (S->isClassScope())
957 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
958 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000959 return true;
960 }
961
Richard Smith1c34fb72013-08-13 18:18:50 +0000962 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
Richard Smith114394f2013-08-09 04:35:01 +0000963 // C++11 [class.friend]p11:
964 // If a friend declaration appears in a local class and the name
965 // specified is an unqualified name, a prior declaration is
966 // looked up without considering scopes that are outside the
967 // innermost enclosing non-class scope.
968 return false;
969 }
970
Douglas Gregor66230062010-03-15 14:33:29 +0000971 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
972 S->getParent() && !S->getParent()->isTemplateParamScope()) {
973 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000974 // found nothing, so look into the contexts between the
Douglas Gregor66230062010-03-15 14:33:29 +0000975 // lexical and semantic declaration contexts returned by
976 // findOuterContext(). This implements the name lookup behavior
977 // of C++ [temp.local]p8.
978 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +0000979 OutsideOfTemplateParamDC = nullptr;
Douglas Gregor66230062010-03-15 14:33:29 +0000980 }
981
982 if (Ctx) {
983 DeclContext *OuterCtx;
984 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000985 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregor66230062010-03-15 14:33:29 +0000986 if (SearchAfterTemplateScope)
987 OutsideOfTemplateParamDC = OuterCtx;
988
Douglas Gregorea166062010-03-15 15:26:48 +0000989 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000990 // We do not directly look into transparent contexts, since
991 // those entities will be found in the nearest enclosing
992 // non-transparent context.
993 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000994 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000995
996 // We do not look directly into function or method contexts,
997 // since all of the local variables and parameters of the
998 // function/method are present within the Scope.
999 if (Ctx->isFunctionOrMethod()) {
1000 // If we have an Objective-C instance method, look for ivars
1001 // in the corresponding interface.
1002 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
1003 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1004 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1005 ObjCInterfaceDecl *ClassDeclared;
1006 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001007 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +00001008 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001009 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1010 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +00001011 R.resolveKind();
1012 return true;
1013 }
1014 }
1015 }
1016 }
1017
1018 continue;
1019 }
1020
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001021 // If this is a file context, we need to perform unqualified name
1022 // lookup considering using directives.
1023 if (Ctx->isFileContext()) {
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001024 // If we haven't handled using directives yet, do so now.
1025 if (!VisitedUsingDirectives) {
1026 // Add using directives from this context up to the top level.
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001027 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1028 if (UCtx->isTransparentContext())
1029 continue;
1030
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001031 UDirs.visit(UCtx, UCtx);
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001032 }
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001033
1034 // Find the innermost file scope, so we can add using directives
1035 // from local scopes.
1036 Scope *InnermostFileScope = S;
1037 while (InnermostFileScope &&
1038 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1039 InnermostFileScope = InnermostFileScope->getParent();
1040 UDirs.visitScopeChain(Initial, InnermostFileScope);
1041
1042 UDirs.done();
1043
1044 VisitedUsingDirectives = true;
1045 }
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001046
1047 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1048 R.resolveKind();
1049 return true;
1050 }
1051
1052 continue;
1053 }
1054
Douglas Gregor7f737c02009-09-10 16:57:35 +00001055 // Perform qualified name lookup into this context.
1056 // FIXME: In some cases, we know that every name that could be found by
1057 // this qualified name lookup will also be on the identifier chain. For
1058 // example, inside a class without any base classes, we never need to
1059 // perform qualified lookup because all of the members are on top of the
1060 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001061 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +00001062 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +00001063 }
Douglas Gregor700792c2009-02-05 19:25:20 +00001064 }
Douglas Gregored8f2882009-01-30 01:04:22 +00001065 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001066
John McCallf6c8a4e2009-11-10 07:01:13 +00001067 // Stop if we ran out of scopes.
1068 // FIXME: This really, really shouldn't be happening.
1069 if (!S) return false;
1070
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001071 // If we are looking for members, no need to look into global/namespace scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00001072 if (NameKind == LookupMemberName)
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001073 return false;
1074
Douglas Gregor700792c2009-02-05 19:25:20 +00001075 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +00001076 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +00001077 //
Mike Stump87c57ac2009-05-16 07:39:55 +00001078 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1079 // don't build it for each lookup!
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001080 if (!VisitedUsingDirectives) {
1081 UDirs.visitScopeChain(Initial, S);
1082 UDirs.done();
1083 }
Richard Smith541b38b2013-09-20 01:15:31 +00001084
1085 // If we're not performing redeclaration lookup, do not look for local
1086 // extern declarations outside of a function scope.
1087 if (!R.isForRedeclaration())
1088 FindLocals.restore();
1089
Douglas Gregor700792c2009-02-05 19:25:20 +00001090 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +00001091 // Unqualified name lookup in C++ requires looking into scopes
1092 // that aren't strictly lexical, and therefore we walk through the
1093 // context as well as walking through the scopes.
1094 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001095 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +00001096 bool Found = false;
John McCall48871652010-08-21 09:40:31 +00001097 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001098 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001099 // We found something. Look for anything else in our scope
1100 // with this same name and in an acceptable identifier
1101 // namespace, so that we can construct an overload set if we
1102 // need to.
John McCall9f3059a2009-10-09 21:13:30 +00001103 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +00001104 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001105 }
1106 }
1107
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001108 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +00001109 R.resolveKind();
1110 return true;
1111 }
1112
Ted Kremenekc37877d2013-10-08 17:08:03 +00001113 DeclContext *Ctx = S->getEntity();
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001114 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1115 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1116 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001117 // found nothing, so look into the contexts between the
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001118 // lexical and semantic declaration contexts returned by
1119 // findOuterContext(). This implements the name lookup behavior
1120 // of C++ [temp.local]p8.
1121 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +00001122 OutsideOfTemplateParamDC = nullptr;
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001123 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001124
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001125 if (Ctx) {
1126 DeclContext *OuterCtx;
1127 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001128 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001129 if (SearchAfterTemplateScope)
1130 OutsideOfTemplateParamDC = OuterCtx;
1131
1132 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1133 // We do not directly look into transparent contexts, since
1134 // those entities will be found in the nearest enclosing
1135 // non-transparent context.
1136 if (Ctx->isTransparentContext())
1137 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001138
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001139 // If we have a context, and it's not a context stashed in the
1140 // template parameter scope for an out-of-line definition, also
1141 // look into that context.
1142 if (!(Found && S && S->isTemplateParamScope())) {
1143 assert(Ctx->isFileContext() &&
1144 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001145
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001146 // Look into context considering using-directives.
1147 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1148 Found = true;
1149 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001150
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001151 if (Found) {
1152 R.resolveKind();
1153 return true;
1154 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001155
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001156 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1157 return false;
1158 }
1159 }
1160
Douglas Gregor3ce74932010-02-05 07:07:10 +00001161 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001162 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001163 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001164
John McCall9f3059a2009-10-09 21:13:30 +00001165 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001166}
1167
Richard Smith0e5d7b82013-07-25 23:08:39 +00001168/// \brief Find the declaration that a class temploid member specialization was
1169/// instantiated from, or the member itself if it is an explicit specialization.
1170static Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) {
1171 return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom();
1172}
1173
Richard Smithd9ba2242015-05-07 03:54:19 +00001174void Sema::makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc) {
1175 if (auto *Listener = getASTMutationListener())
Richard Smith4caa4492015-05-15 02:34:32 +00001176 Listener->RedefinedHiddenDefinition(ND,
1177 PP.getModuleContainingLocation(Loc));
Richard Smithd9ba2242015-05-07 03:54:19 +00001178 ND->setHidden(false);
1179}
1180
Richard Smith0e5d7b82013-07-25 23:08:39 +00001181/// \brief Find the module in which the given declaration was defined.
1182static Module *getDefiningModule(Decl *Entity) {
1183 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1184 // If this function was instantiated from a template, the defining module is
1185 // the module containing the pattern.
1186 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1187 Entity = Pattern;
1188 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
Reid Klecknere7367d62014-10-14 20:28:40 +00001189 if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
1190 Entity = Pattern;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001191 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1192 if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo())
1193 Entity = getInstantiatedFrom(ED, MSInfo);
1194 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1195 // FIXME: Map from variable template specializations back to the template.
1196 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo())
1197 Entity = getInstantiatedFrom(VD, MSInfo);
1198 }
1199
1200 // Walk up to the containing context. That might also have been instantiated
1201 // from a template.
1202 DeclContext *Context = Entity->getDeclContext();
1203 if (Context->isFileContext())
1204 return Entity->getOwningModule();
1205 return getDefiningModule(cast<Decl>(Context));
1206}
1207
1208llvm::DenseSet<Module*> &Sema::getLookupModules() {
1209 unsigned N = ActiveTemplateInstantiations.size();
1210 for (unsigned I = ActiveTemplateInstantiationLookupModules.size();
1211 I != N; ++I) {
1212 Module *M = getDefiningModule(ActiveTemplateInstantiations[I].Entity);
1213 if (M && !LookupModulesCache.insert(M).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00001214 M = nullptr;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001215 ActiveTemplateInstantiationLookupModules.push_back(M);
1216 }
1217 return LookupModulesCache;
1218}
1219
1220/// \brief Determine whether a declaration is visible to name lookup.
1221///
1222/// This routine determines whether the declaration D is visible in the current
1223/// lookup context, taking into account the current template instantiation
1224/// stack. During template instantiation, a declaration is visible if it is
1225/// visible from a module containing any entity on the template instantiation
1226/// path (by instantiating a template, you allow it to see the declarations that
1227/// your module can see, including those later on in your module).
1228bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001229 assert(D->isHidden() && "should not call this: not in slow case");
Richard Smith0e5d7b82013-07-25 23:08:39 +00001230 Module *DeclModule = D->getOwningModule();
1231 assert(DeclModule && "hidden decl not from a module");
1232
Richard Smithbe3980b2015-03-27 00:41:57 +00001233 // If this declaration is not at namespace scope nor module-private,
1234 // then it is visible if its lexical parent has a visible definition.
1235 DeclContext *DC = D->getLexicalDeclContext();
1236 if (!D->isModulePrivate() &&
1237 DC && !DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) {
Richard Smith9a71c992015-03-27 20:16:58 +00001238 if (SemaRef.hasVisibleDefinition(cast<NamedDecl>(DC))) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001239 if (SemaRef.ActiveTemplateInstantiations.empty()) {
1240 // Cache the fact that this declaration is implicitly visible because
1241 // its parent has a visible definition.
1242 D->setHidden(false);
1243 }
1244 return true;
1245 }
1246 return false;
1247 }
1248
Richard Smith0e5d7b82013-07-25 23:08:39 +00001249 // Find the extra places where we need to look.
1250 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
1251 if (LookupModules.empty())
1252 return false;
1253
1254 // If our lookup set contains the decl's module, it's visible.
1255 if (LookupModules.count(DeclModule))
1256 return true;
1257
1258 // If the declaration isn't exported, it's not visible in any other module.
1259 if (D->isModulePrivate())
1260 return false;
1261
1262 // Check whether DeclModule is transitively exported to an import of
1263 // the lookup set.
1264 for (llvm::DenseSet<Module *>::iterator I = LookupModules.begin(),
1265 E = LookupModules.end();
1266 I != E; ++I)
1267 if ((*I)->isModuleVisible(DeclModule))
1268 return true;
1269 return false;
1270}
1271
Douglas Gregor4a814562011-12-14 16:03:29 +00001272/// \brief Retrieve the visible declaration corresponding to D, if any.
1273///
1274/// This routine determines whether the declaration D is visible in the current
1275/// module, with the current imports. If not, it checks whether any
1276/// redeclaration of D is visible, and if so, returns that declaration.
Richard Smith0e5d7b82013-07-25 23:08:39 +00001277///
Douglas Gregor4a814562011-12-14 16:03:29 +00001278/// \returns D, or a visible previous declaration of D, whichever is more recent
1279/// and visible. If no declaration of D is visible, returns null.
Richard Smithe156254d2013-08-20 20:35:18 +00001280static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
1281 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
Richard Smith0e5d7b82013-07-25 23:08:39 +00001282
Aaron Ballman86c93902014-03-06 23:45:36 +00001283 for (auto RD : D->redecls()) {
1284 if (auto ND = dyn_cast<NamedDecl>(RD)) {
Richard Smithe8292b12015-02-10 03:28:10 +00001285 // FIXME: This is wrong in the case where the previous declaration is not
1286 // visible in the same scope as D. This needs to be done much more
1287 // carefully.
Richard Smithe156254d2013-08-20 20:35:18 +00001288 if (LookupResult::isVisible(SemaRef, ND))
Douglas Gregor54079202012-01-06 22:05:37 +00001289 return ND;
1290 }
Douglas Gregor4a814562011-12-14 16:03:29 +00001291 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001292
Craig Topperc3ec1492014-05-26 06:22:03 +00001293 return nullptr;
Douglas Gregor4a814562011-12-14 16:03:29 +00001294}
1295
Richard Smithe156254d2013-08-20 20:35:18 +00001296NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +00001297 return findAcceptableDecl(getSema(), D);
Richard Smithe156254d2013-08-20 20:35:18 +00001298}
1299
Douglas Gregor34074322009-01-14 22:20:51 +00001300/// @brief Perform unqualified name lookup starting from a given
1301/// scope.
1302///
1303/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1304/// used to find names within the current scope. For example, 'x' in
1305/// @code
1306/// int x;
1307/// int f() {
1308/// return x; // unqualified name look finds 'x' in the global scope
1309/// }
1310/// @endcode
1311///
1312/// Different lookup criteria can find different names. For example, a
1313/// particular scope can have both a struct and a function of the same
1314/// name, and each can be found by certain lookup criteria. For more
1315/// information about lookup criteria, see the documentation for the
1316/// class LookupCriteria.
1317///
1318/// @param S The scope from which unqualified name lookup will
1319/// begin. If the lookup criteria permits, name lookup may also search
1320/// in the parent scopes.
1321///
James Dennett91738ff2012-06-22 10:32:46 +00001322/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1323/// look up and the lookup kind), and is updated with the results of lookup
1324/// including zero or more declarations and possibly additional information
1325/// used to diagnose ambiguities.
Douglas Gregor34074322009-01-14 22:20:51 +00001326///
James Dennett91738ff2012-06-22 10:32:46 +00001327/// @returns \c true if lookup succeeded and false otherwise.
John McCall27b18f82009-11-17 02:14:36 +00001328bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1329 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001330 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001331
John McCall27b18f82009-11-17 02:14:36 +00001332 LookupNameKind NameKind = R.getLookupKind();
1333
David Blaikiebbafb8a2012-03-11 07:00:24 +00001334 if (!getLangOpts().CPlusPlus) {
Douglas Gregor34074322009-01-14 22:20:51 +00001335 // Unqualified name lookup in C/Objective-C is purely lexical, so
1336 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001337 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001338 // Find the nearest non-transparent declaration scope.
1339 while (!(S->getFlags() & Scope::DeclScope) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001340 (S->getEntity() && S->getEntity()->isTransparentContext()))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001341 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001342 }
1343
Richard Smith541b38b2013-09-20 01:15:31 +00001344 // When performing a scope lookup, we want to find local extern decls.
1345 FindLocalExternScope FindLocals(R);
1346
Douglas Gregor34074322009-01-14 22:20:51 +00001347 // Scan up the scope chain looking for a decl that matches this
1348 // identifier that is in the appropriate namespace. This search
1349 // should not take long, as shadowing of names is uncommon, and
1350 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001351 bool LeftStartingScope = false;
1352
Douglas Gregored8f2882009-01-30 01:04:22 +00001353 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001354 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001355 I != IEnd; ++I)
Richard Smith0e5d7b82013-07-25 23:08:39 +00001356 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001357 if (NameKind == LookupRedeclarationWithLinkage) {
1358 // Determine whether this (or a previous) declaration is
1359 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001360 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001361 LeftStartingScope = true;
1362
1363 // If we found something outside of our starting scope that
1364 // does not have linkage, skip it.
Richard Smith1c34fb72013-08-13 18:18:50 +00001365 if (LeftStartingScope && !((*I)->hasLinkage())) {
1366 R.setShadowed();
Douglas Gregoreddf4332009-02-24 20:03:32 +00001367 continue;
Richard Smith1c34fb72013-08-13 18:18:50 +00001368 }
Douglas Gregoreddf4332009-02-24 20:03:32 +00001369 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001370 else if (NameKind == LookupObjCImplicitSelfParam &&
1371 !isa<ImplicitParamDecl>(*I))
1372 continue;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001373
Douglas Gregor4a814562011-12-14 16:03:29 +00001374 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001375
Douglas Gregorb59643b2012-01-03 23:26:26 +00001376 // Check whether there are any other declarations with the same name
1377 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001378 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001379 // Find the scope in which this declaration was declared (if it
1380 // actually exists in a Scope).
1381 while (S && !S->isDeclScope(D))
1382 S = S->getParent();
1383
1384 // If the scope containing the declaration is the translation unit,
1385 // then we'll need to perform our checks based on the matching
1386 // DeclContexts rather than matching scopes.
1387 if (S && isNamespaceOrTranslationUnitScope(S))
Craig Topperc3ec1492014-05-26 06:22:03 +00001388 S = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001389
1390 // Compute the DeclContext, if we need it.
Craig Topperc3ec1492014-05-26 06:22:03 +00001391 DeclContext *DC = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001392 if (!S)
1393 DC = (*I)->getDeclContext()->getRedeclContext();
1394
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001395 IdentifierResolver::iterator LastI = I;
1396 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001397 if (S) {
1398 // Match based on scope.
1399 if (!S->isDeclScope(*LastI))
1400 break;
1401 } else {
1402 // Match based on DeclContext.
1403 DeclContext *LastDC
1404 = (*LastI)->getDeclContext()->getRedeclContext();
1405 if (!LastDC->Equals(DC))
1406 break;
1407 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001408
1409 // If the declaration is in the right namespace and visible, add it.
1410 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1411 R.addDecl(LastD);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001412 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001413
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001414 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001415 }
Richard Smith541b38b2013-09-20 01:15:31 +00001416
John McCall9f3059a2009-10-09 21:13:30 +00001417 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001418 }
Douglas Gregor34074322009-01-14 22:20:51 +00001419 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001420 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001421 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001422 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001423 }
1424
1425 // If we didn't find a use of this identifier, and if the identifier
1426 // corresponds to a compiler builtin, create the decl object for the builtin
1427 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001428 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1429 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001430
Axel Naumann016538a2011-02-24 16:47:47 +00001431 // If we didn't find a use of this identifier, the ExternalSource
1432 // may be able to handle the situation.
1433 // Note: some lookup failures are expected!
1434 // See e.g. R.isForRedeclaration().
1435 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001436}
1437
John McCall6538c932009-10-10 05:48:19 +00001438/// @brief Perform qualified name lookup in the namespaces nominated by
1439/// using directives by the given context.
1440///
1441/// C++98 [namespace.qual]p2:
James Dennett51a8d8b2012-06-19 21:05:49 +00001442/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6538c932009-10-10 05:48:19 +00001443/// (where X is the global namespace), let S be the set of all
1444/// declarations of m in X and in the transitive closure of all
1445/// namespaces nominated by using-directives in X and its used
1446/// namespaces, except that using-directives are ignored in any
1447/// namespace, including X, directly containing one or more
1448/// declarations of m. No namespace is searched more than once in
1449/// the lookup of a name. If S is the empty set, the program is
1450/// ill-formed. Otherwise, if S has exactly one member, or if the
1451/// context of the reference is a using-declaration
1452/// (namespace.udecl), S is the required set of declarations of
1453/// m. Otherwise if the use of m is not one that allows a unique
1454/// declaration to be chosen from S, the program is ill-formed.
James Dennett51a8d8b2012-06-19 21:05:49 +00001455///
John McCall6538c932009-10-10 05:48:19 +00001456/// C++98 [namespace.qual]p5:
1457/// During the lookup of a qualified namespace member name, if the
1458/// lookup finds more than one declaration of the member, and if one
1459/// declaration introduces a class name or enumeration name and the
1460/// other declarations either introduce the same object, the same
1461/// enumerator or a set of functions, the non-type name hides the
1462/// class or enumeration name if and only if the declarations are
1463/// from the same namespace; otherwise (the declarations are from
1464/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001465static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001466 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001467 assert(StartDC->isFileContext() && "start context is not a file context");
1468
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001469 DeclContext::udir_range UsingDirectives = StartDC->using_directives();
1470 if (UsingDirectives.begin() == UsingDirectives.end()) return false;
John McCall6538c932009-10-10 05:48:19 +00001471
1472 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001473 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001474 Visited.insert(StartDC);
1475
1476 // We have not yet looked into these namespaces, much less added
1477 // their "using-children" to the queue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001478 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001479
1480 // We have already looked into the initial namespace; seed the queue
1481 // with its using-children.
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001482 for (auto *I : UsingDirectives) {
1483 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +00001484 if (Visited.insert(ND).second)
John McCall6538c932009-10-10 05:48:19 +00001485 Queue.push_back(ND);
1486 }
1487
1488 // The easiest way to implement the restriction in [namespace.qual]p5
1489 // is to check whether any of the individual results found a tag
1490 // and, if so, to declare an ambiguity if the final result is not
1491 // a tag.
1492 bool FoundTag = false;
1493 bool FoundNonTag = false;
1494
John McCall5cebab12009-11-18 07:57:50 +00001495 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001496
1497 bool Found = false;
1498 while (!Queue.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001499 NamespaceDecl *ND = Queue.pop_back_val();
John McCall6538c932009-10-10 05:48:19 +00001500
1501 // We go through some convolutions here to avoid copying results
1502 // between LookupResults.
1503 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001504 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001505 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001506
1507 if (FoundDirect) {
1508 // First do any local hiding.
1509 DirectR.resolveKind();
1510
1511 // If the local result is a tag, remember that.
1512 if (DirectR.isSingleTagDecl())
1513 FoundTag = true;
1514 else
1515 FoundNonTag = true;
1516
1517 // Append the local results to the total results if necessary.
1518 if (UseLocal) {
1519 R.addAllDecls(LocalR);
1520 LocalR.clear();
1521 }
1522 }
1523
1524 // If we find names in this namespace, ignore its using directives.
1525 if (FoundDirect) {
1526 Found = true;
1527 continue;
1528 }
1529
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001530 for (auto I : ND->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00001531 NamespaceDecl *Nom = I->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +00001532 if (Visited.insert(Nom).second)
John McCall6538c932009-10-10 05:48:19 +00001533 Queue.push_back(Nom);
1534 }
1535 }
1536
1537 if (Found) {
1538 if (FoundTag && FoundNonTag)
1539 R.setAmbiguousQualifiedTagHiding();
1540 else
1541 R.resolveKind();
1542 }
1543
1544 return Found;
1545}
1546
Douglas Gregor39982192010-08-15 06:18:01 +00001547/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001548static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor39982192010-08-15 06:18:01 +00001549 CXXBasePath &Path,
1550 void *Name) {
1551 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001552
Douglas Gregor39982192010-08-15 06:18:01 +00001553 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1554 Path.Decls = BaseRecord->lookup(N);
David Blaikieff7d47a2012-12-19 00:45:41 +00001555 return !Path.Decls.empty();
Douglas Gregor39982192010-08-15 06:18:01 +00001556}
1557
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001558/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001559/// static members, nested types, and enumerators.
1560template<typename InputIterator>
1561static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1562 Decl *D = (*First)->getUnderlyingDecl();
1563 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1564 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001565
Douglas Gregorc0d24902010-10-22 22:08:47 +00001566 if (isa<CXXMethodDecl>(D)) {
1567 // Determine whether all of the methods are static.
1568 bool AllMethodsAreStatic = true;
1569 for(; First != Last; ++First) {
1570 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001571
Douglas Gregorc0d24902010-10-22 22:08:47 +00001572 if (!isa<CXXMethodDecl>(D)) {
1573 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1574 break;
1575 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001576
Douglas Gregorc0d24902010-10-22 22:08:47 +00001577 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1578 AllMethodsAreStatic = false;
1579 break;
1580 }
1581 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001582
Douglas Gregorc0d24902010-10-22 22:08:47 +00001583 if (AllMethodsAreStatic)
1584 return true;
1585 }
1586
1587 return false;
1588}
1589
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001590/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001591///
1592/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1593/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001594/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001595///
1596/// Different lookup criteria can find different names. For example, a
1597/// particular scope can have both a struct and a function of the same
1598/// name, and each can be found by certain lookup criteria. For more
1599/// information about lookup criteria, see the documentation for the
1600/// class LookupCriteria.
1601///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001602/// \param R captures both the lookup criteria and any lookup results found.
1603///
1604/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001605/// search. If the lookup criteria permits, name lookup may also search
1606/// in the parent contexts or (for C++ classes) base classes.
1607///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001608/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001609/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001610///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001611/// \returns true if lookup succeeded, false if it failed.
1612bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1613 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001614 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001615
John McCall27b18f82009-11-17 02:14:36 +00001616 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001617 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001618
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001619 // Make sure that the declaration context is complete.
1620 assert((!isa<TagDecl>(LookupCtx) ||
1621 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00001622 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith7d137e32012-03-23 03:33:32 +00001623 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001624 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001625
Douglas Gregor34074322009-01-14 22:20:51 +00001626 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001627 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001628 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001629 if (isa<CXXRecordDecl>(LookupCtx))
1630 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001631 return true;
1632 }
Douglas Gregor34074322009-01-14 22:20:51 +00001633
John McCall6538c932009-10-10 05:48:19 +00001634 // Don't descend into implied contexts for redeclarations.
1635 // C++98 [namespace.qual]p6:
1636 // In a declaration for a namespace member in which the
1637 // declarator-id is a qualified-id, given that the qualified-id
1638 // for the namespace member has the form
1639 // nested-name-specifier unqualified-id
1640 // the unqualified-id shall name a member of the namespace
1641 // designated by the nested-name-specifier.
1642 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001643 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001644 return false;
1645
John McCall27b18f82009-11-17 02:14:36 +00001646 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001647 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001648 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001649
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001650 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001651 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001652 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001653 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001654 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001655
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001656 // If we're performing qualified name lookup into a dependent class,
1657 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001658 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001659 // template instantiation time (at which point all bases will be available)
1660 // or we have to fail.
1661 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1662 LookupRec->hasAnyDependentBases()) {
1663 R.setNotFoundInCurrentInstantiation();
1664 return false;
1665 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001666
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001667 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001668 CXXBasePaths Paths;
1669 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001670
1671 // Look for this member in our base classes
Craig Topperc3ec1492014-05-26 06:22:03 +00001672 CXXRecordDecl::BaseMatchesCallback *BaseCallback = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00001673 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001674 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001675 case LookupOrdinaryName:
1676 case LookupMemberName:
1677 case LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +00001678 case LookupLocalFriendName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001679 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1680 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001681
Douglas Gregor36d1b142009-10-06 17:59:45 +00001682 case LookupTagName:
1683 BaseCallback = &CXXRecordDecl::FindTagMember;
1684 break;
John McCall84d87672009-12-10 09:41:52 +00001685
Douglas Gregor39982192010-08-15 06:18:01 +00001686 case LookupAnyName:
1687 BaseCallback = &LookupAnyMember;
1688 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001689
John McCall84d87672009-12-10 09:41:52 +00001690 case LookupUsingDeclName:
1691 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001692
Douglas Gregor36d1b142009-10-06 17:59:45 +00001693 case LookupOperatorName:
1694 case LookupNamespaceName:
1695 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001696 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001697 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001698 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001699
Douglas Gregor36d1b142009-10-06 17:59:45 +00001700 case LookupNestedNameSpecifierName:
1701 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1702 break;
1703 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001704
John McCall27b18f82009-11-17 02:14:36 +00001705 if (!LookupRec->lookupInBases(BaseCallback,
1706 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001707 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001708
John McCall553c0792010-01-23 00:46:32 +00001709 R.setNamingClass(LookupRec);
1710
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001711 // C++ [class.member.lookup]p2:
1712 // [...] If the resulting set of declarations are not all from
1713 // sub-objects of the same type, or the set has a nonstatic member
1714 // and includes members from distinct sub-objects, there is an
1715 // ambiguity and the program is ill-formed. Otherwise that set is
1716 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001717 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001718 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001719 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001720
Douglas Gregor36d1b142009-10-06 17:59:45 +00001721 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001722 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001723 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001724
John McCall401982f2010-01-20 21:53:11 +00001725 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1726 // across all paths.
1727 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001728
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001729 // Determine whether we're looking at a distinct sub-object or not.
1730 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001731 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001732 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1733 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001734 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001735 }
1736
Douglas Gregorc0d24902010-10-22 22:08:47 +00001737 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001738 != Context.getCanonicalType(PathElement.Base->getType())) {
1739 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001740 // different types. If the declaration sets aren't the same, this
Nikola Smiljanic1c125682014-07-09 05:42:35 +00001741 // lookup is ambiguous.
David Blaikieff7d47a2012-12-19 00:45:41 +00001742 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00001743 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikieff7d47a2012-12-19 00:45:41 +00001744 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
1745 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001746
David Blaikieff7d47a2012-12-19 00:45:41 +00001747 while (FirstD != FirstPath->Decls.end() &&
1748 CurrentD != Path->Decls.end()) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00001749 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1750 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1751 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001752
Douglas Gregorc0d24902010-10-22 22:08:47 +00001753 ++FirstD;
1754 ++CurrentD;
1755 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001756
David Blaikieff7d47a2012-12-19 00:45:41 +00001757 if (FirstD == FirstPath->Decls.end() &&
1758 CurrentD == Path->Decls.end())
Douglas Gregorc0d24902010-10-22 22:08:47 +00001759 continue;
1760 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001761
John McCall9f3059a2009-10-09 21:13:30 +00001762 R.setAmbiguousBaseSubobjectTypes(Paths);
1763 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001764 }
1765
Douglas Gregorc0d24902010-10-22 22:08:47 +00001766 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001767 // We have a different subobject of the same type.
1768
1769 // C++ [class.member.lookup]p5:
1770 // A static member, a nested type or an enumerator defined in
1771 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001772 // has more than one base class subobject of type T.
David Blaikieff7d47a2012-12-19 00:45:41 +00001773 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001774 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001775
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001776 // We have found a nonstatic member name in multiple, distinct
1777 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001778 R.setAmbiguousBaseSubobjects(Paths);
1779 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001780 }
1781 }
1782
1783 // Lookup in a base class succeeded; return these results.
1784
Aaron Ballman1e606f42014-07-15 22:03:49 +00001785 for (auto *D : Paths.front().Decls) {
John McCall553c0792010-01-23 00:46:32 +00001786 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1787 D->getAccess());
1788 R.addDecl(D, AS);
1789 }
John McCall9f3059a2009-10-09 21:13:30 +00001790 R.resolveKind();
1791 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001792}
1793
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00001794/// \brief Performs qualified name lookup or special type of lookup for
1795/// "__super::" scope specifier.
1796///
1797/// This routine is a convenience overload meant to be called from contexts
1798/// that need to perform a qualified name lookup with an optional C++ scope
1799/// specifier that might require special kind of lookup.
1800///
1801/// \param R captures both the lookup criteria and any lookup results found.
1802///
1803/// \param LookupCtx The context in which qualified name lookup will
1804/// search.
1805///
1806/// \param SS An optional C++ scope-specifier.
1807///
1808/// \returns true if lookup succeeded, false if it failed.
1809bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1810 CXXScopeSpec &SS) {
1811 auto *NNS = SS.getScopeRep();
1812 if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
1813 return LookupInSuper(R, NNS->getAsRecordDecl());
1814 else
1815
1816 return LookupQualifiedName(R, LookupCtx);
1817}
1818
Douglas Gregor34074322009-01-14 22:20:51 +00001819/// @brief Performs name lookup for a name that was parsed in the
1820/// source code, and may contain a C++ scope specifier.
1821///
1822/// This routine is a convenience routine meant to be called from
1823/// contexts that receive a name and an optional C++ scope specifier
1824/// (e.g., "N::M::x"). It will then perform either qualified or
1825/// unqualified name lookup (with LookupQualifiedName or LookupName,
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00001826/// respectively) on the given name and return those results. It will
1827/// perform a special type of lookup for "__super::" scope specifier.
Douglas Gregor34074322009-01-14 22:20:51 +00001828///
1829/// @param S The scope from which unqualified name lookup will
1830/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001831///
Douglas Gregore861bac2009-08-25 22:51:20 +00001832/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001833///
Douglas Gregore861bac2009-08-25 22:51:20 +00001834/// @param EnteringContext Indicates whether we are going to enter the
1835/// context of the scope-specifier SS (if present).
1836///
John McCall9f3059a2009-10-09 21:13:30 +00001837/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001838bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001839 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001840 if (SS && SS->isInvalid()) {
1841 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001842 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001843 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001844 }
Mike Stump11289f42009-09-09 15:08:12 +00001845
Douglas Gregore861bac2009-08-25 22:51:20 +00001846 if (SS && SS->isSet()) {
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00001847 NestedNameSpecifier *NNS = SS->getScopeRep();
1848 if (NNS->getKind() == NestedNameSpecifier::Super)
1849 return LookupInSuper(R, NNS->getAsRecordDecl());
1850
Douglas Gregore861bac2009-08-25 22:51:20 +00001851 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001852 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001853 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001854 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001855 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001856
John McCall27b18f82009-11-17 02:14:36 +00001857 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00001858 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001859 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001860
Douglas Gregore861bac2009-08-25 22:51:20 +00001861 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001862 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001863 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00001864 R.setNotFoundInCurrentInstantiation();
1865 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00001866 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001867 }
1868
Mike Stump11289f42009-09-09 15:08:12 +00001869 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001870 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001871}
1872
Nikola Smiljanic67860242014-09-26 00:28:20 +00001873/// \brief Perform qualified name lookup into all base classes of the given
1874/// class.
1875///
1876/// \param R captures both the lookup criteria and any lookup results found.
1877///
1878/// \param Class The context in which qualified name lookup will
1879/// search. Name lookup will search in all base classes merging the results.
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00001880///
1881/// @returns True if any decls were found (but possibly ambiguous)
1882bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
Nikola Smiljanic67860242014-09-26 00:28:20 +00001883 for (const auto &BaseSpec : Class->bases()) {
1884 CXXRecordDecl *RD = cast<CXXRecordDecl>(
1885 BaseSpec.getType()->castAs<RecordType>()->getDecl());
1886 LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
1887 Result.setBaseObjectType(Context.getRecordType(Class));
1888 LookupQualifiedName(Result, RD);
1889 for (auto *Decl : Result)
1890 R.addDecl(Decl);
1891 }
1892
1893 R.resolveKind();
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00001894
1895 return !R.empty();
Nikola Smiljanic67860242014-09-26 00:28:20 +00001896}
Douglas Gregor889ceb72009-02-03 19:21:40 +00001897
James Dennett41725122012-06-22 10:16:05 +00001898/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001899/// from name lookup.
1900///
James Dennett41725122012-06-22 10:16:05 +00001901/// \param Result The result of the ambiguous lookup to be diagnosed.
Serge Pavlov99292092013-08-29 07:23:24 +00001902void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001903 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1904
John McCall27b18f82009-11-17 02:14:36 +00001905 DeclarationName Name = Result.getLookupName();
1906 SourceLocation NameLoc = Result.getNameLoc();
1907 SourceRange LookupRange = Result.getContextRange();
1908
John McCall6538c932009-10-10 05:48:19 +00001909 switch (Result.getAmbiguityKind()) {
1910 case LookupResult::AmbiguousBaseSubobjects: {
1911 CXXBasePaths *Paths = Result.getBasePaths();
1912 QualType SubobjectType = Paths->front().back().Base->getType();
1913 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1914 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1915 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001916
David Blaikieff7d47a2012-12-19 00:45:41 +00001917 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6538c932009-10-10 05:48:19 +00001918 while (isa<CXXMethodDecl>(*Found) &&
1919 cast<CXXMethodDecl>(*Found)->isStatic())
1920 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001921
John McCall6538c932009-10-10 05:48:19 +00001922 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
Serge Pavlov99292092013-08-29 07:23:24 +00001923 break;
John McCall6538c932009-10-10 05:48:19 +00001924 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001925
John McCall6538c932009-10-10 05:48:19 +00001926 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001927 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1928 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001929
John McCall6538c932009-10-10 05:48:19 +00001930 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001931 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001932 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1933 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001934 Path != PathEnd; ++Path) {
David Blaikieff7d47a2012-12-19 00:45:41 +00001935 Decl *D = Path->Decls.front();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001936 if (DeclsPrinted.insert(D).second)
1937 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1938 }
Serge Pavlov99292092013-08-29 07:23:24 +00001939 break;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001940 }
1941
John McCall6538c932009-10-10 05:48:19 +00001942 case LookupResult::AmbiguousTagHiding: {
1943 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001944
John McCall6538c932009-10-10 05:48:19 +00001945 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1946
Aaron Ballman1e606f42014-07-15 22:03:49 +00001947 for (auto *D : Result)
1948 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
John McCall6538c932009-10-10 05:48:19 +00001949 TagDecls.insert(TD);
1950 Diag(TD->getLocation(), diag::note_hidden_tag);
1951 }
1952
Aaron Ballman1e606f42014-07-15 22:03:49 +00001953 for (auto *D : Result)
1954 if (!isa<TagDecl>(D))
1955 Diag(D->getLocation(), diag::note_hiding_object);
John McCall6538c932009-10-10 05:48:19 +00001956
1957 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001958 LookupResult::Filter F = Result.makeFilter();
1959 while (F.hasNext()) {
1960 if (TagDecls.count(F.next()))
1961 F.erase();
1962 }
1963 F.done();
Serge Pavlov99292092013-08-29 07:23:24 +00001964 break;
John McCall6538c932009-10-10 05:48:19 +00001965 }
1966
1967 case LookupResult::AmbiguousReference: {
1968 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001969
Aaron Ballman1e606f42014-07-15 22:03:49 +00001970 for (auto *D : Result)
1971 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
Serge Pavlov99292092013-08-29 07:23:24 +00001972 break;
John McCall6538c932009-10-10 05:48:19 +00001973 }
Serge Pavlov99292092013-08-29 07:23:24 +00001974 }
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001975}
Douglas Gregore254f902009-02-04 00:32:51 +00001976
John McCallf24d7bb2010-05-28 18:45:08 +00001977namespace {
1978 struct AssociatedLookup {
John McCall7d8b0412012-08-24 20:38:34 +00001979 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallf24d7bb2010-05-28 18:45:08 +00001980 Sema::AssociatedNamespaceSet &Namespaces,
1981 Sema::AssociatedClassSet &Classes)
John McCall7d8b0412012-08-24 20:38:34 +00001982 : S(S), Namespaces(Namespaces), Classes(Classes),
1983 InstantiationLoc(InstantiationLoc) {
John McCallf24d7bb2010-05-28 18:45:08 +00001984 }
1985
1986 Sema &S;
1987 Sema::AssociatedNamespaceSet &Namespaces;
1988 Sema::AssociatedClassSet &Classes;
John McCall7d8b0412012-08-24 20:38:34 +00001989 SourceLocation InstantiationLoc;
John McCallf24d7bb2010-05-28 18:45:08 +00001990 };
1991}
1992
Mike Stump11289f42009-09-09 15:08:12 +00001993static void
John McCallf24d7bb2010-05-28 18:45:08 +00001994addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001995
Douglas Gregor8b895222010-04-30 07:08:38 +00001996static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1997 DeclContext *Ctx) {
1998 // Add the associated namespace for this class.
1999
2000 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
2001 // be a locally scoped record.
2002
Sebastian Redlbd595762010-08-31 20:53:31 +00002003 // We skip out of inline namespaces. The innermost non-inline namespace
2004 // contains all names of all its nested inline namespaces anyway, so we can
2005 // replace the entire inline namespace tree with its root.
2006 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
2007 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00002008 Ctx = Ctx->getParent();
2009
John McCallc7e8e792009-08-07 22:18:02 +00002010 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00002011 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00002012}
Douglas Gregor197e5f72009-07-08 07:51:57 +00002013
Mike Stump11289f42009-09-09 15:08:12 +00002014// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00002015// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00002016static void
John McCallf24d7bb2010-05-28 18:45:08 +00002017addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2018 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002019 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00002020 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00002021 switch (Arg.getKind()) {
2022 case TemplateArgument::Null:
2023 break;
Mike Stump11289f42009-09-09 15:08:12 +00002024
Douglas Gregor197e5f72009-07-08 07:51:57 +00002025 case TemplateArgument::Type:
2026 // [...] the namespaces and classes associated with the types of the
2027 // template arguments provided for template type parameters (excluding
2028 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00002029 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00002030 break;
Mike Stump11289f42009-09-09 15:08:12 +00002031
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002032 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002033 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00002034 // [...] the namespaces in which any template template arguments are
2035 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00002036 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002037 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00002038 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002039 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002040 DeclContext *Ctx = ClassTemplate->getDeclContext();
2041 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002042 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002043 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002044 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002045 }
2046 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002047 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002048
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002049 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00002050 case TemplateArgument::Integral:
2051 case TemplateArgument::Expression:
Eli Friedmanb826a002012-09-26 02:36:12 +00002052 case TemplateArgument::NullPtr:
Mike Stump11289f42009-09-09 15:08:12 +00002053 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00002054 // associated namespaces. ]
2055 break;
Mike Stump11289f42009-09-09 15:08:12 +00002056
Douglas Gregor197e5f72009-07-08 07:51:57 +00002057 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00002058 for (const auto &P : Arg.pack_elements())
2059 addAssociatedClassesAndNamespaces(Result, P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002060 break;
2061 }
2062}
2063
Douglas Gregore254f902009-02-04 00:32:51 +00002064// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00002065// argument-dependent lookup with an argument of class type
2066// (C++ [basic.lookup.koenig]p2).
2067static void
John McCallf24d7bb2010-05-28 18:45:08 +00002068addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2069 CXXRecordDecl *Class) {
2070
2071 // Just silently ignore anything whose name is __va_list_tag.
2072 if (Class->getDeclName() == Result.S.VAListTagName)
2073 return;
2074
Douglas Gregore254f902009-02-04 00:32:51 +00002075 // C++ [basic.lookup.koenig]p2:
2076 // [...]
2077 // -- If T is a class type (including unions), its associated
2078 // classes are: the class itself; the class of which it is a
2079 // member, if any; and its direct and indirect base
2080 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00002081 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00002082
2083 // Add the class of which it is a member, if any.
2084 DeclContext *Ctx = Class->getDeclContext();
2085 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002086 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002087 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002088 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002089
Douglas Gregore254f902009-02-04 00:32:51 +00002090 // Add the class itself. If we've already seen this class, we don't
2091 // need to visit base classes.
Richard Smith594461f2014-03-14 22:07:27 +00002092 //
2093 // FIXME: That's not correct, we may have added this class only because it
2094 // was the enclosing class of another class, and in that case we won't have
2095 // added its base classes yet.
David Blaikie82e95a32014-11-19 07:49:47 +00002096 if (!Result.Classes.insert(Class).second)
Douglas Gregore254f902009-02-04 00:32:51 +00002097 return;
2098
Mike Stump11289f42009-09-09 15:08:12 +00002099 // -- If T is a template-id, its associated namespaces and classes are
2100 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002101 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00002102 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00002103 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00002104 // namespaces in which any template template arguments are defined; and
2105 // the classes in which any member templates used as template template
2106 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00002107 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00002108 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00002109 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2110 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2111 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002112 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002113 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002114 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002115
Douglas Gregor197e5f72009-07-08 07:51:57 +00002116 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2117 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00002118 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002119 }
Mike Stump11289f42009-09-09 15:08:12 +00002120
John McCall67da35c2010-02-04 22:26:26 +00002121 // Only recurse into base classes for complete types.
Richard Smith594461f2014-03-14 22:07:27 +00002122 if (!Class->hasDefinition())
2123 return;
John McCall67da35c2010-02-04 22:26:26 +00002124
Douglas Gregore254f902009-02-04 00:32:51 +00002125 // Add direct and indirect base classes along with their associated
2126 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002127 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00002128 Bases.push_back(Class);
2129 while (!Bases.empty()) {
2130 // Pop this class off the stack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002131 Class = Bases.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002132
2133 // Visit the base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +00002134 for (const auto &Base : Class->bases()) {
2135 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00002136 // In dependent contexts, we do ADL twice, and the first time around,
2137 // the base type might be a dependent TemplateSpecializationType, or a
2138 // TemplateTypeParmType. If that happens, simply ignore it.
2139 // FIXME: If we want to support export, we probably need to add the
2140 // namespace of the template in a TemplateSpecializationType, or even
2141 // the classes and namespaces of known non-dependent arguments.
2142 if (!BaseType)
2143 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002144 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
David Blaikie82e95a32014-11-19 07:49:47 +00002145 if (Result.Classes.insert(BaseDecl).second) {
Douglas Gregore254f902009-02-04 00:32:51 +00002146 // Find the associated namespace for this base class.
2147 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00002148 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00002149
2150 // Make sure we visit the bases of this base class.
2151 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2152 Bases.push_back(BaseDecl);
2153 }
2154 }
2155 }
2156}
2157
2158// \brief Add the associated classes and namespaces for
2159// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00002160// (C++ [basic.lookup.koenig]p2).
2161static void
John McCallf24d7bb2010-05-28 18:45:08 +00002162addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00002163 // C++ [basic.lookup.koenig]p2:
2164 //
2165 // For each argument type T in the function call, there is a set
2166 // of zero or more associated namespaces and a set of zero or more
2167 // associated classes to be considered. The sets of namespaces and
2168 // classes is determined entirely by the types of the function
2169 // arguments (and the namespace of any template template
2170 // argument). Typedef names and using-declarations used to specify
2171 // the types do not contribute to this set. The sets of namespaces
2172 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00002173
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002174 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00002175 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2176
Douglas Gregore254f902009-02-04 00:32:51 +00002177 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00002178 switch (T->getTypeClass()) {
2179
2180#define TYPE(Class, Base)
2181#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2182#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2183#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2184#define ABSTRACT_TYPE(Class, Base)
2185#include "clang/AST/TypeNodes.def"
2186 // T is canonical. We can also ignore dependent types because
2187 // we don't need to do ADL at the definition point, but if we
2188 // wanted to implement template export (or if we find some other
2189 // use for associated classes and namespaces...) this would be
2190 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00002191 break;
Douglas Gregore254f902009-02-04 00:32:51 +00002192
John McCall0af3d3b2010-05-28 06:08:54 +00002193 // -- If T is a pointer to U or an array of U, its associated
2194 // namespaces and classes are those associated with U.
2195 case Type::Pointer:
2196 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2197 continue;
2198 case Type::ConstantArray:
2199 case Type::IncompleteArray:
2200 case Type::VariableArray:
2201 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2202 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002203
John McCall0af3d3b2010-05-28 06:08:54 +00002204 // -- If T is a fundamental type, its associated sets of
2205 // namespaces and classes are both empty.
2206 case Type::Builtin:
2207 break;
2208
2209 // -- If T is a class type (including unions), its associated
2210 // classes are: the class itself; the class of which it is a
2211 // member, if any; and its direct and indirect base
2212 // classes. Its associated namespaces are the namespaces in
2213 // which its associated classes are defined.
2214 case Type::Record: {
Richard Smith594461f2014-03-14 22:07:27 +00002215 Result.S.RequireCompleteType(Result.InstantiationLoc, QualType(T, 0),
2216 /*no diagnostic*/ 0);
John McCall0af3d3b2010-05-28 06:08:54 +00002217 CXXRecordDecl *Class
2218 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002219 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00002220 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00002221 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00002222
John McCall0af3d3b2010-05-28 06:08:54 +00002223 // -- If T is an enumeration type, its associated namespace is
2224 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002225 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00002226 // it has no associated class.
2227 case Type::Enum: {
2228 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002229
John McCall0af3d3b2010-05-28 06:08:54 +00002230 DeclContext *Ctx = Enum->getDeclContext();
2231 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002232 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002233
John McCall0af3d3b2010-05-28 06:08:54 +00002234 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002235 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00002236
John McCall0af3d3b2010-05-28 06:08:54 +00002237 break;
2238 }
2239
2240 // -- If T is a function type, its associated namespaces and
2241 // classes are those associated with the function parameter
2242 // types and those associated with the return type.
2243 case Type::FunctionProto: {
2244 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002245 for (const auto &Arg : Proto->param_types())
2246 Queue.push_back(Arg.getTypePtr());
John McCall0af3d3b2010-05-28 06:08:54 +00002247 // fallthrough
2248 }
2249 case Type::FunctionNoProto: {
2250 const FunctionType *FnType = cast<FunctionType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00002251 T = FnType->getReturnType().getTypePtr();
John McCall0af3d3b2010-05-28 06:08:54 +00002252 continue;
2253 }
2254
2255 // -- If T is a pointer to a member function of a class X, its
2256 // associated namespaces and classes are those associated
2257 // with the function parameter types and return type,
2258 // together with those associated with X.
2259 //
2260 // -- If T is a pointer to a data member of class X, its
2261 // associated namespaces and classes are those associated
2262 // with the member type together with those associated with
2263 // X.
2264 case Type::MemberPointer: {
2265 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2266
2267 // Queue up the class type into which this points.
2268 Queue.push_back(MemberPtr->getClass());
2269
2270 // And directly continue with the pointee type.
2271 T = MemberPtr->getPointeeType().getTypePtr();
2272 continue;
2273 }
2274
2275 // As an extension, treat this like a normal pointer.
2276 case Type::BlockPointer:
2277 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2278 continue;
2279
2280 // References aren't covered by the standard, but that's such an
2281 // obvious defect that we cover them anyway.
2282 case Type::LValueReference:
2283 case Type::RValueReference:
2284 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2285 continue;
2286
2287 // These are fundamental types.
2288 case Type::Vector:
2289 case Type::ExtVector:
2290 case Type::Complex:
2291 break;
2292
Richard Smith27d807c2013-04-30 13:56:41 +00002293 // Non-deduced auto types only get here for error cases.
2294 case Type::Auto:
2295 break;
2296
Douglas Gregor8e936662011-04-12 01:02:45 +00002297 // If T is an Objective-C object or interface type, or a pointer to an
2298 // object or interface type, the associated namespace is the global
2299 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002300 case Type::ObjCObject:
2301 case Type::ObjCInterface:
2302 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002303 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002304 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002305
2306 // Atomic types are just wrappers; use the associations of the
2307 // contained type.
2308 case Type::Atomic:
2309 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2310 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002311 }
2312
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002313 if (Queue.empty())
2314 break;
2315 T = Queue.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002316 }
Douglas Gregore254f902009-02-04 00:32:51 +00002317}
2318
2319/// \brief Find the associated classes and namespaces for
2320/// argument-dependent lookup for a call with the given set of
2321/// arguments.
2322///
2323/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002324/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002325/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00002326void Sema::FindAssociatedClassesAndNamespaces(
2327 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2328 AssociatedNamespaceSet &AssociatedNamespaces,
2329 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002330 AssociatedNamespaces.clear();
2331 AssociatedClasses.clear();
2332
John McCall7d8b0412012-08-24 20:38:34 +00002333 AssociatedLookup Result(*this, InstantiationLoc,
2334 AssociatedNamespaces, AssociatedClasses);
John McCallf24d7bb2010-05-28 18:45:08 +00002335
Douglas Gregore254f902009-02-04 00:32:51 +00002336 // C++ [basic.lookup.koenig]p2:
2337 // For each argument type T in the function call, there is a set
2338 // of zero or more associated namespaces and a set of zero or more
2339 // associated classes to be considered. The sets of namespaces and
2340 // classes is determined entirely by the types of the function
2341 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002342 // argument).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002343 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregore254f902009-02-04 00:32:51 +00002344 Expr *Arg = Args[ArgIdx];
2345
2346 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002347 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002348 continue;
2349 }
2350
2351 // [...] In addition, if the argument is the name or address of a
2352 // set of overloaded functions and/or function templates, its
2353 // associated classes and namespaces are the union of those
2354 // associated with each of the members of the set: the namespace
2355 // in which the function or function template is defined and the
2356 // classes and namespaces associated with its (non-dependent)
2357 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002358 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002359 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002360 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002361 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002362
John McCallf24d7bb2010-05-28 18:45:08 +00002363 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2364 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002365
Aaron Ballman1e606f42014-07-15 22:03:49 +00002366 for (const auto *D : ULE->decls()) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002367 // Look through any using declarations to find the underlying function.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002368 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
Douglas Gregore254f902009-02-04 00:32:51 +00002369
2370 // Add the classes and namespaces associated with the parameter
2371 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002372 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002373 }
2374 }
2375}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002376
John McCall5cebab12009-11-18 07:57:50 +00002377NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002378 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002379 LookupNameKind NameKind,
2380 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002381 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002382 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002383 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002384}
2385
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002386/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002387ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002388 SourceLocation IdLoc,
2389 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002390 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002391 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002392 return cast_or_null<ObjCProtocolDecl>(D);
2393}
2394
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002395void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002396 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002397 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002398 // C++ [over.match.oper]p3:
2399 // -- The set of non-member candidates is the result of the
2400 // unqualified lookup of operator@ in the context of the
2401 // expression according to the usual rules for name lookup in
2402 // unqualified function calls (3.4.2) except that all member
Richard Smith100b24a2014-04-17 01:52:14 +00002403 // functions are ignored.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002404 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002405 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2406 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002407
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002408 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
Richard Smith100b24a2014-04-17 01:52:14 +00002409 Functions.append(Operators.begin(), Operators.end());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002410}
2411
Alexis Hunt1da39282011-06-24 02:11:39 +00002412Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002413 CXXSpecialMember SM,
2414 bool ConstArg,
2415 bool VolatileArg,
2416 bool RValueThis,
2417 bool ConstThis,
2418 bool VolatileThis) {
Richard Smith7d125a12012-11-27 21:20:31 +00002419 assert(CanDeclareSpecialMemberFunction(RD) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002420 "doing special member lookup into record that isn't fully complete");
Richard Smith7d125a12012-11-27 21:20:31 +00002421 RD = RD->getDefinition();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002422 if (RValueThis || ConstThis || VolatileThis)
2423 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2424 "constructors and destructors always have unqualified lvalue this");
2425 if (ConstArg || VolatileArg)
2426 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2427 "parameter-less special members can't have qualified arguments");
2428
2429 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002430 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002431 ID.AddInteger(SM);
2432 ID.AddInteger(ConstArg);
2433 ID.AddInteger(VolatileArg);
2434 ID.AddInteger(RValueThis);
2435 ID.AddInteger(ConstThis);
2436 ID.AddInteger(VolatileThis);
2437
2438 void *InsertPoint;
2439 SpecialMemberOverloadResult *Result =
2440 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2441
2442 // This was already cached
2443 if (Result)
2444 return Result;
2445
Alexis Huntba8e18d2011-06-07 00:11:58 +00002446 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2447 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002448 SpecialMemberCache.InsertNode(Result, InsertPoint);
2449
2450 if (SM == CXXDestructor) {
Richard Smith2be35f52012-12-01 02:35:44 +00002451 if (RD->needsImplicitDestructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002452 DeclareImplicitDestructor(RD);
2453 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002454 assert(DD && "record without a destructor");
2455 Result->setMethod(DD);
Richard Smith852265f2012-03-30 20:53:28 +00002456 Result->setKind(DD->isDeleted() ?
2457 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith83c478d2012-04-20 18:46:14 +00002458 SpecialMemberOverloadResult::Success);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002459 return Result;
2460 }
2461
Alexis Hunteef8ee02011-06-10 03:50:41 +00002462 // Prepare for overload resolution. Here we construct a synthetic argument
2463 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002464 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002465 DeclarationName Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002466 Expr *Arg = nullptr;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002467 unsigned NumArgs;
2468
Richard Smith83c478d2012-04-20 18:46:14 +00002469 QualType ArgType = CanTy;
2470 ExprValueKind VK = VK_LValue;
2471
Alexis Hunteef8ee02011-06-10 03:50:41 +00002472 if (SM == CXXDefaultConstructor) {
2473 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2474 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002475 if (RD->needsImplicitDefaultConstructor())
2476 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002477 } else {
2478 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2479 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smith2be35f52012-12-01 02:35:44 +00002480 if (RD->needsImplicitCopyConstructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002481 DeclareImplicitCopyConstructor(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002482 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002483 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002484 } else {
2485 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smith2be35f52012-12-01 02:35:44 +00002486 if (RD->needsImplicitCopyAssignment())
Alexis Hunt1da39282011-06-24 02:11:39 +00002487 DeclareImplicitCopyAssignment(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002488 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002489 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002490 }
2491
Alexis Hunteef8ee02011-06-10 03:50:41 +00002492 if (ConstArg)
2493 ArgType.addConst();
2494 if (VolatileArg)
2495 ArgType.addVolatile();
2496
2497 // This isn't /really/ specified by the standard, but it's implied
2498 // we should be working from an RValue in the case of move to ensure
2499 // that we prefer to bind to rvalue references, and an LValue in the
2500 // case of copy to ensure we don't bind to rvalue references.
2501 // Possibly an XValue is actually correct in the case of move, but
2502 // there is no semantic difference for class types in this restricted
2503 // case.
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002504 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002505 VK = VK_LValue;
2506 else
2507 VK = VK_RValue;
Richard Smith83c478d2012-04-20 18:46:14 +00002508 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00002509
Richard Smith83c478d2012-04-20 18:46:14 +00002510 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2511
2512 if (SM != CXXDefaultConstructor) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002513 NumArgs = 1;
Richard Smith83c478d2012-04-20 18:46:14 +00002514 Arg = &FakeArg;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002515 }
2516
2517 // Create the object argument
2518 QualType ThisTy = CanTy;
2519 if (ConstThis)
2520 ThisTy.addConst();
2521 if (VolatileThis)
2522 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002523 Expr::Classification Classification =
Richard Smith83c478d2012-04-20 18:46:14 +00002524 OpaqueValueExpr(SourceLocation(), ThisTy,
2525 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002526
2527 // Now we perform lookup on the name we computed earlier and do overload
2528 // resolution. Lookup is only performed directly into the class since there
2529 // will always be a (possibly implicit) declaration to shadow any others.
Richard Smith100b24a2014-04-17 01:52:14 +00002530 OverloadCandidateSet OCS(RD->getLocation(), OverloadCandidateSet::CSK_Normal);
David Blaikieff7d47a2012-12-19 00:45:41 +00002531 DeclContext::lookup_result R = RD->lookup(Name);
Richard Smith8c37ab52015-02-11 01:48:47 +00002532
2533 if (R.empty()) {
2534 // We might have no default constructor because we have a lambda's closure
2535 // type, rather than because there's some other declared constructor.
2536 // Every class has a copy/move constructor, copy/move assignment, and
2537 // destructor.
2538 assert(SM == CXXDefaultConstructor &&
2539 "lookup for a constructor or assignment operator was empty");
2540 Result->setMethod(nullptr);
2541 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
2542 return Result;
2543 }
Chandler Carruth7deaae72013-08-18 07:20:52 +00002544
2545 // Copy the candidates as our processing of them may load new declarations
2546 // from an external source and invalidate lookup_result.
2547 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2548
Aaron Ballman1e606f42014-07-15 22:03:49 +00002549 for (auto *Cand : Candidates) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002550 if (Cand->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002551 continue;
2552
Alexis Hunt1da39282011-06-24 02:11:39 +00002553 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2554 // FIXME: [namespace.udecl]p15 says that we should only consider a
2555 // using declaration here if it does not match a declaration in the
2556 // derived class. We do not implement this correctly in other cases
2557 // either.
2558 Cand = U->getTargetDecl();
2559
2560 if (Cand->isInvalidDecl())
2561 continue;
2562 }
2563
2564 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002565 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Alexis Hunt1da39282011-06-24 02:11:39 +00002566 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002567 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2568 OCS, true);
Alexis Hunt080709f2011-06-23 00:26:20 +00002569 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002570 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2571 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt2949f022011-06-22 02:58:46 +00002572 } else if (FunctionTemplateDecl *Tmpl =
Alexis Hunt1da39282011-06-24 02:11:39 +00002573 dyn_cast<FunctionTemplateDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002574 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2575 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Craig Topperc3ec1492014-05-26 06:22:03 +00002576 RD, nullptr, ThisTy, Classification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002577 llvm::makeArrayRef(&Arg, NumArgs),
Alexis Hunt080709f2011-06-23 00:26:20 +00002578 OCS, true);
2579 else
2580 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Craig Topperc3ec1492014-05-26 06:22:03 +00002581 nullptr, llvm::makeArrayRef(&Arg, NumArgs),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002582 OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002583 } else {
2584 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002585 }
2586 }
2587
2588 OverloadCandidateSet::iterator Best;
2589 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2590 case OR_Success:
2591 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith83c478d2012-04-20 18:46:14 +00002592 Result->setKind(SpecialMemberOverloadResult::Success);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002593 break;
2594
2595 case OR_Deleted:
2596 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith852265f2012-03-30 20:53:28 +00002597 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002598 break;
2599
2600 case OR_Ambiguous:
Craig Topperc3ec1492014-05-26 06:22:03 +00002601 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00002602 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2603 break;
2604
Alexis Hunteef8ee02011-06-10 03:50:41 +00002605 case OR_No_Viable_Function:
Craig Topperc3ec1492014-05-26 06:22:03 +00002606 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00002607 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002608 break;
2609 }
2610
2611 return Result;
2612}
2613
2614/// \brief Look up the default constructor for the given class.
2615CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002616 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002617 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2618 false, false);
2619
2620 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002621}
2622
Alexis Hunt491ec602011-06-21 23:42:56 +00002623/// \brief Look up the copying constructor for the given class.
2624CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith83c478d2012-04-20 18:46:14 +00002625 unsigned Quals) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002626 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2627 "non-const, non-volatile qualifiers for copy ctor arg");
2628 SpecialMemberOverloadResult *Result =
2629 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2630 Quals & Qualifiers::Volatile, false, false, false);
2631
Alexis Hunt899bd442011-06-10 04:44:37 +00002632 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2633}
2634
Sebastian Redl22653ba2011-08-30 19:58:05 +00002635/// \brief Look up the moving constructor for the given class.
Richard Smith1c6461e2012-07-18 03:36:00 +00002636CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2637 unsigned Quals) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002638 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002639 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2640 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002641
2642 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2643}
2644
Douglas Gregor52b72822010-07-02 23:12:18 +00002645/// \brief Look up the constructors for the given class.
2646DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002647 // If the implicit constructors have not yet been declared, do so now.
Richard Smith7d125a12012-11-27 21:20:31 +00002648 if (CanDeclareSpecialMemberFunction(Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00002649 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002650 DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +00002651 if (Class->needsImplicitCopyConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002652 DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002653 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002654 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00002655 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002656
Douglas Gregor52b72822010-07-02 23:12:18 +00002657 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2658 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2659 return Class->lookup(Name);
2660}
2661
Alexis Hunt491ec602011-06-21 23:42:56 +00002662/// \brief Look up the copying assignment operator for the given class.
2663CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2664 unsigned Quals, bool RValueThis,
Richard Smith83c478d2012-04-20 18:46:14 +00002665 unsigned ThisQuals) {
Alexis Hunt491ec602011-06-21 23:42:56 +00002666 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2667 "non-const, non-volatile qualifiers for copy assignment arg");
2668 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2669 "non-const, non-volatile qualifiers for copy assignment this");
2670 SpecialMemberOverloadResult *Result =
2671 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2672 Quals & Qualifiers::Volatile, RValueThis,
2673 ThisQuals & Qualifiers::Const,
2674 ThisQuals & Qualifiers::Volatile);
2675
Alexis Hunt491ec602011-06-21 23:42:56 +00002676 return Result->getMethod();
2677}
2678
Sebastian Redl22653ba2011-08-30 19:58:05 +00002679/// \brief Look up the moving assignment operator for the given class.
2680CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith1c6461e2012-07-18 03:36:00 +00002681 unsigned Quals,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002682 bool RValueThis,
2683 unsigned ThisQuals) {
2684 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2685 "non-const, non-volatile qualifiers for copy assignment this");
2686 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002687 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2688 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002689 ThisQuals & Qualifiers::Const,
2690 ThisQuals & Qualifiers::Volatile);
2691
2692 return Result->getMethod();
2693}
2694
Douglas Gregore71edda2010-07-01 22:47:18 +00002695/// \brief Look for the destructor of the given class.
2696///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00002697/// During semantic analysis, this routine should be used in lieu of
2698/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00002699///
2700/// \returns The destructor for this class.
2701CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002702 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2703 false, false, false,
2704 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00002705}
2706
Richard Smithbcc22fc2012-03-09 08:00:36 +00002707/// LookupLiteralOperator - Determine which literal operator should be used for
2708/// a user-defined literal, per C++11 [lex.ext].
2709///
2710/// Normal overload resolution is not used to select which literal operator to
2711/// call for a user-defined literal. Look up the provided literal operator name,
2712/// and filter the results to the appropriate set for the given argument types.
2713Sema::LiteralOperatorLookupResult
2714Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2715 ArrayRef<QualType> ArgTys,
Richard Smithb8b41d32013-10-07 19:57:58 +00002716 bool AllowRaw, bool AllowTemplate,
2717 bool AllowStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002718 LookupName(R, S);
2719 assert(R.getResultKind() != LookupResult::Ambiguous &&
2720 "literal operator lookup can't be ambiguous");
2721
2722 // Filter the lookup results appropriately.
2723 LookupResult::Filter F = R.makeFilter();
2724
Richard Smithbcc22fc2012-03-09 08:00:36 +00002725 bool FoundRaw = false;
Richard Smithb8b41d32013-10-07 19:57:58 +00002726 bool FoundTemplate = false;
2727 bool FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002728 bool FoundExactMatch = false;
2729
2730 while (F.hasNext()) {
2731 Decl *D = F.next();
2732 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2733 D = USD->getTargetDecl();
2734
Douglas Gregorc1970572013-04-10 05:18:00 +00002735 // If the declaration we found is invalid, skip it.
2736 if (D->isInvalidDecl()) {
2737 F.erase();
2738 continue;
2739 }
2740
Richard Smithb8b41d32013-10-07 19:57:58 +00002741 bool IsRaw = false;
2742 bool IsTemplate = false;
2743 bool IsStringTemplate = false;
2744 bool IsExactMatch = false;
2745
Richard Smithbcc22fc2012-03-09 08:00:36 +00002746 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2747 if (FD->getNumParams() == 1 &&
2748 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2749 IsRaw = true;
Richard Smith550de452013-01-15 07:12:59 +00002750 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002751 IsExactMatch = true;
2752 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2753 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2754 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2755 IsExactMatch = false;
2756 break;
2757 }
2758 }
2759 }
2760 }
Richard Smithb8b41d32013-10-07 19:57:58 +00002761 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
2762 TemplateParameterList *Params = FD->getTemplateParameters();
2763 if (Params->size() == 1)
2764 IsTemplate = true;
2765 else
2766 IsStringTemplate = true;
2767 }
Richard Smithbcc22fc2012-03-09 08:00:36 +00002768
2769 if (IsExactMatch) {
2770 FoundExactMatch = true;
Richard Smithb8b41d32013-10-07 19:57:58 +00002771 AllowRaw = false;
2772 AllowTemplate = false;
2773 AllowStringTemplate = false;
2774 if (FoundRaw || FoundTemplate || FoundStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002775 // Go through again and remove the raw and template decls we've
2776 // already found.
2777 F.restart();
Richard Smithb8b41d32013-10-07 19:57:58 +00002778 FoundRaw = FoundTemplate = FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002779 }
Richard Smithb8b41d32013-10-07 19:57:58 +00002780 } else if (AllowRaw && IsRaw) {
2781 FoundRaw = true;
2782 } else if (AllowTemplate && IsTemplate) {
2783 FoundTemplate = true;
2784 } else if (AllowStringTemplate && IsStringTemplate) {
2785 FoundStringTemplate = true;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002786 } else {
2787 F.erase();
2788 }
2789 }
2790
2791 F.done();
2792
2793 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2794 // parameter type, that is used in preference to a raw literal operator
2795 // or literal operator template.
2796 if (FoundExactMatch)
2797 return LOLR_Cooked;
2798
2799 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2800 // operator template, but not both.
2801 if (FoundRaw && FoundTemplate) {
2802 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
Alp Tokera2794f92014-01-22 07:29:52 +00002803 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2804 NoteOverloadCandidate((*I)->getUnderlyingDecl()->getAsFunction());
Richard Smithbcc22fc2012-03-09 08:00:36 +00002805 return LOLR_Error;
2806 }
2807
2808 if (FoundRaw)
2809 return LOLR_Raw;
2810
2811 if (FoundTemplate)
2812 return LOLR_Template;
2813
Richard Smithb8b41d32013-10-07 19:57:58 +00002814 if (FoundStringTemplate)
2815 return LOLR_StringTemplate;
2816
Richard Smithbcc22fc2012-03-09 08:00:36 +00002817 // Didn't find anything we could use.
2818 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2819 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
Richard Smithb8b41d32013-10-07 19:57:58 +00002820 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
2821 << (AllowTemplate || AllowStringTemplate);
Richard Smithbcc22fc2012-03-09 08:00:36 +00002822 return LOLR_Error;
2823}
2824
John McCall8fe68082010-01-26 07:16:45 +00002825void ADLResult::insert(NamedDecl *New) {
2826 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2827
2828 // If we haven't yet seen a decl for this key, or the last decl
2829 // was exactly this one, we're done.
Craig Topperc3ec1492014-05-26 06:22:03 +00002830 if (Old == nullptr || Old == New) {
John McCall8fe68082010-01-26 07:16:45 +00002831 Old = New;
2832 return;
2833 }
2834
2835 // Otherwise, decide which is a more recent redeclaration.
Alp Tokera2794f92014-01-22 07:29:52 +00002836 FunctionDecl *OldFD = Old->getAsFunction();
2837 FunctionDecl *NewFD = New->getAsFunction();
John McCall8fe68082010-01-26 07:16:45 +00002838
2839 FunctionDecl *Cursor = NewFD;
2840 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002841 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00002842
2843 // If we got to the end without finding OldFD, OldFD is the newer
2844 // declaration; leave things as they are.
2845 if (!Cursor) return;
2846
2847 // If we do find OldFD, then NewFD is newer.
2848 if (Cursor == OldFD) break;
2849
2850 // Otherwise, keep looking.
2851 }
2852
2853 Old = New;
2854}
2855
Richard Smith100b24a2014-04-17 01:52:14 +00002856void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
2857 ArrayRef<Expr *> Args, ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002858 // Find all of the associated namespaces and classes based on the
2859 // arguments we have.
2860 AssociatedNamespaceSet AssociatedNamespaces;
2861 AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00002862 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCallc7e8e792009-08-07 22:18:02 +00002863 AssociatedNamespaces,
2864 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002865
2866 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002867 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2868 // and let Y be the lookup set produced by argument dependent
2869 // lookup (defined as follows). If X contains [...] then Y is
2870 // empty. Otherwise Y is the set of declarations found in the
2871 // namespaces associated with the argument types as described
2872 // below. The set of declarations found by the lookup of the name
2873 // is the union of X and Y.
2874 //
2875 // Here, we compute Y and add its members to the overloaded
2876 // candidate set.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002877 for (auto *NS : AssociatedNamespaces) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002878 // When considering an associated namespace, the lookup is the
2879 // same as the lookup performed when the associated namespace is
2880 // used as a qualifier (3.4.3.2) except that:
2881 //
2882 // -- Any using-directives in the associated namespace are
2883 // ignored.
2884 //
John McCallc7e8e792009-08-07 22:18:02 +00002885 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002886 // associated classes are visible within their respective
2887 // namespaces even if they are not visible during an ordinary
2888 // lookup (11.4).
Aaron Ballman1e606f42014-07-15 22:03:49 +00002889 DeclContext::lookup_result R = NS->lookup(Name);
2890 for (auto *D : R) {
John McCallaa74a0c2009-08-28 07:59:38 +00002891 // If the only declaration here is an ordinary friend, consider
2892 // it only if it was declared in an associated classes.
Richard Smith541b38b2013-09-20 01:15:31 +00002893 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) {
2894 // If it's neither ordinarily visible nor a friend, we can't find it.
2895 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0)
2896 continue;
2897
Richard Smith64017682013-07-17 23:53:16 +00002898 bool DeclaredInAssociatedClass = false;
2899 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
2900 DeclContext *LexDC = DI->getLexicalDeclContext();
2901 if (isa<CXXRecordDecl>(LexDC) &&
2902 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) {
2903 DeclaredInAssociatedClass = true;
2904 break;
2905 }
2906 }
2907 if (!DeclaredInAssociatedClass)
John McCalld1e9d832009-08-11 06:59:38 +00002908 continue;
2909 }
Mike Stump11289f42009-09-09 15:08:12 +00002910
John McCall91f61fc2010-01-26 06:04:06 +00002911 if (isa<UsingShadowDecl>(D))
2912 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002913
Richard Smith100b24a2014-04-17 01:52:14 +00002914 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D))
John McCall8fe68082010-01-26 07:16:45 +00002915 continue;
2916
2917 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002918 }
2919 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002920}
Douglas Gregor2d435302009-12-30 17:04:44 +00002921
2922//----------------------------------------------------------------------------
2923// Search for all visible declarations.
2924//----------------------------------------------------------------------------
2925VisibleDeclConsumer::~VisibleDeclConsumer() { }
2926
Richard Smithe156254d2013-08-20 20:35:18 +00002927bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
2928
Douglas Gregor2d435302009-12-30 17:04:44 +00002929namespace {
2930
2931class ShadowContextRAII;
2932
2933class VisibleDeclsRecord {
2934public:
2935 /// \brief An entry in the shadow map, which is optimized to store a
2936 /// single declaration (the common case) but can also store a list
2937 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002938 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00002939
2940private:
2941 /// \brief A mapping from declaration names to the declarations that have
2942 /// this name within a particular scope.
2943 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2944
2945 /// \brief A list of shadow maps, which is used to model name hiding.
2946 std::list<ShadowMap> ShadowMaps;
2947
2948 /// \brief The declaration contexts we have already visited.
2949 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2950
2951 friend class ShadowContextRAII;
2952
2953public:
2954 /// \brief Determine whether we have already visited this context
2955 /// (and, if not, note that we are going to visit that context now).
2956 bool visitedContext(DeclContext *Ctx) {
David Blaikie82e95a32014-11-19 07:49:47 +00002957 return !VisitedContexts.insert(Ctx).second;
Douglas Gregor2d435302009-12-30 17:04:44 +00002958 }
2959
Douglas Gregor39982192010-08-15 06:18:01 +00002960 bool alreadyVisitedContext(DeclContext *Ctx) {
2961 return VisitedContexts.count(Ctx);
2962 }
2963
Douglas Gregor2d435302009-12-30 17:04:44 +00002964 /// \brief Determine whether the given declaration is hidden in the
2965 /// current scope.
2966 ///
2967 /// \returns the declaration that hides the given declaration, or
2968 /// NULL if no such declaration exists.
2969 NamedDecl *checkHidden(NamedDecl *ND);
2970
2971 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002972 void add(NamedDecl *ND) {
2973 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2974 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002975};
2976
2977/// \brief RAII object that records when we've entered a shadow context.
2978class ShadowContextRAII {
2979 VisibleDeclsRecord &Visible;
2980
2981 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2982
2983public:
2984 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2985 Visible.ShadowMaps.push_back(ShadowMap());
2986 }
2987
2988 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00002989 Visible.ShadowMaps.pop_back();
2990 }
2991};
2992
2993} // end anonymous namespace
2994
Douglas Gregor2d435302009-12-30 17:04:44 +00002995NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002996 // Look through using declarations.
2997 ND = ND->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002998
Douglas Gregor2d435302009-12-30 17:04:44 +00002999 unsigned IDNS = ND->getIdentifierNamespace();
3000 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
3001 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3002 SM != SMEnd; ++SM) {
3003 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
3004 if (Pos == SM->end())
3005 continue;
3006
Aaron Ballman1e606f42014-07-15 22:03:49 +00003007 for (auto *D : Pos->second) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003008 // A tag declaration does not hide a non-tag declaration.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003009 if (D->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003010 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00003011 Decl::IDNS_ObjCProtocol)))
3012 continue;
3013
3014 // Protocols are in distinct namespaces from everything else.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003015 if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor2d435302009-12-30 17:04:44 +00003016 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Aaron Ballman1e606f42014-07-15 22:03:49 +00003017 D->getIdentifierNamespace() != IDNS)
Douglas Gregor2d435302009-12-30 17:04:44 +00003018 continue;
3019
Douglas Gregor09bbc652010-01-14 15:47:35 +00003020 // Functions and function templates in the same scope overload
3021 // rather than hide. FIXME: Look for hiding based on function
3022 // signatures!
Aaron Ballman1e606f42014-07-15 22:03:49 +00003023 if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Alp Tokera2794f92014-01-22 07:29:52 +00003024 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00003025 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00003026 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003027
Douglas Gregor2d435302009-12-30 17:04:44 +00003028 // We've found a declaration that hides this one.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003029 return D;
Douglas Gregor2d435302009-12-30 17:04:44 +00003030 }
3031 }
3032
Craig Topperc3ec1492014-05-26 06:22:03 +00003033 return nullptr;
Douglas Gregor2d435302009-12-30 17:04:44 +00003034}
3035
3036static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
3037 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003038 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00003039 VisibleDeclConsumer &Consumer,
3040 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00003041 if (!Ctx)
3042 return;
3043
Douglas Gregor2d435302009-12-30 17:04:44 +00003044 // Make sure we don't visit the same context twice.
3045 if (Visited.visitedContext(Ctx->getPrimaryContext()))
3046 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003047
Richard Smith9e2341d2015-03-23 03:25:59 +00003048 // Outside C++, lookup results for the TU live on identifiers.
3049 if (isa<TranslationUnitDecl>(Ctx) &&
3050 !Result.getSema().getLangOpts().CPlusPlus) {
3051 auto &S = Result.getSema();
3052 auto &Idents = S.Context.Idents;
3053
3054 // Ensure all external identifiers are in the identifier table.
3055 if (IdentifierInfoLookup *External = Idents.getExternalIdentifierLookup()) {
3056 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
3057 for (StringRef Name = Iter->Next(); !Name.empty(); Name = Iter->Next())
3058 Idents.get(Name);
3059 }
3060
3061 // Walk all lookup results in the TU for each identifier.
3062 for (const auto &Ident : Idents) {
3063 for (auto I = S.IdResolver.begin(Ident.getValue()),
3064 E = S.IdResolver.end();
3065 I != E; ++I) {
3066 if (S.IdResolver.isDeclInScope(*I, Ctx)) {
3067 if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
3068 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3069 Visited.add(ND);
3070 }
3071 }
3072 }
3073 }
3074
3075 return;
3076 }
3077
Douglas Gregor7454c562010-07-02 20:37:36 +00003078 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3079 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3080
Douglas Gregor2d435302009-12-30 17:04:44 +00003081 // Enumerate all of the results in this context.
Richard Trieu20abd6b2015-04-15 03:48:48 +00003082 for (DeclContextLookupResult R : Ctx->lookups()) {
Richard Smith9e2341d2015-03-23 03:25:59 +00003083 for (auto *D : R) {
3084 if (auto *ND = Result.getAcceptableDecl(D)) {
3085 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3086 Visited.add(ND);
Douglas Gregora3b23b02010-12-09 21:44:02 +00003087 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003088 }
3089 }
3090
3091 // Traverse using directives for qualified name lookup.
3092 if (QualifiedNameLookup) {
3093 ShadowContextRAII Shadow(Visited);
Aaron Ballman804a7fb2014-03-17 17:14:12 +00003094 for (auto I : Ctx->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00003095 LookupVisibleDecls(I->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003096 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003097 }
3098 }
3099
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003100 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00003101 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00003102 if (!Record->hasDefinition())
3103 return;
3104
Aaron Ballman574705e2014-03-13 15:41:46 +00003105 for (const auto &B : Record->bases()) {
3106 QualType BaseType = B.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003107
Douglas Gregor2d435302009-12-30 17:04:44 +00003108 // Don't look into dependent bases, because name lookup can't look
3109 // there anyway.
3110 if (BaseType->isDependentType())
3111 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003112
Douglas Gregor2d435302009-12-30 17:04:44 +00003113 const RecordType *Record = BaseType->getAs<RecordType>();
3114 if (!Record)
3115 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003116
Douglas Gregor2d435302009-12-30 17:04:44 +00003117 // FIXME: It would be nice to be able to determine whether referencing
3118 // a particular member would be ambiguous. For example, given
3119 //
3120 // struct A { int member; };
3121 // struct B { int member; };
3122 // struct C : A, B { };
3123 //
3124 // void f(C *c) { c->### }
3125 //
3126 // accessing 'member' would result in an ambiguity. However, we
3127 // could be smart enough to qualify the member with the base
3128 // class, e.g.,
3129 //
3130 // c->B::member
3131 //
3132 // or
3133 //
3134 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003135
Douglas Gregor2d435302009-12-30 17:04:44 +00003136 // Find results in this base class (and its bases).
3137 ShadowContextRAII Shadow(Visited);
3138 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003139 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003140 }
3141 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003142
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003143 // Traverse the contexts of Objective-C classes.
3144 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3145 // Traverse categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003146 for (auto *Cat : IFace->visible_categories()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003147 ShadowContextRAII Shadow(Visited);
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003148 LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003149 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003150 }
3151
3152 // Traverse protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003153 for (auto *I : IFace->all_referenced_protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003154 ShadowContextRAII Shadow(Visited);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003155 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003156 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003157 }
3158
3159 // Traverse the superclass.
3160 if (IFace->getSuperClass()) {
3161 ShadowContextRAII Shadow(Visited);
3162 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003163 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003164 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003165
Douglas Gregor0b59e802010-04-19 18:02:19 +00003166 // If there is an implementation, traverse it. We do this to find
3167 // synthesized ivars.
3168 if (IFace->getImplementation()) {
3169 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003170 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky13668f22012-04-03 20:26:45 +00003171 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor0b59e802010-04-19 18:02:19 +00003172 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003173 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003174 for (auto *I : Protocol->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003175 ShadowContextRAII Shadow(Visited);
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003176 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003177 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003178 }
3179 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003180 for (auto *I : Category->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003181 ShadowContextRAII Shadow(Visited);
Aaron Ballman19a41762014-03-14 12:55:57 +00003182 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003183 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003184 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003185
Douglas Gregor0b59e802010-04-19 18:02:19 +00003186 // If there is an implementation, traverse it.
3187 if (Category->getImplementation()) {
3188 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003189 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00003190 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003191 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003192 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003193}
3194
3195static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3196 UnqualUsingDirectiveSet &UDirs,
3197 VisibleDeclConsumer &Consumer,
3198 VisibleDeclsRecord &Visited) {
3199 if (!S)
3200 return;
3201
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003202 if (!S->getEntity() ||
3203 (!S->getParent() &&
Ted Kremenekc37877d2013-10-08 17:08:03 +00003204 !Visited.alreadyVisitedContext(S->getEntity())) ||
3205 (S->getEntity())->isFunctionOrMethod()) {
Richard Smith541b38b2013-09-20 01:15:31 +00003206 FindLocalExternScope FindLocals(Result);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003207 // Walk through the declarations in this Scope.
Aaron Ballman35c54952014-03-17 16:55:25 +00003208 for (auto *D : S->decls()) {
3209 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Douglas Gregor4a814562011-12-14 16:03:29 +00003210 if ((ND = Result.getAcceptableDecl(ND))) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003211 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003212 Visited.add(ND);
3213 }
3214 }
3215 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003216
Douglas Gregor66230062010-03-15 14:33:29 +00003217 // FIXME: C++ [temp.local]p8
Craig Topperc3ec1492014-05-26 06:22:03 +00003218 DeclContext *Entity = nullptr;
Douglas Gregor4f248632010-01-01 17:44:25 +00003219 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003220 // Look into this scope's declaration context, along with any of its
3221 // parent lookup contexts (e.g., enclosing classes), up to the point
3222 // where we hit the context stored in the next outer scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00003223 Entity = S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00003224 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003225
Douglas Gregorea166062010-03-15 15:26:48 +00003226 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00003227 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003228 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3229 if (Method->isInstanceMethod()) {
3230 // For instance methods, look for ivars in the method's interface.
3231 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3232 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003233 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003234 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Richard Smithe156254d2013-08-20 20:35:18 +00003235 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003236 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003237 }
3238
3239 // We've already performed all of the name lookup that we need
3240 // to for Objective-C methods; the next context will be the
3241 // outer scope.
3242 break;
3243 }
3244
Douglas Gregor2d435302009-12-30 17:04:44 +00003245 if (Ctx->isFunctionOrMethod())
3246 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003247
3248 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003249 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003250 }
3251 } else if (!S->getParent()) {
3252 // Look into the translation unit scope. We walk through the translation
3253 // unit's declaration context, because the Scope itself won't have all of
3254 // the declarations if we loaded a precompiled header.
3255 // FIXME: We would like the translation unit's Scope object to point to the
3256 // translation unit, so we don't need this special "if" branch. However,
3257 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003258 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00003259 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003260 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00003261 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003262 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003263 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003264 }
3265
Douglas Gregor2d435302009-12-30 17:04:44 +00003266 if (Entity) {
3267 // Lookup visible declarations in any namespaces found by using
3268 // directives.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003269 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
3270 LookupVisibleDecls(const_cast<DeclContext *>(UUE.getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003271 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003272 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003273 }
3274
3275 // Lookup names in the parent scope.
3276 ShadowContextRAII Shadow(Visited);
3277 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3278}
3279
3280void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003281 VisibleDeclConsumer &Consumer,
3282 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003283 // Determine the set of using directives available during
3284 // unqualified name lookup.
3285 Scope *Initial = S;
3286 UnqualUsingDirectiveSet UDirs;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003287 if (getLangOpts().CPlusPlus) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003288 // Find the first namespace or translation-unit scope.
3289 while (S && !isNamespaceOrTranslationUnitScope(S))
3290 S = S->getParent();
3291
3292 UDirs.visitScopeChain(Initial, S);
3293 }
3294 UDirs.done();
3295
3296 // Look for visible declarations.
3297 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003298 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003299 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003300 if (!IncludeGlobalScope)
3301 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003302 ShadowContextRAII Shadow(Visited);
3303 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3304}
3305
3306void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003307 VisibleDeclConsumer &Consumer,
3308 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003309 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003310 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003311 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003312 if (!IncludeGlobalScope)
3313 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003314 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003315 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003316 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003317}
3318
Chris Lattner43e7f312011-02-18 02:08:43 +00003319/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003320/// If GnuLabelLoc is a valid source location, then this is a definition
3321/// of an __label__ label name, otherwise it is a normal label definition
3322/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003323LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003324 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003325 // Do a lookup to see if we have a label with this name already.
Craig Topperc3ec1492014-05-26 06:22:03 +00003326 NamedDecl *Res = nullptr;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003327
3328 if (GnuLabelLoc.isValid()) {
3329 // Local label definitions always shadow existing labels.
3330 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3331 Scope *S = CurScope;
3332 PushOnScopeChains(Res, S, true);
3333 return cast<LabelDecl>(Res);
3334 }
3335
3336 // Not a GNU local label.
3337 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3338 // If we found a label, check to see if it is in the same context as us.
3339 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003340 if (Res && Res->getDeclContext() != CurContext)
Craig Topperc3ec1492014-05-26 06:22:03 +00003341 Res = nullptr;
3342 if (!Res) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003343 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003344 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3345 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003346 assert(S && "Not in a function?");
3347 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003348 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003349 return cast<LabelDecl>(Res);
3350}
3351
3352//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003353// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003354//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003355
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003356static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3357 TypoCorrection &Candidate) {
3358 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3359 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3360}
3361
3362static void LookupPotentialTypoResult(Sema &SemaRef,
3363 LookupResult &Res,
3364 IdentifierInfo *Name,
3365 Scope *S, CXXScopeSpec *SS,
3366 DeclContext *MemberContext,
3367 bool EnteringContext,
3368 bool isObjCIvarLookup,
3369 bool FindHidden);
3370
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003371/// \brief Check whether the declarations found for a typo correction are
3372/// visible, and if none of them are, convert the correction to an 'import
3373/// a module' correction.
3374static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
3375 if (TC.begin() == TC.end())
3376 return;
3377
3378 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3379
3380 for (/**/; DI != DE; ++DI)
3381 if (!LookupResult::isVisible(SemaRef, *DI))
3382 break;
3383 // Nothing to do if all decls are visible.
3384 if (DI == DE)
3385 return;
3386
3387 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3388 bool AnyVisibleDecls = !NewDecls.empty();
3389
3390 for (/**/; DI != DE; ++DI) {
3391 NamedDecl *VisibleDecl = *DI;
3392 if (!LookupResult::isVisible(SemaRef, *DI))
3393 VisibleDecl = findAcceptableDecl(SemaRef, *DI);
3394
3395 if (VisibleDecl) {
3396 if (!AnyVisibleDecls) {
3397 // Found a visible decl, discard all hidden ones.
3398 AnyVisibleDecls = true;
3399 NewDecls.clear();
3400 }
3401 NewDecls.push_back(VisibleDecl);
3402 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
3403 NewDecls.push_back(*DI);
3404 }
3405
3406 if (NewDecls.empty())
3407 TC = TypoCorrection();
3408 else {
3409 TC.setCorrectionDecls(NewDecls);
3410 TC.setRequiresImport(!AnyVisibleDecls);
3411 }
3412}
3413
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003414// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3415// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3416// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3417static void getNestedNameSpecifierIdentifiers(
3418 NestedNameSpecifier *NNS,
3419 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3420 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3421 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3422 else
3423 Identifiers.clear();
3424
3425 const IdentifierInfo *II = nullptr;
3426
3427 switch (NNS->getKind()) {
3428 case NestedNameSpecifier::Identifier:
3429 II = NNS->getAsIdentifier();
3430 break;
3431
3432 case NestedNameSpecifier::Namespace:
3433 if (NNS->getAsNamespace()->isAnonymousNamespace())
3434 return;
3435 II = NNS->getAsNamespace()->getIdentifier();
3436 break;
3437
3438 case NestedNameSpecifier::NamespaceAlias:
3439 II = NNS->getAsNamespaceAlias()->getIdentifier();
3440 break;
3441
3442 case NestedNameSpecifier::TypeSpecWithTemplate:
3443 case NestedNameSpecifier::TypeSpec:
3444 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3445 break;
3446
3447 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00003448 case NestedNameSpecifier::Super:
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003449 return;
3450 }
3451
3452 if (II)
3453 Identifiers.push_back(II);
3454}
3455
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003456void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003457 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003458 // Don't consider hidden names for typo correction.
3459 if (Hiding)
3460 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003461
Douglas Gregor2d435302009-12-30 17:04:44 +00003462 // Only consider entities with identifiers for names, ignoring
3463 // special names (constructors, overloaded operators, selectors,
3464 // etc.).
3465 IdentifierInfo *Name = ND->getIdentifier();
3466 if (!Name)
3467 return;
3468
Richard Smithe156254d2013-08-20 20:35:18 +00003469 // Only consider visible declarations and declarations from modules with
3470 // names that exactly match.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003471 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo &&
Richard Smithe156254d2013-08-20 20:35:18 +00003472 !findAcceptableDecl(SemaRef, ND))
3473 return;
3474
Douglas Gregor57756ea2010-10-14 22:11:03 +00003475 FoundName(Name->getName());
3476}
3477
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003478void TypoCorrectionConsumer::FoundName(StringRef Name) {
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003479 // Compute the edit distance between the typo and the name of this
3480 // entity, and add the identifier to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003481 addName(Name, nullptr);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003482}
3483
3484void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3485 // Compute the edit distance between the typo and this keyword,
3486 // and add the keyword to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003487 addName(Keyword, nullptr, nullptr, true);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003488}
3489
3490void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
3491 NestedNameSpecifier *NNS, bool isKeyword) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003492 // Use a simple length-based heuristic to determine the minimum possible
3493 // edit distance. If the minimum isn't good enough, bail out early.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003494 StringRef TypoStr = Typo->getName();
3495 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
3496 if (MinED && TypoStr.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00003497 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003498
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003499 // Compute an upper bound on the allowable edit distance, so that the
3500 // edit-distance algorithm can short-circuit.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003501 unsigned UpperBound = (TypoStr.size() + 2) / 3 + 1;
3502 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003503 if (ED >= UpperBound) return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003504
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003505 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003506 if (isKeyword) TC.makeKeyword();
Kaelyn Takata0a313022014-11-20 22:06:26 +00003507 TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003508 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003509}
3510
Kaelyn Takatad2287c32014-10-27 18:07:13 +00003511static const unsigned MaxTypoDistanceResultSets = 5;
3512
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003513void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003514 StringRef TypoStr = Typo->getName();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003515 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003516
3517 // For very short typos, ignore potential corrections that have a different
3518 // base identifier from the typo or which have a normalized edit distance
3519 // longer than the typo itself.
3520 if (TypoStr.size() < 3 &&
3521 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
3522 return;
3523
3524 // If the correction is resolved but is not viable, ignore it.
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003525 if (Correction.isResolved()) {
3526 checkCorrectionVisibility(SemaRef, Correction);
3527 if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
3528 return;
3529 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003530
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003531 TypoResultList &CList =
3532 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003533
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003534 if (!CList.empty() && !CList.back().isResolved())
3535 CList.pop_back();
3536 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3537 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3538 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3539 RI != RIEnd; ++RI) {
3540 // If the Correction refers to a decl already in the result list,
3541 // replace the existing result if the string representation of Correction
3542 // comes before the current result alphabetically, then stop as there is
3543 // nothing more to be done to add Correction to the candidate set.
3544 if (RI->getCorrectionDecl() == NewND) {
3545 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3546 *RI = Correction;
3547 return;
3548 }
3549 }
3550 }
3551 if (CList.empty() || Correction.isResolved())
3552 CList.push_back(Correction);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003553
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003554 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003555 CorrectionResults.erase(std::prev(CorrectionResults.end()));
3556}
3557
3558void TypoCorrectionConsumer::addNamespaces(
3559 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
3560 SearchNamespaces = true;
3561
3562 for (auto KNPair : KnownNamespaces)
3563 Namespaces.addNameSpecifier(KNPair.first);
3564
3565 bool SSIsTemplate = false;
3566 if (NestedNameSpecifier *NNS =
3567 (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
3568 if (const Type *T = NNS->getAsType())
3569 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
3570 }
3571 for (const auto *TI : SemaRef.getASTContext().types()) {
3572 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
3573 CD = CD->getCanonicalDecl();
3574 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
3575 !CD->isUnion() && CD->getIdentifier() &&
3576 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
3577 (CD->isBeingDefined() || CD->isCompleteDefinition()))
3578 Namespaces.addNameSpecifier(CD);
3579 }
3580 }
3581}
3582
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003583const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
3584 if (++CurrentTCIndex < ValidatedCorrections.size())
3585 return ValidatedCorrections[CurrentTCIndex];
3586
3587 CurrentTCIndex = ValidatedCorrections.size();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003588 while (!CorrectionResults.empty()) {
3589 auto DI = CorrectionResults.begin();
3590 if (DI->second.empty()) {
3591 CorrectionResults.erase(DI);
3592 continue;
3593 }
3594
3595 auto RI = DI->second.begin();
3596 if (RI->second.empty()) {
3597 DI->second.erase(RI);
3598 performQualifiedLookups();
3599 continue;
3600 }
3601
3602 TypoCorrection TC = RI->second.pop_back_val();
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003603 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003604 ValidatedCorrections.push_back(TC);
3605 return ValidatedCorrections[CurrentTCIndex];
3606 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003607 }
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003608 return ValidatedCorrections[0]; // The empty correction.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003609}
3610
3611bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
3612 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
3613 DeclContext *TempMemberContext = MemberContext;
Kaelyn Takata6c759512014-10-27 18:07:37 +00003614 CXXScopeSpec *TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003615retry_lookup:
3616 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
3617 EnteringContext,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00003618 CorrectionValidator->IsObjCIvarLookup,
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003619 Name == Typo && !Candidate.WillReplaceSpecifier());
3620 switch (Result.getResultKind()) {
3621 case LookupResult::NotFound:
3622 case LookupResult::NotFoundInCurrentInstantiation:
3623 case LookupResult::FoundUnresolvedValue:
3624 if (TempSS) {
3625 // Immediately retry the lookup without the given CXXScopeSpec
3626 TempSS = nullptr;
3627 Candidate.WillReplaceSpecifier(true);
3628 goto retry_lookup;
3629 }
3630 if (TempMemberContext) {
3631 if (SS && !TempSS)
Kaelyn Takata6c759512014-10-27 18:07:37 +00003632 TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003633 TempMemberContext = nullptr;
3634 goto retry_lookup;
3635 }
3636 if (SearchNamespaces)
3637 QualifiedResults.push_back(Candidate);
3638 break;
3639
3640 case LookupResult::Ambiguous:
3641 // We don't deal with ambiguities.
3642 break;
3643
3644 case LookupResult::Found:
3645 case LookupResult::FoundOverloaded:
3646 // Store all of the Decls for overloaded symbols
3647 for (auto *TRD : Result)
3648 Candidate.addCorrectionDecl(TRD);
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003649 checkCorrectionVisibility(SemaRef, Candidate);
Kaelyn Takata89c881b2014-10-27 18:07:29 +00003650 if (!isCandidateViable(*CorrectionValidator, Candidate)) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003651 if (SearchNamespaces)
3652 QualifiedResults.push_back(Candidate);
3653 break;
3654 }
Kaelyn Takata20deb1d2015-01-28 00:46:09 +00003655 Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003656 return true;
3657 }
3658 return false;
3659}
3660
3661void TypoCorrectionConsumer::performQualifiedLookups() {
3662 unsigned TypoLen = Typo->getName().size();
3663 for (auto QR : QualifiedResults) {
3664 for (auto NSI : Namespaces) {
3665 DeclContext *Ctx = NSI.DeclCtx;
3666 const Type *NSType = NSI.NameSpecifier->getAsType();
3667
3668 // If the current NestedNameSpecifier refers to a class and the
3669 // current correction candidate is the name of that class, then skip
3670 // it as it is unlikely a qualified version of the class' constructor
3671 // is an appropriate correction.
3672 if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() : 0) {
3673 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
3674 continue;
3675 }
3676
3677 TypoCorrection TC(QR);
3678 TC.ClearCorrectionDecls();
3679 TC.setCorrectionSpecifier(NSI.NameSpecifier);
3680 TC.setQualifierDistance(NSI.EditDistance);
3681 TC.setCallbackDistance(0); // Reset the callback distance
3682
3683 // If the current correction candidate and namespace combination are
3684 // too far away from the original typo based on the normalized edit
3685 // distance, then skip performing a qualified name lookup.
3686 unsigned TmpED = TC.getEditDistance(true);
3687 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
3688 TypoLen / TmpED < 3)
3689 continue;
3690
3691 Result.clear();
3692 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
3693 if (!SemaRef.LookupQualifiedName(Result, Ctx))
3694 continue;
3695
3696 // Any corrections added below will be validated in subsequent
3697 // iterations of the main while() loop over the Consumer's contents.
3698 switch (Result.getResultKind()) {
3699 case LookupResult::Found:
3700 case LookupResult::FoundOverloaded: {
3701 if (SS && SS->isValid()) {
3702 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
3703 std::string OldQualified;
3704 llvm::raw_string_ostream OldOStream(OldQualified);
3705 SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
3706 OldOStream << Typo->getName();
3707 // If correction candidate would be an identical written qualified
3708 // identifer, then the existing CXXScopeSpec probably included a
3709 // typedef that didn't get accounted for properly.
3710 if (OldOStream.str() == NewQualified)
3711 break;
3712 }
3713 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
3714 TRD != TRDEnd; ++TRD) {
3715 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
3716 NSType ? NSType->getAsCXXRecordDecl()
3717 : nullptr,
3718 TRD.getPair()) == Sema::AR_accessible)
3719 TC.addCorrectionDecl(*TRD);
3720 }
Kaelyn Takata0a313022014-11-20 22:06:26 +00003721 if (TC.isResolved()) {
3722 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003723 addCorrection(TC);
Kaelyn Takata0a313022014-11-20 22:06:26 +00003724 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003725 break;
3726 }
3727 case LookupResult::NotFound:
3728 case LookupResult::NotFoundInCurrentInstantiation:
3729 case LookupResult::Ambiguous:
3730 case LookupResult::FoundUnresolvedValue:
3731 break;
3732 }
3733 }
3734 }
3735 QualifiedResults.clear();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003736}
3737
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00003738TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
3739 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
Benjamin Kramer15537272015-03-13 16:10:42 +00003740 : Context(Context), CurContextChain(buildContextChain(CurContext)) {
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00003741 if (NestedNameSpecifier *NNS =
3742 CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
3743 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
3744 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3745
3746 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
3747 }
3748 // Build the list of identifiers that would be used for an absolute
3749 // (from the global context) NestedNameSpecifier referring to the current
3750 // context.
3751 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3752 CEnd = CurContextChain.rend();
3753 C != CEnd; ++C) {
3754 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3755 CurContextIdentifiers.push_back(ND->getIdentifier());
3756 }
3757
3758 // Add the global context as a NestedNameSpecifier
Hans Wennborg66010132014-06-11 21:24:13 +00003759 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
3760 NestedNameSpecifier::GlobalSpecifier(Context), 1};
3761 DistanceMap[1].push_back(SI);
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00003762}
3763
Kaelyn Takata7dcc0e62014-06-11 18:07:08 +00003764auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
3765 DeclContext *Start) -> DeclContextList {
Nick Lewycky0d9b3192013-04-08 21:55:21 +00003766 assert(Start && "Building a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003767 DeclContextList Chain;
Craig Topperc3ec1492014-05-26 06:22:03 +00003768 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003769 DC = DC->getLookupParent()) {
3770 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3771 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3772 !(ND && ND->isAnonymousNamespace()))
3773 Chain.push_back(DC->getPrimaryContext());
3774 }
3775 return Chain;
3776}
3777
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003778unsigned
3779TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
3780 DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003781 unsigned NumSpecifiers = 0;
3782 for (DeclContextList::reverse_iterator C = DeclChain.rbegin(),
3783 CEnd = DeclChain.rend();
3784 C != CEnd; ++C) {
3785 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) {
3786 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3787 ++NumSpecifiers;
3788 } else if (RecordDecl *RD = dyn_cast_or_null<RecordDecl>(*C)) {
3789 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
3790 RD->getTypeForDecl());
3791 ++NumSpecifiers;
3792 }
3793 }
3794 return NumSpecifiers;
3795}
3796
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003797void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
3798 DeclContext *Ctx) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003799 NestedNameSpecifier *NNS = nullptr;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003800 unsigned NumSpecifiers = 0;
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003801 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003802 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
3803
3804 // Eliminate common elements from the two DeclContext chains.
3805 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3806 CEnd = CurContextChain.rend();
3807 C != CEnd && !NamespaceDeclChain.empty() &&
3808 NamespaceDeclChain.back() == *C; ++C) {
3809 NamespaceDeclChain.pop_back();
3810 }
3811
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003812 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003813 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003814
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003815 // Add an explicit leading '::' specifier if needed.
3816 if (NamespaceDeclChain.empty()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003817 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003818 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003819 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003820 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003821 } else if (NamedDecl *ND =
3822 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003823 IdentifierInfo *Name = ND->getIdentifier();
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003824 bool SameNameSpecifier = false;
3825 if (std::find(CurNameSpecifierIdentifiers.begin(),
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003826 CurNameSpecifierIdentifiers.end(),
3827 Name) != CurNameSpecifierIdentifiers.end()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003828 std::string NewNameSpecifier;
3829 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
3830 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
3831 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3832 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3833 SpecifierOStream.flush();
3834 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003835 }
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003836 if (SameNameSpecifier ||
3837 std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3838 Name) != CurContextIdentifiers.end()) {
3839 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
3840 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3841 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003842 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003843 }
3844 }
3845
3846 // If the built NestedNameSpecifier would be replacing an existing
3847 // NestedNameSpecifier, use the number of component identifiers that
3848 // would need to be changed as the edit distance instead of the number
3849 // of components in the built NestedNameSpecifier.
3850 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3851 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3852 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3853 NumSpecifiers = llvm::ComputeEditDistance(
Craig Topper8c2a2a02014-08-30 16:55:39 +00003854 llvm::makeArrayRef(CurNameSpecifierIdentifiers),
3855 llvm::makeArrayRef(NewNameSpecifierIdentifiers));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003856 }
3857
Hans Wennborg66010132014-06-11 21:24:13 +00003858 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
3859 DistanceMap[NumSpecifiers].push_back(SI);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003860}
3861
Douglas Gregord507d772010-10-20 03:06:34 +00003862/// \brief Perform name lookup for a possible result for typo correction.
3863static void LookupPotentialTypoResult(Sema &SemaRef,
3864 LookupResult &Res,
3865 IdentifierInfo *Name,
3866 Scope *S, CXXScopeSpec *SS,
3867 DeclContext *MemberContext,
3868 bool EnteringContext,
Richard Smithe156254d2013-08-20 20:35:18 +00003869 bool isObjCIvarLookup,
3870 bool FindHidden) {
Douglas Gregord507d772010-10-20 03:06:34 +00003871 Res.suppressDiagnostics();
3872 Res.clear();
3873 Res.setLookupName(Name);
Richard Smithe156254d2013-08-20 20:35:18 +00003874 Res.setAllowHidden(FindHidden);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003875 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00003876 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003877 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00003878 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3879 Res.addDecl(Ivar);
3880 Res.resolveKind();
3881 return;
3882 }
3883 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003884
Douglas Gregord507d772010-10-20 03:06:34 +00003885 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3886 Res.addDecl(Prop);
3887 Res.resolveKind();
3888 return;
3889 }
3890 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003891
Douglas Gregord507d772010-10-20 03:06:34 +00003892 SemaRef.LookupQualifiedName(Res, MemberContext);
3893 return;
3894 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003895
3896 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00003897 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003898
Douglas Gregord507d772010-10-20 03:06:34 +00003899 // Fake ivar lookup; this should really be part of
3900 // LookupParsedName.
3901 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3902 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003903 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00003904 (Res.isSingleResult() &&
3905 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003906 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00003907 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3908 Res.addDecl(IV);
3909 Res.resolveKind();
3910 }
3911 }
3912 }
3913}
3914
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003915/// \brief Add keywords to the consumer as possible typo corrections.
3916static void AddKeywordsToConsumer(Sema &SemaRef,
3917 TypoCorrectionConsumer &Consumer,
Richard Smithb3a1df02012-06-08 21:35:42 +00003918 Scope *S, CorrectionCandidateCallback &CCC,
3919 bool AfterNestedNameSpecifier) {
3920 if (AfterNestedNameSpecifier) {
3921 // For 'X::', we know exactly which keywords can appear next.
3922 Consumer.addKeywordResult("template");
3923 if (CCC.WantExpressionKeywords)
3924 Consumer.addKeywordResult("operator");
3925 return;
3926 }
3927
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003928 if (CCC.WantObjCSuper)
3929 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003930
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003931 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003932 // Add type-specifier keywords to the set of results.
Craig Topperd6d31ac2013-07-15 08:24:27 +00003933 static const char *const CTypeSpecs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003934 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00003935 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003936 "_Complex", "_Imaginary",
3937 // storage-specifiers as well
3938 "extern", "inline", "static", "typedef"
3939 };
3940
Craig Toppere5ce8312013-07-15 03:38:40 +00003941 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003942 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3943 Consumer.addKeywordResult(CTypeSpecs[I]);
3944
David Blaikiebbafb8a2012-03-11 07:00:24 +00003945 if (SemaRef.getLangOpts().C99)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003946 Consumer.addKeywordResult("restrict");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003947 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003948 Consumer.addKeywordResult("bool");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003949 else if (SemaRef.getLangOpts().C99)
Douglas Gregor3b22a882011-07-01 21:27:45 +00003950 Consumer.addKeywordResult("_Bool");
3951
David Blaikiebbafb8a2012-03-11 07:00:24 +00003952 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003953 Consumer.addKeywordResult("class");
3954 Consumer.addKeywordResult("typename");
3955 Consumer.addKeywordResult("wchar_t");
3956
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003957 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003958 Consumer.addKeywordResult("char16_t");
3959 Consumer.addKeywordResult("char32_t");
3960 Consumer.addKeywordResult("constexpr");
3961 Consumer.addKeywordResult("decltype");
3962 Consumer.addKeywordResult("thread_local");
3963 }
3964 }
3965
David Blaikiebbafb8a2012-03-11 07:00:24 +00003966 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003967 Consumer.addKeywordResult("typeof");
Kaelyn Takatab04846b2014-07-28 18:14:02 +00003968 } else if (CCC.WantFunctionLikeCasts) {
3969 static const char *const CastableTypeSpecs[] = {
3970 "char", "double", "float", "int", "long", "short",
3971 "signed", "unsigned", "void"
3972 };
3973 for (auto *kw : CastableTypeSpecs)
3974 Consumer.addKeywordResult(kw);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003975 }
3976
David Blaikiebbafb8a2012-03-11 07:00:24 +00003977 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003978 Consumer.addKeywordResult("const_cast");
3979 Consumer.addKeywordResult("dynamic_cast");
3980 Consumer.addKeywordResult("reinterpret_cast");
3981 Consumer.addKeywordResult("static_cast");
3982 }
3983
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003984 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003985 Consumer.addKeywordResult("sizeof");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003986 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003987 Consumer.addKeywordResult("false");
3988 Consumer.addKeywordResult("true");
3989 }
3990
David Blaikiebbafb8a2012-03-11 07:00:24 +00003991 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topperd6d31ac2013-07-15 08:24:27 +00003992 static const char *const CXXExprs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003993 "delete", "new", "operator", "throw", "typeid"
3994 };
Craig Toppere5ce8312013-07-15 03:38:40 +00003995 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003996 for (unsigned I = 0; I != NumCXXExprs; ++I)
3997 Consumer.addKeywordResult(CXXExprs[I]);
3998
3999 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
4000 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
4001 Consumer.addKeywordResult("this");
4002
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004003 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004004 Consumer.addKeywordResult("alignof");
4005 Consumer.addKeywordResult("nullptr");
4006 }
4007 }
Jordan Rose58d54722012-06-30 21:33:57 +00004008
4009 if (SemaRef.getLangOpts().C11) {
4010 // FIXME: We should not suggest _Alignof if the alignof macro
4011 // is present.
4012 Consumer.addKeywordResult("_Alignof");
4013 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004014 }
4015
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004016 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004017 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
4018 // Statements.
Craig Topperd6d31ac2013-07-15 08:24:27 +00004019 static const char *const CStmts[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004020 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Toppere5ce8312013-07-15 03:38:40 +00004021 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004022 for (unsigned I = 0; I != NumCStmts; ++I)
4023 Consumer.addKeywordResult(CStmts[I]);
4024
David Blaikiebbafb8a2012-03-11 07:00:24 +00004025 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004026 Consumer.addKeywordResult("catch");
4027 Consumer.addKeywordResult("try");
4028 }
4029
4030 if (S && S->getBreakParent())
4031 Consumer.addKeywordResult("break");
4032
4033 if (S && S->getContinueParent())
4034 Consumer.addKeywordResult("continue");
4035
4036 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
4037 Consumer.addKeywordResult("case");
4038 Consumer.addKeywordResult("default");
4039 }
4040 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004041 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004042 Consumer.addKeywordResult("namespace");
4043 Consumer.addKeywordResult("template");
4044 }
4045
4046 if (S && S->isClassScope()) {
4047 Consumer.addKeywordResult("explicit");
4048 Consumer.addKeywordResult("friend");
4049 Consumer.addKeywordResult("mutable");
4050 Consumer.addKeywordResult("private");
4051 Consumer.addKeywordResult("protected");
4052 Consumer.addKeywordResult("public");
4053 Consumer.addKeywordResult("virtual");
4054 }
4055 }
4056
David Blaikiebbafb8a2012-03-11 07:00:24 +00004057 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004058 Consumer.addKeywordResult("using");
4059
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004060 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004061 Consumer.addKeywordResult("static_assert");
4062 }
4063 }
4064}
4065
Kaelyn Takata6c759512014-10-27 18:07:37 +00004066std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
4067 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4068 Scope *S, CXXScopeSpec *SS,
4069 std::unique_ptr<CorrectionCandidateCallback> CCC,
4070 DeclContext *MemberContext, bool EnteringContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004071 const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00004072
4073 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4074 DisableTypoCorrection)
4075 return nullptr;
4076
4077 // In Microsoft mode, don't perform typo correction in a template member
4078 // function dependent context because it interferes with the "lookup into
4079 // dependent bases of class templates" feature.
4080 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
4081 isa<CXXMethodDecl>(CurContext))
4082 return nullptr;
4083
4084 // We only attempt to correct typos for identifiers.
4085 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4086 if (!Typo)
4087 return nullptr;
4088
4089 // If the scope specifier itself was invalid, don't try to correct
4090 // typos.
4091 if (SS && SS->isInvalid())
4092 return nullptr;
4093
4094 // Never try to correct typos during template deduction or
4095 // instantiation.
4096 if (!ActiveTemplateInstantiations.empty())
4097 return nullptr;
4098
4099 // Don't try to correct 'super'.
4100 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4101 return nullptr;
4102
4103 // Abort if typo correction already failed for this specific typo.
4104 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4105 if (locs != TypoCorrectionFailures.end() &&
4106 locs->second.count(TypoName.getLoc()))
4107 return nullptr;
4108
4109 // Don't try to correct the identifier "vector" when in AltiVec mode.
4110 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4111 // remove this workaround.
4112 if (getLangOpts().AltiVec && Typo->isStr("vector"))
4113 return nullptr;
4114
Nick Lewycky24653262014-12-16 21:39:02 +00004115 // Provide a stop gap for files that are just seriously broken. Trying
4116 // to correct all typos can turn into a HUGE performance penalty, causing
4117 // some files to take minutes to get rejected by the parser.
4118 unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
4119 if (Limit && TyposCorrected >= Limit)
4120 return nullptr;
4121 ++TyposCorrected;
4122
Kaelyn Takata6c759512014-10-27 18:07:37 +00004123 // If we're handling a missing symbol error, using modules, and the
4124 // special search all modules option is used, look for a missing import.
4125 if (ErrorRecovery && getLangOpts().Modules &&
4126 getLangOpts().ModulesSearchAll) {
4127 // The following has the side effect of loading the missing module.
4128 getModuleLoader().lookupMissingImports(Typo->getName(),
4129 TypoName.getLocStart());
4130 }
4131
4132 CorrectionCandidateCallback &CCCRef = *CCC;
4133 auto Consumer = llvm::make_unique<TypoCorrectionConsumer>(
4134 *this, TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
4135 EnteringContext);
4136
Kaelyn Takata6c759512014-10-27 18:07:37 +00004137 // Perform name lookup to find visible, similarly-named entities.
Nick Lewycky24653262014-12-16 21:39:02 +00004138 bool IsUnqualifiedLookup = false;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004139 DeclContext *QualifiedDC = MemberContext;
4140 if (MemberContext) {
4141 LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
4142
4143 // Look in qualified interfaces.
4144 if (OPT) {
4145 for (auto *I : OPT->quals())
4146 LookupVisibleDecls(I, LookupKind, *Consumer);
4147 }
4148 } else if (SS && SS->isSet()) {
4149 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4150 if (!QualifiedDC)
4151 return nullptr;
4152
Kaelyn Takata6c759512014-10-27 18:07:37 +00004153 LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
4154 } else {
4155 IsUnqualifiedLookup = true;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004156 }
4157
4158 // Determine whether we are going to search in the various namespaces for
4159 // corrections.
4160 bool SearchNamespaces
4161 = getLangOpts().CPlusPlus &&
4162 (IsUnqualifiedLookup || (SS && SS->isSet()));
4163
4164 if (IsUnqualifiedLookup || SearchNamespaces) {
4165 // For unqualified lookup, look through all of the names that we have
4166 // seen in this translation unit.
4167 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4168 for (const auto &I : Context.Idents)
4169 Consumer->FoundName(I.getKey());
4170
4171 // Walk through identifiers in external identifier sources.
4172 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4173 if (IdentifierInfoLookup *External
4174 = Context.Idents.getExternalIdentifierLookup()) {
4175 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4176 do {
4177 StringRef Name = Iter->Next();
4178 if (Name.empty())
4179 break;
4180
4181 Consumer->FoundName(Name);
4182 } while (true);
4183 }
4184 }
4185
4186 AddKeywordsToConsumer(*this, *Consumer, S, CCCRef, SS && SS->isNotEmpty());
4187
4188 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4189 // to search those namespaces.
4190 if (SearchNamespaces) {
4191 // Load any externally-known namespaces.
4192 if (ExternalSource && !LoadedExternalKnownNamespaces) {
4193 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
4194 LoadedExternalKnownNamespaces = true;
4195 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4196 for (auto *N : ExternalKnownNamespaces)
4197 KnownNamespaces[N] = true;
4198 }
4199
4200 Consumer->addNamespaces(KnownNamespaces);
4201 }
4202
4203 return Consumer;
4204}
4205
Douglas Gregor2d435302009-12-30 17:04:44 +00004206/// \brief Try to "correct" a typo in the source code by finding
4207/// visible declarations whose names are similar to the name that was
4208/// present in the source code.
4209///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004210/// \param TypoName the \c DeclarationNameInfo structure that contains
4211/// the name that was present in the source code along with its location.
4212///
4213/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00004214///
4215/// \param S the scope in which name lookup occurs.
4216///
4217/// \param SS the nested-name-specifier that precedes the name we're
4218/// looking for, if present.
4219///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004220/// \param CCC A CorrectionCandidateCallback object that provides further
4221/// validation of typo correction candidates. It also provides flags for
4222/// determining the set of keywords permitted.
4223///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00004224/// \param MemberContext if non-NULL, the context in which to look for
4225/// a member access expression.
4226///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004227/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00004228/// the nested-name-specifier SS.
4229///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004230/// \param OPT when non-NULL, the search for visible declarations will
4231/// also walk the protocols in the qualified interfaces of \p OPT.
4232///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004233/// \returns a \c TypoCorrection containing the corrected name if the typo
4234/// along with information such as the \c NamedDecl where the corrected name
4235/// was declared, and any additional \c NestedNameSpecifier needed to access
4236/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
4237TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
4238 Sema::LookupNameKind LookupKind,
4239 Scope *S, CXXScopeSpec *SS,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004240 std::unique_ptr<CorrectionCandidateCallback> CCC,
John Thompson2255f2c2014-04-23 12:57:01 +00004241 CorrectTypoKind Mode,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004242 DeclContext *MemberContext,
4243 bool EnteringContext,
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004244 const ObjCObjectPointerType *OPT,
4245 bool RecordFailure) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004246 assert(CCC && "CorrectTypo requires a CorrectionCandidateCallback");
4247
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004248 // Always let the ExternalSource have the first chance at correction, even
4249 // if we would otherwise have given up.
4250 if (ExternalSource) {
4251 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004252 TypoName, LookupKind, S, SS, *CCC, MemberContext, EnteringContext, OPT))
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004253 return Correction;
4254 }
4255
Kaelyn Takata6c759512014-10-27 18:07:37 +00004256 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4257 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4258 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4259 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
4260 bool ObjCMessageReceiver = CCC->WantObjCSuper && !CCC->WantRemainingKeywords;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004261
Kaelyn Takata6c759512014-10-27 18:07:37 +00004262 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Kaelyn Takata6c759512014-10-27 18:07:37 +00004263 auto Consumer = makeTypoCorrectionConsumer(
4264 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004265 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004266
Kaelyn Takata6c759512014-10-27 18:07:37 +00004267 if (!Consumer)
4268 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004269
Douglas Gregor280e1ee2010-04-14 20:04:41 +00004270 // If we haven't found anything, we're done.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004271 if (Consumer->empty())
Nick Lewycky24653262014-12-16 21:39:02 +00004272 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregor2d435302009-12-30 17:04:44 +00004273
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004274 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4275 // is not more that about a third of the length of the typo's identifier.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004276 unsigned ED = Consumer->getBestEditDistance(true);
4277 unsigned TypoLen = Typo->getName().size();
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004278 if (ED > 0 && TypoLen / ED < 3)
Nick Lewycky24653262014-12-16 21:39:02 +00004279 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004280
Kaelyn Takata6c759512014-10-27 18:07:37 +00004281 TypoCorrection BestTC = Consumer->getNextCorrection();
4282 TypoCorrection SecondBestTC = Consumer->getNextCorrection();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004283 if (!BestTC)
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004284 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004285
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004286 ED = BestTC.getEditDistance();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004287
Kaelyn Takata6c759512014-10-27 18:07:37 +00004288 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004289 // If this was an unqualified lookup and we believe the callback
4290 // object wouldn't have filtered out possible corrections, note
4291 // that no correction was found.
Nick Lewycky24653262014-12-16 21:39:02 +00004292 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004293 }
4294
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004295 // If only a single name remains, return that result.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004296 if (!SecondBestTC ||
4297 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
4298 const TypoCorrection &Result = BestTC;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004299
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00004300 // Don't correct to a keyword that's the same as the typo; the keyword
4301 // wasn't actually in scope.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004302 if (ED == 0 && Result.isKeyword())
4303 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004304
David Blaikie04ea41c2012-10-12 20:00:44 +00004305 TypoCorrection TC = Result;
4306 TC.setCorrectionRange(SS, TypoName);
Kaelyn Takataa95ebc62014-06-17 23:47:29 +00004307 checkCorrectionVisibility(*this, TC);
David Blaikie04ea41c2012-10-12 20:00:44 +00004308 return TC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004309 } else if (SecondBestTC && ObjCMessageReceiver) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004310 // Prefer 'super' when we're completing in a message-receiver
4311 // context.
4312
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004313 if (BestTC.getCorrection().getAsString() != "super") {
4314 if (SecondBestTC.getCorrection().getAsString() == "super")
4315 BestTC = SecondBestTC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004316 else if ((*Consumer)["super"].front().isKeyword())
4317 BestTC = (*Consumer)["super"].front();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004318 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004319 // Don't correct to a keyword that's the same as the typo; the keyword
4320 // wasn't actually in scope.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004321 if (BestTC.getEditDistance() == 0 ||
4322 BestTC.getCorrection().getAsString() != "super")
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004323 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004324
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004325 BestTC.setCorrectionRange(SS, TypoName);
4326 return BestTC;
Douglas Gregoraf9eb592010-10-15 13:35:25 +00004327 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004328
Kaelyn Takata73429fd2014-06-10 21:03:49 +00004329 // Record the failure's location if needed and return an empty correction. If
4330 // this was an unqualified lookup and we believe the callback object did not
4331 // filter out possible corrections, also cache the failure for the typo.
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004332 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004333}
4334
Kaelyn Takata6c759512014-10-27 18:07:37 +00004335/// \brief Try to "correct" a typo in the source code by finding
4336/// visible declarations whose names are similar to the name that was
4337/// present in the source code.
4338///
4339/// \param TypoName the \c DeclarationNameInfo structure that contains
4340/// the name that was present in the source code along with its location.
4341///
4342/// \param LookupKind the name-lookup criteria used to search for the name.
4343///
4344/// \param S the scope in which name lookup occurs.
4345///
4346/// \param SS the nested-name-specifier that precedes the name we're
4347/// looking for, if present.
4348///
4349/// \param CCC A CorrectionCandidateCallback object that provides further
4350/// validation of typo correction candidates. It also provides flags for
4351/// determining the set of keywords permitted.
4352///
4353/// \param TDG A TypoDiagnosticGenerator functor that will be used to print
4354/// diagnostics when the actual typo correction is attempted.
4355///
Kaelyn Takata8363f042014-10-27 18:07:42 +00004356/// \param TRC A TypoRecoveryCallback functor that will be used to build an
4357/// Expr from a typo correction candidate.
4358///
Kaelyn Takata6c759512014-10-27 18:07:37 +00004359/// \param MemberContext if non-NULL, the context in which to look for
4360/// a member access expression.
4361///
4362/// \param EnteringContext whether we're entering the context described by
4363/// the nested-name-specifier SS.
4364///
4365/// \param OPT when non-NULL, the search for visible declarations will
4366/// also walk the protocols in the qualified interfaces of \p OPT.
4367///
4368/// \returns a new \c TypoExpr that will later be replaced in the AST with an
4369/// Expr representing the result of performing typo correction, or nullptr if
4370/// typo correction is not possible. If nullptr is returned, no diagnostics will
4371/// be emitted and it is the responsibility of the caller to emit any that are
4372/// needed.
4373TypoExpr *Sema::CorrectTypoDelayed(
4374 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4375 Scope *S, CXXScopeSpec *SS,
4376 std::unique_ptr<CorrectionCandidateCallback> CCC,
Kaelyn Takata8363f042014-10-27 18:07:42 +00004377 TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,
Kaelyn Takata6c759512014-10-27 18:07:37 +00004378 DeclContext *MemberContext, bool EnteringContext,
4379 const ObjCObjectPointerType *OPT) {
4380 assert(CCC && "CorrectTypoDelayed requires a CorrectionCandidateCallback");
4381
4382 TypoCorrection Empty;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004383 auto Consumer = makeTypoCorrectionConsumer(
4384 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004385 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Kaelyn Takata6c759512014-10-27 18:07:37 +00004386
4387 if (!Consumer || Consumer->empty())
4388 return nullptr;
4389
4390 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4391 // is not more that about a third of the length of the typo's identifier.
4392 unsigned ED = Consumer->getBestEditDistance(true);
4393 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4394 if (ED > 0 && Typo->getName().size() / ED < 3)
4395 return nullptr;
4396
4397 ExprEvalContexts.back().NumTypos++;
Kaelyn Takata8363f042014-10-27 18:07:42 +00004398 return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC));
Kaelyn Takata6c759512014-10-27 18:07:37 +00004399}
4400
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004401void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4402 if (!CDecl) return;
4403
4404 if (isKeyword())
4405 CorrectionDecls.clear();
4406
Kaelyn Uhrainf60b55a2012-11-19 18:49:53 +00004407 CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004408
4409 if (!CorrectionName)
4410 CorrectionName = CDecl->getDeclName();
4411}
4412
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004413std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4414 if (CorrectionNameSpec) {
4415 std::string tmpBuffer;
4416 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4417 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikied4da8722013-05-14 21:04:00 +00004418 PrefixOStream << CorrectionName;
Benjamin Kramer73faad62012-04-14 08:26:28 +00004419 return PrefixOStream.str();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004420 }
4421
4422 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00004423}
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004424
Nico Weberb58e51c2014-11-19 05:21:39 +00004425bool CorrectionCandidateCallback::ValidateCandidate(
4426 const TypoCorrection &candidate) {
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004427 if (!candidate.isResolved())
4428 return true;
4429
4430 if (candidate.isKeyword())
4431 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4432 WantRemainingKeywords || WantObjCSuper;
4433
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004434 bool HasNonType = false;
4435 bool HasStaticMethod = false;
4436 bool HasNonStaticMethod = false;
4437 for (Decl *D : candidate) {
4438 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
4439 D = FTD->getTemplatedDecl();
4440 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4441 if (Method->isStatic())
4442 HasStaticMethod = true;
4443 else
4444 HasNonStaticMethod = true;
4445 }
4446 if (!isa<TypeDecl>(D))
4447 HasNonType = true;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004448 }
4449
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004450 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
4451 !candidate.getCorrectionSpecifier())
4452 return false;
4453
4454 return WantTypeSpecifiers || HasNonType;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004455}
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004456
4457FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004458 bool HasExplicitTemplateArgs,
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004459 MemberExpr *ME)
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004460 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004461 CurContext(SemaRef.CurContext), MemberFn(ME) {
Kaelyn Takatab04846b2014-07-28 18:14:02 +00004462 WantTypeSpecifiers = false;
4463 WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus && NumArgs == 1;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004464 WantRemainingKeywords = false;
4465}
4466
4467bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4468 if (!candidate.getCorrectionDecl())
4469 return candidate.isKeyword();
4470
Aaron Ballman1e606f42014-07-15 22:03:49 +00004471 for (auto *C : candidate) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004472 FunctionDecl *FD = nullptr;
Aaron Ballman1e606f42014-07-15 22:03:49 +00004473 NamedDecl *ND = C->getUnderlyingDecl();
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004474 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4475 FD = FTD->getTemplatedDecl();
4476 if (!HasExplicitTemplateArgs && !FD) {
4477 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4478 // If the Decl is neither a function nor a template function,
4479 // determine if it is a pointer or reference to a function. If so,
4480 // check against the number of arguments expected for the pointee.
4481 QualType ValType = cast<ValueDecl>(ND)->getType();
4482 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4483 ValType = ValType->getPointeeType();
4484 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
Alp Toker9cacbab2014-01-20 20:26:09 +00004485 if (FPT->getNumParams() == NumArgs)
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004486 return true;
4487 }
4488 }
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004489
4490 // Skip the current candidate if it is not a FunctionDecl or does not accept
4491 // the current number of arguments.
4492 if (!FD || !(FD->getNumParams() >= NumArgs &&
4493 FD->getMinRequiredArguments() <= NumArgs))
4494 continue;
4495
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004496 // If the current candidate is a non-static C++ method, skip the candidate
4497 // unless the method being corrected--or the current DeclContext, if the
4498 // function being corrected is not a method--is a method in the same class
4499 // or a descendent class of the candidate's parent class.
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004500 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004501 if (MemberFn || !MD->isStatic()) {
4502 CXXMethodDecl *CurMD =
4503 MemberFn
4504 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
4505 : dyn_cast_or_null<CXXMethodDecl>(CurContext);
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004506 CXXRecordDecl *CurRD =
Craig Topperc3ec1492014-05-26 06:22:03 +00004507 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004508 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
4509 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
4510 continue;
4511 }
4512 }
4513 return true;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004514 }
4515 return false;
4516}
Richard Smithf9b15102013-08-17 00:46:16 +00004517
4518void Sema::diagnoseTypo(const TypoCorrection &Correction,
4519 const PartialDiagnostic &TypoDiag,
4520 bool ErrorRecovery) {
4521 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
4522 ErrorRecovery);
4523}
4524
Richard Smithe156254d2013-08-20 20:35:18 +00004525/// Find which declaration we should import to provide the definition of
4526/// the given declaration.
4527static const NamedDecl *getDefinitionToImport(const NamedDecl *D) {
4528 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4529 return VD->getDefinition();
4530 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +00004531 return FD->isDefined(FD) ? FD : nullptr;
Richard Smithe156254d2013-08-20 20:35:18 +00004532 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
4533 return TD->getDefinition();
4534 if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
4535 return ID->getDefinition();
4536 if (const ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
4537 return PD->getDefinition();
4538 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
4539 return getDefinitionToImport(TD->getTemplatedDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004540 return nullptr;
Richard Smithe156254d2013-08-20 20:35:18 +00004541}
4542
Richard Smithf9b15102013-08-17 00:46:16 +00004543/// \brief Diagnose a successfully-corrected typo. Separated from the correction
4544/// itself to allow external validation of the result, etc.
4545///
4546/// \param Correction The result of performing typo correction.
4547/// \param TypoDiag The diagnostic to produce. This will have the corrected
4548/// string added to it (and usually also a fixit).
4549/// \param PrevNote A note to use when indicating the location of the entity to
4550/// which we are correcting. Will have the correction string added to it.
4551/// \param ErrorRecovery If \c true (the default), the caller is going to
4552/// recover from the typo as if the corrected string had been typed.
4553/// In this case, \c PDiag must be an error, and we will attach a fixit
4554/// to it.
4555void Sema::diagnoseTypo(const TypoCorrection &Correction,
4556 const PartialDiagnostic &TypoDiag,
4557 const PartialDiagnostic &PrevNote,
4558 bool ErrorRecovery) {
4559 std::string CorrectedStr = Correction.getAsString(getLangOpts());
4560 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
4561 FixItHint FixTypo = FixItHint::CreateReplacement(
4562 Correction.getCorrectionRange(), CorrectedStr);
4563
Richard Smithe156254d2013-08-20 20:35:18 +00004564 // Maybe we're just missing a module import.
4565 if (Correction.requiresImport()) {
4566 NamedDecl *Decl = Correction.getCorrectionDecl();
4567 assert(Decl && "import required but no declaration to import");
4568
4569 // Suggest importing a module providing the definition of this entity, if
4570 // possible.
4571 const NamedDecl *Def = getDefinitionToImport(Decl);
4572 if (!Def)
4573 Def = Decl;
4574 Module *Owner = Def->getOwningModule();
4575 assert(Owner && "definition of hidden declaration is not in a module");
4576
4577 Diag(Correction.getCorrectionRange().getBegin(),
4578 diag::err_module_private_declaration)
4579 << Def << Owner->getFullModuleName();
4580 Diag(Def->getLocation(), diag::note_previous_declaration);
4581
4582 // Recover by implicitly importing this module.
Richard Smith3d23c422014-05-07 02:25:43 +00004583 if (ErrorRecovery)
4584 createImplicitModuleImportForErrorRecovery(
4585 Correction.getCorrectionRange().getBegin(), Owner);
Richard Smithe156254d2013-08-20 20:35:18 +00004586 return;
4587 }
4588
Richard Smithf9b15102013-08-17 00:46:16 +00004589 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
4590 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
4591
4592 NamedDecl *ChosenDecl =
Craig Topperc3ec1492014-05-26 06:22:03 +00004593 Correction.isKeyword() ? nullptr : Correction.getCorrectionDecl();
Richard Smithf9b15102013-08-17 00:46:16 +00004594 if (PrevNote.getDiagID() && ChosenDecl)
4595 Diag(ChosenDecl->getLocation(), PrevNote)
4596 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
4597}
Kaelyn Takata6c759512014-10-27 18:07:37 +00004598
Kaelyn Takata8363f042014-10-27 18:07:42 +00004599TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
4600 TypoDiagnosticGenerator TDG,
4601 TypoRecoveryCallback TRC) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00004602 assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
4603 auto TE = new (Context) TypoExpr(Context.DependentTy);
4604 auto &State = DelayedTypos[TE];
4605 State.Consumer = std::move(TCC);
4606 State.DiagHandler = std::move(TDG);
Kaelyn Takata8363f042014-10-27 18:07:42 +00004607 State.RecoveryHandler = std::move(TRC);
Kaelyn Takata6c759512014-10-27 18:07:37 +00004608 return TE;
4609}
4610
4611const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
4612 auto Entry = DelayedTypos.find(TE);
4613 assert(Entry != DelayedTypos.end() &&
4614 "Failed to get the state for a TypoExpr!");
4615 return Entry->second;
4616}
4617
4618void Sema::clearDelayedTypo(TypoExpr *TE) {
4619 DelayedTypos.erase(TE);
4620}