blob: 147b81bc597bfe0713a535e5296a7e1b939a469d [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"
Richard Smith42413142015-05-15 20:05:43 +000027#include "clang/Lex/HeaderSearch.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000028#include "clang/Lex/ModuleLoader.h"
Richard Smith4caa4492015-05-15 02:34:32 +000029#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/ExternalSemaSource.h"
32#include "clang/Sema/Overload.h"
33#include "clang/Sema/Scope.h"
34#include "clang/Sema/ScopeInfo.h"
35#include "clang/Sema/Sema.h"
36#include "clang/Sema/SemaInternal.h"
37#include "clang/Sema/TemplateDeduction.h"
38#include "clang/Sema/TypoCorrection.h"
Douglas Gregor34074322009-01-14 22:20:51 +000039#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "llvm/ADT/SetVector.h"
Douglas Gregore254f902009-02-04 00:32:51 +000041#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0afa7f62010-10-14 20:34:08 +000042#include "llvm/ADT/StringMap.h"
Chris Lattner83cfc7c2011-07-18 01:54:02 +000043#include "llvm/ADT/TinyPtrVector.h"
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +000044#include "llvm/ADT/edit_distance.h"
John McCall6538c932009-10-10 05:48:19 +000045#include "llvm/Support/ErrorHandling.h"
Nick Lewycky13668f22012-04-03 20:26:45 +000046#include <algorithm>
47#include <iterator>
Douglas Gregor0afa7f62010-10-14 20:34:08 +000048#include <limits>
Douglas Gregor2d435302009-12-30 17:04:44 +000049#include <list>
Douglas Gregorc2fa1692011-06-28 16:20:02 +000050#include <map>
Nick Lewycky13668f22012-04-03 20:26:45 +000051#include <set>
52#include <utility>
53#include <vector>
Douglas Gregor34074322009-01-14 22:20:51 +000054
55using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000056using namespace sema;
Douglas Gregor34074322009-01-14 22:20:51 +000057
John McCallf6c8a4e2009-11-10 07:01:13 +000058namespace {
59 class UnqualUsingEntry {
60 const DeclContext *Nominated;
61 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000062
John McCallf6c8a4e2009-11-10 07:01:13 +000063 public:
64 UnqualUsingEntry(const DeclContext *Nominated,
65 const DeclContext *CommonAncestor)
66 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
67 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000068
John McCallf6c8a4e2009-11-10 07:01:13 +000069 const DeclContext *getCommonAncestor() const {
70 return CommonAncestor;
71 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000072
John McCallf6c8a4e2009-11-10 07:01:13 +000073 const DeclContext *getNominatedNamespace() const {
74 return Nominated;
75 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000076
John McCallf6c8a4e2009-11-10 07:01:13 +000077 // Sort by the pointer value of the common ancestor.
78 struct Comparator {
79 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
80 return L.getCommonAncestor() < R.getCommonAncestor();
81 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000082
John McCallf6c8a4e2009-11-10 07:01:13 +000083 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
84 return E.getCommonAncestor() < DC;
85 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000086
John McCallf6c8a4e2009-11-10 07:01:13 +000087 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
88 return DC < E.getCommonAncestor();
89 }
90 };
91 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000092
John McCallf6c8a4e2009-11-10 07:01:13 +000093 /// A collection of using directives, as used by C++ unqualified
94 /// lookup.
95 class UnqualUsingDirectiveSet {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000096 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000097
John McCallf6c8a4e2009-11-10 07:01:13 +000098 ListTy list;
99 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000100
John McCallf6c8a4e2009-11-10 07:01:13 +0000101 public:
102 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +0000103
John McCallf6c8a4e2009-11-10 07:01:13 +0000104 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000105 // C++ [namespace.udir]p1:
John McCallf6c8a4e2009-11-10 07:01:13 +0000106 // During unqualified name lookup, the names appear as if they
107 // were declared in the nearest enclosing namespace which contains
108 // both the using-directive and the nominated namespace.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000109 DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
John McCallf6c8a4e2009-11-10 07:01:13 +0000110 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +0000111
John McCallf6c8a4e2009-11-10 07:01:13 +0000112 for (; S; S = S->getParent()) {
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000113 // C++ [namespace.udir]p1:
114 // A using-directive shall not appear in class scope, but may
115 // appear in namespace scope or in block scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000116 DeclContext *Ctx = S->getEntity();
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000117 if (Ctx && Ctx->isFileContext()) {
118 visit(Ctx, Ctx);
119 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
Aaron Ballman5df6aa42014-03-17 17:03:37 +0000120 for (auto *I : S->using_directives())
121 visit(I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000122 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000123 }
124 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000125
126 // Visits a context and collect all of its using directives
127 // recursively. Treats all using directives as if they were
128 // declared in the context.
129 //
130 // A given context is only every visited once, so it is important
131 // that contexts be visited from the inside out in order to get
132 // the effective DCs right.
133 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
David Blaikie82e95a32014-11-19 07:49:47 +0000134 if (!visited.insert(DC).second)
John McCallf6c8a4e2009-11-10 07:01:13 +0000135 return;
136
137 addUsingDirectives(DC, EffectiveDC);
138 }
139
140 // Visits a using directive and collects all of its using
141 // directives recursively. Treats all using directives as if they
142 // were declared in the effective DC.
143 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
144 DeclContext *NS = UD->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +0000145 if (!visited.insert(NS).second)
John McCallf6c8a4e2009-11-10 07:01:13 +0000146 return;
147
148 addUsingDirective(UD, EffectiveDC);
149 addUsingDirectives(NS, EffectiveDC);
150 }
151
152 // Adds all the using directives in a context (and those nominated
153 // by its using directives, transitively) as if they appeared in
154 // the given effective context.
155 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000156 SmallVector<DeclContext*,4> queue;
John McCallf6c8a4e2009-11-10 07:01:13 +0000157 while (true) {
Aaron Ballman804a7fb2014-03-17 17:14:12 +0000158 for (auto UD : DC->using_directives()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000159 DeclContext *NS = UD->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +0000160 if (visited.insert(NS).second) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000161 addUsingDirective(UD, EffectiveDC);
162 queue.push_back(NS);
163 }
164 }
165
166 if (queue.empty())
167 return;
168
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000169 DC = queue.pop_back_val();
John McCallf6c8a4e2009-11-10 07:01:13 +0000170 }
171 }
172
173 // Add a using directive as if it had been declared in the given
174 // context. This helps implement C++ [namespace.udir]p3:
175 // The using-directive is transitive: if a scope contains a
176 // using-directive that nominates a second namespace that itself
177 // contains using-directives, the effect is as if the
178 // using-directives from the second namespace also appeared in
179 // the first.
180 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
181 // Find the common ancestor between the effective context and
182 // the nominated namespace.
183 DeclContext *Common = UD->getNominatedNamespace();
184 while (!Common->Encloses(EffectiveDC))
185 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000186 Common = Common->getPrimaryContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000187
John McCallf6c8a4e2009-11-10 07:01:13 +0000188 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
189 }
190
191 void done() {
192 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
193 }
194
John McCallf6c8a4e2009-11-10 07:01:13 +0000195 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000196
John McCallf6c8a4e2009-11-10 07:01:13 +0000197 const_iterator begin() const { return list.begin(); }
198 const_iterator end() const { return list.end(); }
199
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000200 llvm::iterator_range<const_iterator>
John McCallf6c8a4e2009-11-10 07:01:13 +0000201 getNamespacesFor(DeclContext *DC) const {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000202 return llvm::make_range(std::equal_range(begin(), end(),
203 DC->getPrimaryContext(),
204 UnqualUsingEntry::Comparator()));
John McCallf6c8a4e2009-11-10 07:01:13 +0000205 }
206 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000207}
208
Douglas Gregor889ceb72009-02-03 19:21:40 +0000209// Retrieve the set of identifier namespaces that correspond to a
210// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000211static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
212 bool CPlusPlus,
213 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000214 unsigned IDNS = 0;
215 switch (NameKind) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +0000216 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000217 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000218 case Sema::LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +0000219 case Sema::LookupLocalFriendName:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000220 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000221 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000222 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000223 if (Redeclaration)
224 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCallea305ed2009-12-18 10:40:03 +0000225 }
Richard Smith541b38b2013-09-20 01:15:31 +0000226 if (Redeclaration)
227 IDNS |= Decl::IDNS_LocalExtern;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000228 break;
229
John McCallb9467b62010-04-24 01:30:58 +0000230 case Sema::LookupOperatorName:
231 // Operator lookup is its own crazy thing; it is not the same
232 // as (e.g.) looking up an operator name for redeclaration.
233 assert(!Redeclaration && "cannot do redeclaration operator lookup");
234 IDNS = Decl::IDNS_NonMemberOperator;
235 break;
236
Douglas Gregor889ceb72009-02-03 19:21:40 +0000237 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000238 if (CPlusPlus) {
239 IDNS = Decl::IDNS_Type;
240
241 // When looking for a redeclaration of a tag name, we add:
242 // 1) TagFriend to find undeclared friend decls
243 // 2) Namespace because they can't "overload" with tag decls.
244 // 3) Tag because it includes class templates, which can't
245 // "overload" with tag decls.
246 if (Redeclaration)
247 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
248 } else {
249 IDNS = Decl::IDNS_Tag;
250 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000251 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000252
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000253 case Sema::LookupLabel:
254 IDNS = Decl::IDNS_Label;
255 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000256
Douglas Gregor889ceb72009-02-03 19:21:40 +0000257 case Sema::LookupMemberName:
258 IDNS = Decl::IDNS_Member;
259 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000260 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000261 break;
262
263 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000264 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
265 break;
266
Douglas Gregor889ceb72009-02-03 19:21:40 +0000267 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000268 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000269 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000270
John McCall84d87672009-12-10 09:41:52 +0000271 case Sema::LookupUsingDeclName:
Richard Smith83e78f52014-04-11 01:03:38 +0000272 assert(Redeclaration && "should only be used for redecl lookup");
273 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |
274 Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend |
275 Decl::IDNS_LocalExtern;
John McCall84d87672009-12-10 09:41:52 +0000276 break;
277
Douglas Gregor79947a22009-04-24 00:11:27 +0000278 case Sema::LookupObjCProtocolName:
279 IDNS = Decl::IDNS_ObjCProtocol;
280 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000281
Douglas Gregor39982192010-08-15 06:18:01 +0000282 case Sema::LookupAnyName:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000283 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor39982192010-08-15 06:18:01 +0000284 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
285 | Decl::IDNS_Type;
286 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000287 }
288 return IDNS;
289}
290
John McCallea305ed2009-12-18 10:40:03 +0000291void LookupResult::configure() {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000292 IDNS = getIDNS(LookupKind, getSema().getLangOpts().CPlusPlus,
John McCallea305ed2009-12-18 10:40:03 +0000293 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000294
Richard Smithbdd14642014-02-04 01:14:30 +0000295 // If we're looking for one of the allocation or deallocation
296 // operators, make sure that the implicitly-declared new and delete
297 // operators can be found.
298 switch (NameInfo.getName().getCXXOverloadedOperator()) {
299 case OO_New:
300 case OO_Delete:
301 case OO_Array_New:
302 case OO_Array_Delete:
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000303 getSema().DeclareGlobalNewDelete();
Richard Smithbdd14642014-02-04 01:14:30 +0000304 break;
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000305
Richard Smithbdd14642014-02-04 01:14:30 +0000306 default:
307 break;
308 }
Douglas Gregor15197662013-04-03 23:06:26 +0000309
Richard Smithbdd14642014-02-04 01:14:30 +0000310 // Compiler builtins are always visible, regardless of where they end
311 // up being declared.
312 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
313 if (unsigned BuiltinID = Id->getBuiltinID()) {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000314 if (!getSema().Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
Richard Smithbdd14642014-02-04 01:14:30 +0000315 AllowHidden = true;
Douglas Gregor15197662013-04-03 23:06:26 +0000316 }
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000317 }
John McCallea305ed2009-12-18 10:40:03 +0000318}
319
Alp Tokerc1086762013-12-07 13:51:35 +0000320bool LookupResult::sanity() const {
Richard Smithf97ad222014-04-01 18:33:50 +0000321 // This function is never called by NDEBUG builds.
John McCall19c1bfd2010-08-25 05:32:35 +0000322 assert(ResultKind != NotFound || Decls.size() == 0);
323 assert(ResultKind != Found || Decls.size() == 1);
324 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
325 (Decls.size() == 1 &&
326 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
327 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
328 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000329 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
330 Ambiguity == AmbiguousBaseSubobjectTypes)));
Craig Topperc3ec1492014-05-26 06:22:03 +0000331 assert((Paths != nullptr) == (ResultKind == Ambiguous &&
332 (Ambiguity == AmbiguousBaseSubobjectTypes ||
333 Ambiguity == AmbiguousBaseSubobjects)));
Alp Tokerc1086762013-12-07 13:51:35 +0000334 return true;
John McCall19c1bfd2010-08-25 05:32:35 +0000335}
John McCall19c1bfd2010-08-25 05:32:35 +0000336
John McCall9f3059a2009-10-09 21:13:30 +0000337// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000338void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000339 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000340}
341
Richard Smith3876cc82013-10-30 01:02:04 +0000342/// Get a representative context for a declaration such that two declarations
343/// will have the same context if they were found within the same scope.
Benjamin Kramerfc58b042013-11-01 11:50:55 +0000344static DeclContext *getContextForScopeMatching(Decl *D) {
Richard Smith3876cc82013-10-30 01:02:04 +0000345 // For function-local declarations, use that function as the context. This
346 // doesn't account for scopes within the function; the caller must deal with
347 // those.
348 DeclContext *DC = D->getLexicalDeclContext();
349 if (DC->isFunctionOrMethod())
350 return DC;
351
352 // Otherwise, look at the semantic context of the declaration. The
353 // declaration must have been found there.
354 return D->getDeclContext()->getRedeclContext();
355}
356
John McCall283b9012009-11-22 00:44:51 +0000357/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000358void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000359 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000360
John McCall9f3059a2009-10-09 21:13:30 +0000361 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000362 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000363 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000364 return;
365 }
366
John McCall283b9012009-11-22 00:44:51 +0000367 // If there's a single decl, we need to examine it to decide what
368 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000369 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000370 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
371 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000372 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000373 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000374 ResultKind = FoundUnresolvedValue;
375 return;
376 }
John McCall9f3059a2009-10-09 21:13:30 +0000377
John McCall6538c932009-10-10 05:48:19 +0000378 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000379 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000380
John McCall9f3059a2009-10-09 21:13:30 +0000381 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor13e65872010-08-11 14:45:53 +0000382 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000383
John McCall9f3059a2009-10-09 21:13:30 +0000384 bool Ambiguous = false;
385 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000386 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000387
388 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000389
John McCall9f3059a2009-10-09 21:13:30 +0000390 unsigned I = 0;
391 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000392 NamedDecl *D = Decls[I]->getUnderlyingDecl();
393 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000394
Argyrios Kyrtzidis1fcd7fd2013-02-22 06:58:37 +0000395 // Ignore an invalid declaration unless it's the only one left.
396 if (D->isInvalidDecl() && I < N-1) {
397 Decls[I] = Decls[--N];
398 continue;
399 }
400
Douglas Gregor13e65872010-08-11 14:45:53 +0000401 // Redeclarations of types via typedef can occur both within a scope
402 // and, through using declarations and directives, across scopes. There is
403 // no ambiguity if they all refer to the same type, so unique based on the
404 // canonical type.
405 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
406 if (!TD->getDeclContext()->isRecord()) {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000407 QualType T = getSema().Context.getTypeDeclType(TD);
David Blaikie82e95a32014-11-19 07:49:47 +0000408 if (!UniqueTypes.insert(getSema().Context.getCanonicalType(T)).second) {
Douglas Gregor13e65872010-08-11 14:45:53 +0000409 // The type is not unique; pull something off the back and continue
410 // at this index.
411 Decls[I] = Decls[--N];
412 continue;
413 }
414 }
415 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000416
David Blaikie82e95a32014-11-19 07:49:47 +0000417 if (!Unique.insert(D).second) {
John McCall9f3059a2009-10-09 21:13:30 +0000418 // If it's not unique, pull something off the back (and
419 // continue at this index).
Richard Smithe8292b12015-02-10 03:28:10 +0000420 // FIXME: This is wrong. We need to take the more recent declaration in
Richard Smithfe620d22015-03-05 23:24:12 +0000421 // order to get the right type, default arguments, etc. We also need to
422 // prefer visible declarations to hidden ones (for redeclaration lookup
423 // in modules builds).
John McCall9f3059a2009-10-09 21:13:30 +0000424 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000425 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000426 }
427
Douglas Gregor13e65872010-08-11 14:45:53 +0000428 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000429
Douglas Gregor13e65872010-08-11 14:45:53 +0000430 if (isa<UnresolvedUsingValueDecl>(D)) {
431 HasUnresolved = true;
432 } else if (isa<TagDecl>(D)) {
433 if (HasTag)
434 Ambiguous = true;
435 UniqueTagIndex = I;
436 HasTag = true;
437 } else if (isa<FunctionTemplateDecl>(D)) {
438 HasFunction = true;
439 HasFunctionTemplate = true;
440 } else if (isa<FunctionDecl>(D)) {
441 HasFunction = true;
442 } else {
443 if (HasNonFunction)
444 Ambiguous = true;
445 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000446 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000447 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000448 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000449
John McCall9f3059a2009-10-09 21:13:30 +0000450 // C++ [basic.scope.hiding]p2:
451 // A class name or enumeration name can be hidden by the name of
452 // an object, function, or enumerator declared in the same
453 // scope. If a class or enumeration name and an object, function,
454 // or enumerator are declared in the same scope (in any order)
455 // with the same name, the class or enumeration name is hidden
456 // wherever the object, function, or enumerator name is visible.
457 // But it's still an error if there are distinct tag types found,
458 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000459 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000460 (HasFunction || HasNonFunction || HasUnresolved)) {
Richard Smith3876cc82013-10-30 01:02:04 +0000461 if (getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
462 getContextForScopeMatching(Decls[UniqueTagIndex ? 0 : N - 1])))
Douglas Gregore63d0872010-10-23 16:06:17 +0000463 Decls[UniqueTagIndex] = Decls[--N];
464 else
465 Ambiguous = true;
466 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000467
John McCall9f3059a2009-10-09 21:13:30 +0000468 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000469
John McCall80053822009-12-03 00:58:24 +0000470 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000471 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000472
John McCall9f3059a2009-10-09 21:13:30 +0000473 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000474 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000475 else if (HasUnresolved)
476 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000477 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000478 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000479 else
John McCall27b18f82009-11-17 02:14:36 +0000480 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000481}
482
John McCall5cebab12009-11-18 07:57:50 +0000483void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000484 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000485 for (I = P.begin(), E = P.end(); I != E; ++I)
David Blaikieff7d47a2012-12-19 00:45:41 +0000486 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
487 DE = I->Decls.end(); DI != DE; ++DI)
John McCall9f3059a2009-10-09 21:13:30 +0000488 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000489}
490
John McCall5cebab12009-11-18 07:57:50 +0000491void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000492 Paths = new CXXBasePaths;
493 Paths->swap(P);
494 addDeclsFromBasePaths(*Paths);
495 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000496 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000497}
498
John McCall5cebab12009-11-18 07:57:50 +0000499void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000500 Paths = new CXXBasePaths;
501 Paths->swap(P);
502 addDeclsFromBasePaths(*Paths);
503 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000504 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000505}
506
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000507void LookupResult::print(raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000508 Out << Decls.size() << " result(s)";
509 if (isAmbiguous()) Out << ", ambiguous";
510 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000511
John McCall9f3059a2009-10-09 21:13:30 +0000512 for (iterator I = begin(), E = end(); I != E; ++I) {
513 Out << "\n";
514 (*I)->print(Out, 2);
515 }
516}
517
Douglas Gregord3a59182010-02-12 05:48:04 +0000518/// \brief Lookup a builtin function, when name lookup would otherwise
519/// fail.
520static bool LookupBuiltin(Sema &S, LookupResult &R) {
521 Sema::LookupNameKind NameKind = R.getLookupKind();
522
523 // If we didn't find a use of this identifier, and if the identifier
524 // corresponds to a compiler builtin, create the decl object for the builtin
525 // now, injecting it into translation unit scope, and return it.
526 if (NameKind == Sema::LookupOrdinaryName ||
527 NameKind == Sema::LookupRedeclarationWithLinkage) {
528 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
529 if (II) {
Nico Webere1687c52013-06-20 21:44:55 +0000530 if (S.getLangOpts().CPlusPlus11 && S.getLangOpts().GNUMode &&
531 II == S.getFloat128Identifier()) {
532 // libstdc++4.7's type_traits expects type __float128 to exist, so
533 // insert a dummy type to make that header build in gnu++11 mode.
534 R.addDecl(S.getASTContext().getFloat128StubType());
535 return true;
536 }
537
Douglas Gregord3a59182010-02-12 05:48:04 +0000538 // If this is a builtin on this (or all) targets, create the decl.
539 if (unsigned BuiltinID = II->getBuiltinID()) {
540 // In C++, we don't have any predefined library functions like
541 // 'malloc'. Instead, we'll just error.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000542 if (S.getLangOpts().CPlusPlus &&
Douglas Gregord3a59182010-02-12 05:48:04 +0000543 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
544 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000545
546 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
547 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000548 R.isForRedeclaration(),
549 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000550 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000551 return true;
552 }
Douglas Gregord3a59182010-02-12 05:48:04 +0000553 }
554 }
555 }
556
557 return false;
558}
559
Douglas Gregor7454c562010-07-02 20:37:36 +0000560/// \brief Determine whether we can declare a special member function within
561/// the class at this point.
Richard Smith7d125a12012-11-27 21:20:31 +0000562static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +0000563 // We need to have a definition for the class.
564 if (!Class->getDefinition() || Class->isDependentContext())
565 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000566
Douglas Gregor7454c562010-07-02 20:37:36 +0000567 // We can't be in the middle of defining the class.
Richard Smith7d125a12012-11-27 21:20:31 +0000568 return !Class->isBeingDefined();
Douglas Gregor7454c562010-07-02 20:37:36 +0000569}
570
571void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smith7d125a12012-11-27 21:20:31 +0000572 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregora6d69502010-07-02 23:41:54 +0000573 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000574
575 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000576 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000577 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000578
Douglas Gregora6d69502010-07-02 23:41:54 +0000579 // If the copy constructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000580 if (Class->needsImplicitCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +0000581 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000582
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000583 // If the copy assignment operator has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000584 if (Class->needsImplicitCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000585 DeclareImplicitCopyAssignment(Class);
586
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000587 if (getLangOpts().CPlusPlus11) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000588 // If the move constructor has not yet been declared, do so now.
589 if (Class->needsImplicitMoveConstructor())
590 DeclareImplicitMoveConstructor(Class); // might not actually do it
591
592 // If the move assignment operator has not yet been declared, do so now.
593 if (Class->needsImplicitMoveAssignment())
594 DeclareImplicitMoveAssignment(Class); // might not actually do it
595 }
596
Douglas Gregor7454c562010-07-02 20:37:36 +0000597 // If the destructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000598 if (Class->needsImplicitDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000599 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000600}
601
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000602/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000603/// special member function.
604static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
605 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000606 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000607 case DeclarationName::CXXDestructorName:
608 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000609
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000610 case DeclarationName::CXXOperatorName:
611 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000612
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000613 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000614 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000615 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000616
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000617 return false;
618}
619
620/// \brief If there are any implicit member functions with the given name
621/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000622static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000623 DeclarationName Name,
624 const DeclContext *DC) {
625 if (!DC)
626 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000627
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000628 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000629 case DeclarationName::CXXConstructorName:
630 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith7d125a12012-11-27 21:20:31 +0000631 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000632 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000633 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000634 S.DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +0000635 if (Record->needsImplicitCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000636 S.DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000637 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000638 Record->needsImplicitMoveConstructor())
639 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000640 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000641 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000642
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000643 case DeclarationName::CXXDestructorName:
644 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith2be35f52012-12-01 02:35:44 +0000645 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smith7d125a12012-11-27 21:20:31 +0000646 CanDeclareSpecialMemberFunction(Record))
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000647 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000648 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000649
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000650 case DeclarationName::CXXOperatorName:
651 if (Name.getCXXOverloadedOperator() != OO_Equal)
652 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000653
Sebastian Redl22653ba2011-08-30 19:58:05 +0000654 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smith7d125a12012-11-27 21:20:31 +0000655 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000656 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smith2be35f52012-12-01 02:35:44 +0000657 if (Record->needsImplicitCopyAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000658 S.DeclareImplicitCopyAssignment(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000659 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000660 Record->needsImplicitMoveAssignment())
661 S.DeclareImplicitMoveAssignment(Class);
662 }
663 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000664 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000665
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000666 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000667 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000668 }
669}
Douglas Gregor7454c562010-07-02 20:37:36 +0000670
John McCall9f3059a2009-10-09 21:13:30 +0000671// Adds all qualifying matches for a name within a decl context to the
672// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000673static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000674 bool Found = false;
675
Douglas Gregor7454c562010-07-02 20:37:36 +0000676 // Lazily declare C++ special member functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000677 if (S.getLangOpts().CPlusPlus)
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000678 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000679
Douglas Gregor7454c562010-07-02 20:37:36 +0000680 // Perform lookup into this declaration context.
Richard Smithcf4bdde2015-02-21 02:45:19 +0000681 DeclContext::lookup_result DR = DC->lookup(R.getLookupName());
682 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E;
David Blaikieff7d47a2012-12-19 00:45:41 +0000683 ++I) {
John McCall401982f2010-01-20 21:53:11 +0000684 NamedDecl *D = *I;
Douglas Gregor4a814562011-12-14 16:03:29 +0000685 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000686 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000687 Found = true;
688 }
689 }
John McCall9f3059a2009-10-09 21:13:30 +0000690
Douglas Gregord3a59182010-02-12 05:48:04 +0000691 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
692 return true;
693
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000694 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000695 != DeclarationName::CXXConversionFunctionName ||
696 R.getLookupName().getCXXNameType()->isDependentType() ||
697 !isa<CXXRecordDecl>(DC))
698 return Found;
699
700 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000701 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000702 // name lookup. Instead, any conversion function templates visible in the
703 // context of the use are considered. [...]
704 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000705 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000706 return Found;
707
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +0000708 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
709 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruth3a693b72010-01-31 11:44:02 +0000710 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
711 if (!ConvTemplate)
712 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000713
Chandler Carruth3a693b72010-01-31 11:44:02 +0000714 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000715 // add the conversion function template. When we deduce template
716 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000717 // type of the new declaration with the type of the function template.
718 if (R.isForRedeclaration()) {
719 R.addDecl(ConvTemplate);
720 Found = true;
721 continue;
722 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000723
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000724 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000725 // [...] For each such operator, if argument deduction succeeds
726 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000727 // name lookup.
728 //
729 // When referencing a conversion function for any purpose other than
730 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000731 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000732 // specialization into the result set. We do this to avoid forcing all
733 // callers to perform special deduction for conversion functions.
Craig Toppere6706e42012-09-19 02:26:47 +0000734 TemplateDeductionInfo Info(R.getNameLoc());
Craig Topperc3ec1492014-05-26 06:22:03 +0000735 FunctionDecl *Specialization = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000736
737 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000738 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
739 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000740
Chandler Carruth3a693b72010-01-31 11:44:02 +0000741 // Compute the type of the function that we would expect the conversion
742 // function to have, if it were to match the name given.
743 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000744 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
Reid Kleckner78af0702013-08-27 23:08:25 +0000745 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
Richard Smith8acb4282014-07-31 21:57:55 +0000746 EPI.ExceptionSpec = EST_None;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000747 QualType ExpectedType
748 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000749 None, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000750
Chandler Carruth3a693b72010-01-31 11:44:02 +0000751 // Perform template argument deduction against the type that we would
752 // expect the function to have.
Craig Topperc3ec1492014-05-26 06:22:03 +0000753 if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
Chandler Carruth3a693b72010-01-31 11:44:02 +0000754 Specialization, Info)
755 == Sema::TDK_Success) {
756 R.addDecl(Specialization);
757 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000758 }
759 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000760
John McCall9f3059a2009-10-09 21:13:30 +0000761 return Found;
762}
763
John McCallf6c8a4e2009-11-10 07:01:13 +0000764// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000765static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000766CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000767 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000768
769 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
770
John McCallf6c8a4e2009-11-10 07:01:13 +0000771 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000772 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000773
John McCallf6c8a4e2009-11-10 07:01:13 +0000774 // Perform direct name lookup into the namespaces nominated by the
775 // using directives whose common ancestor is this namespace.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000776 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
777 if (LookupDirect(S, R, UUE.getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000778 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000779
780 R.resolveKind();
781
782 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000783}
784
785static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000786 if (DeclContext *Ctx = S->getEntity())
Douglas Gregor700792c2009-02-05 19:25:20 +0000787 return Ctx->isFileContext();
788 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000789}
Douglas Gregored8f2882009-01-30 01:04:22 +0000790
Douglas Gregor66230062010-03-15 14:33:29 +0000791// Find the next outer declaration context from this scope. This
792// routine actually returns the semantic outer context, which may
793// differ from the lexical context (encoded directly in the Scope
794// stack) when we are parsing a member of a class template. In this
795// case, the second element of the pair will be true, to indicate that
796// name lookup should continue searching in this semantic context when
797// it leaves the current template parameter scope.
798static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000799 DeclContext *DC = S->getEntity();
Craig Topperc3ec1492014-05-26 06:22:03 +0000800 DeclContext *Lexical = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000801 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000802 OuterS = OuterS->getParent()) {
803 if (OuterS->getEntity()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000804 Lexical = OuterS->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +0000805 break;
806 }
807 }
808
809 // C++ [temp.local]p8:
810 // In the definition of a member of a class template that appears
811 // outside of the namespace containing the class template
812 // definition, the name of a template-parameter hides the name of
813 // a member of this namespace.
814 //
815 // Example:
816 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000817 // namespace N {
818 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000819 //
820 // template<class T> class B {
821 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000822 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000823 // }
824 //
825 // template<class C> void N::B<C>::f(C) {
826 // C b; // C is the template parameter, not N::C
827 // }
828 //
829 // In this example, the lexical context we return is the
830 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000831 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000832 !S->getParent()->isTemplateParamScope())
833 return std::make_pair(Lexical, false);
834
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000835 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000836 // For the example, this is the scope for the template parameters of
837 // template<class C>.
838 Scope *OutermostTemplateScope = S->getParent();
839 while (OutermostTemplateScope->getParent() &&
840 OutermostTemplateScope->getParent()->isTemplateParamScope())
841 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000842
Douglas Gregor66230062010-03-15 14:33:29 +0000843 // Find the namespace context in which the original scope occurs. In
844 // the example, this is namespace N.
845 DeclContext *Semantic = DC;
846 while (!Semantic->isFileContext())
847 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000848
Douglas Gregor66230062010-03-15 14:33:29 +0000849 // Find the declaration context just outside of the template
850 // parameter scope. This is the context in which the template is
851 // being lexically declaration (a namespace context). In the
852 // example, this is the global scope.
853 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
854 Lexical->Encloses(Semantic))
855 return std::make_pair(Semantic, true);
856
857 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000858}
859
Richard Smith541b38b2013-09-20 01:15:31 +0000860namespace {
861/// An RAII object to specify that we want to find block scope extern
862/// declarations.
863struct FindLocalExternScope {
864 FindLocalExternScope(LookupResult &R)
865 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
866 Decl::IDNS_LocalExtern) {
867 R.setFindLocalExtern(R.getIdentifierNamespace() & Decl::IDNS_Ordinary);
868 }
869 void restore() {
870 R.setFindLocalExtern(OldFindLocalExtern);
871 }
872 ~FindLocalExternScope() {
873 restore();
874 }
875 LookupResult &R;
876 bool OldFindLocalExtern;
877};
878}
879
John McCall27b18f82009-11-17 02:14:36 +0000880bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000881 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000882
883 DeclarationName Name = R.getLookupName();
Richard Smith1c34fb72013-08-13 18:18:50 +0000884 Sema::LookupNameKind NameKind = R.getLookupKind();
John McCall27b18f82009-11-17 02:14:36 +0000885
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000886 // If this is the name of an implicitly-declared special member function,
887 // go through the scope stack to implicitly declare
888 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
889 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +0000890 if (DeclContext *DC = PreS->getEntity())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000891 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
892 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000893
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000894 // Implicitly declare member functions with the name we're looking for, if in
895 // fact we are in a scope where it matters.
896
Douglas Gregor889ceb72009-02-03 19:21:40 +0000897 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000898 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000899 I = IdResolver.begin(Name),
900 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000901
Douglas Gregor889ceb72009-02-03 19:21:40 +0000902 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000903 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000904 // ...During unqualified name lookup (3.4.1), the names appear as if
905 // they were declared in the nearest enclosing namespace which contains
906 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000907 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000908 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000909 //
910 // For example:
911 // namespace A { int i; }
912 // void foo() {
913 // int i;
914 // {
915 // using namespace A;
916 // ++i; // finds local 'i', A::i appears at global scope
917 // }
918 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000919 //
Douglas Gregorcc9406c2013-04-08 23:11:25 +0000920 UnqualUsingDirectiveSet UDirs;
921 bool VisitedUsingDirectives = false;
Richard Smith1c34fb72013-08-13 18:18:50 +0000922 bool LeftStartingScope = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000923 DeclContext *OutsideOfTemplateParamDC = nullptr;
Richard Smith541b38b2013-09-20 01:15:31 +0000924
925 // When performing a scope lookup, we want to find local extern decls.
926 FindLocalExternScope FindLocals(R);
927
Douglas Gregor700792c2009-02-05 19:25:20 +0000928 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000929 DeclContext *Ctx = S->getEntity();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000930
Douglas Gregor889ceb72009-02-03 19:21:40 +0000931 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000932 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000933 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000934 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Richard Smith1c34fb72013-08-13 18:18:50 +0000935 if (NameKind == LookupRedeclarationWithLinkage) {
936 // Determine whether this (or a previous) declaration is
937 // out-of-scope.
938 if (!LeftStartingScope && !Initial->isDeclScope(*I))
939 LeftStartingScope = true;
940
941 // If we found something outside of our starting scope that
Richard Smith9a00bbf2013-10-16 21:12:00 +0000942 // does not have linkage, skip it. If it's a template parameter,
943 // we still find it, so we can diagnose the invalid redeclaration.
944 if (LeftStartingScope && !((*I)->hasLinkage()) &&
945 !(*I)->isTemplateParameter()) {
Richard Smith1c34fb72013-08-13 18:18:50 +0000946 R.setShadowed();
947 continue;
948 }
949 }
950
John McCall9f3059a2009-10-09 21:13:30 +0000951 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +0000952 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000953 }
954 }
John McCall9f3059a2009-10-09 21:13:30 +0000955 if (Found) {
956 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000957 if (S->isClassScope())
958 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
959 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000960 return true;
961 }
962
Richard Smith1c34fb72013-08-13 18:18:50 +0000963 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
Richard Smith114394f2013-08-09 04:35:01 +0000964 // C++11 [class.friend]p11:
965 // If a friend declaration appears in a local class and the name
966 // specified is an unqualified name, a prior declaration is
967 // looked up without considering scopes that are outside the
968 // innermost enclosing non-class scope.
969 return false;
970 }
971
Douglas Gregor66230062010-03-15 14:33:29 +0000972 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
973 S->getParent() && !S->getParent()->isTemplateParamScope()) {
974 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000975 // found nothing, so look into the contexts between the
Douglas Gregor66230062010-03-15 14:33:29 +0000976 // lexical and semantic declaration contexts returned by
977 // findOuterContext(). This implements the name lookup behavior
978 // of C++ [temp.local]p8.
979 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +0000980 OutsideOfTemplateParamDC = nullptr;
Douglas Gregor66230062010-03-15 14:33:29 +0000981 }
982
983 if (Ctx) {
984 DeclContext *OuterCtx;
985 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000986 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregor66230062010-03-15 14:33:29 +0000987 if (SearchAfterTemplateScope)
988 OutsideOfTemplateParamDC = OuterCtx;
989
Douglas Gregorea166062010-03-15 15:26:48 +0000990 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000991 // We do not directly look into transparent contexts, since
992 // those entities will be found in the nearest enclosing
993 // non-transparent context.
994 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000995 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000996
997 // We do not look directly into function or method contexts,
998 // since all of the local variables and parameters of the
999 // function/method are present within the Scope.
1000 if (Ctx->isFunctionOrMethod()) {
1001 // If we have an Objective-C instance method, look for ivars
1002 // in the corresponding interface.
1003 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
1004 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1005 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1006 ObjCInterfaceDecl *ClassDeclared;
1007 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001008 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +00001009 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001010 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1011 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +00001012 R.resolveKind();
1013 return true;
1014 }
1015 }
1016 }
1017 }
1018
1019 continue;
1020 }
1021
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001022 // If this is a file context, we need to perform unqualified name
1023 // lookup considering using directives.
1024 if (Ctx->isFileContext()) {
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001025 // If we haven't handled using directives yet, do so now.
1026 if (!VisitedUsingDirectives) {
1027 // Add using directives from this context up to the top level.
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001028 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1029 if (UCtx->isTransparentContext())
1030 continue;
1031
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001032 UDirs.visit(UCtx, UCtx);
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001033 }
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001034
1035 // Find the innermost file scope, so we can add using directives
1036 // from local scopes.
1037 Scope *InnermostFileScope = S;
1038 while (InnermostFileScope &&
1039 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1040 InnermostFileScope = InnermostFileScope->getParent();
1041 UDirs.visitScopeChain(Initial, InnermostFileScope);
1042
1043 UDirs.done();
1044
1045 VisitedUsingDirectives = true;
1046 }
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001047
1048 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1049 R.resolveKind();
1050 return true;
1051 }
1052
1053 continue;
1054 }
1055
Douglas Gregor7f737c02009-09-10 16:57:35 +00001056 // Perform qualified name lookup into this context.
1057 // FIXME: In some cases, we know that every name that could be found by
1058 // this qualified name lookup will also be on the identifier chain. For
1059 // example, inside a class without any base classes, we never need to
1060 // perform qualified lookup because all of the members are on top of the
1061 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001062 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +00001063 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +00001064 }
Douglas Gregor700792c2009-02-05 19:25:20 +00001065 }
Douglas Gregored8f2882009-01-30 01:04:22 +00001066 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001067
John McCallf6c8a4e2009-11-10 07:01:13 +00001068 // Stop if we ran out of scopes.
1069 // FIXME: This really, really shouldn't be happening.
1070 if (!S) return false;
1071
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001072 // If we are looking for members, no need to look into global/namespace scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00001073 if (NameKind == LookupMemberName)
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001074 return false;
1075
Douglas Gregor700792c2009-02-05 19:25:20 +00001076 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +00001077 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +00001078 //
Mike Stump87c57ac2009-05-16 07:39:55 +00001079 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1080 // don't build it for each lookup!
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001081 if (!VisitedUsingDirectives) {
1082 UDirs.visitScopeChain(Initial, S);
1083 UDirs.done();
1084 }
Richard Smith541b38b2013-09-20 01:15:31 +00001085
1086 // If we're not performing redeclaration lookup, do not look for local
1087 // extern declarations outside of a function scope.
1088 if (!R.isForRedeclaration())
1089 FindLocals.restore();
1090
Douglas Gregor700792c2009-02-05 19:25:20 +00001091 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +00001092 // Unqualified name lookup in C++ requires looking into scopes
1093 // that aren't strictly lexical, and therefore we walk through the
1094 // context as well as walking through the scopes.
1095 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001096 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +00001097 bool Found = false;
John McCall48871652010-08-21 09:40:31 +00001098 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001099 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001100 // We found something. Look for anything else in our scope
1101 // with this same name and in an acceptable identifier
1102 // namespace, so that we can construct an overload set if we
1103 // need to.
John McCall9f3059a2009-10-09 21:13:30 +00001104 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +00001105 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001106 }
1107 }
1108
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001109 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +00001110 R.resolveKind();
1111 return true;
1112 }
1113
Ted Kremenekc37877d2013-10-08 17:08:03 +00001114 DeclContext *Ctx = S->getEntity();
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001115 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1116 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1117 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001118 // found nothing, so look into the contexts between the
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001119 // lexical and semantic declaration contexts returned by
1120 // findOuterContext(). This implements the name lookup behavior
1121 // of C++ [temp.local]p8.
1122 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +00001123 OutsideOfTemplateParamDC = nullptr;
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001124 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001125
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001126 if (Ctx) {
1127 DeclContext *OuterCtx;
1128 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001129 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001130 if (SearchAfterTemplateScope)
1131 OutsideOfTemplateParamDC = OuterCtx;
1132
1133 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1134 // We do not directly look into transparent contexts, since
1135 // those entities will be found in the nearest enclosing
1136 // non-transparent context.
1137 if (Ctx->isTransparentContext())
1138 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001139
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001140 // If we have a context, and it's not a context stashed in the
1141 // template parameter scope for an out-of-line definition, also
1142 // look into that context.
1143 if (!(Found && S && S->isTemplateParamScope())) {
1144 assert(Ctx->isFileContext() &&
1145 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001146
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001147 // Look into context considering using-directives.
1148 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1149 Found = true;
1150 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001151
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001152 if (Found) {
1153 R.resolveKind();
1154 return true;
1155 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001156
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001157 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1158 return false;
1159 }
1160 }
1161
Douglas Gregor3ce74932010-02-05 07:07:10 +00001162 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001163 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001164 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001165
John McCall9f3059a2009-10-09 21:13:30 +00001166 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001167}
1168
Richard Smith0e5d7b82013-07-25 23:08:39 +00001169/// \brief Find the declaration that a class temploid member specialization was
1170/// instantiated from, or the member itself if it is an explicit specialization.
1171static Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) {
1172 return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom();
1173}
1174
Richard Smith42413142015-05-15 20:05:43 +00001175Module *Sema::getOwningModule(Decl *Entity) {
1176 // If it's imported, grab its owning module.
1177 Module *M = Entity->getImportedOwningModule();
1178 if (M || !isa<NamedDecl>(Entity) || !cast<NamedDecl>(Entity)->isHidden())
1179 return M;
1180 assert(!Entity->isFromASTFile() &&
1181 "hidden entity from AST file has no owning module");
1182
Richard Smith87bb5692015-06-09 00:35:49 +00001183 if (!getLangOpts().ModulesLocalVisibility) {
1184 // If we're not tracking visibility locally, the only way a declaration
1185 // can be hidden and local is if it's hidden because it's parent is (for
1186 // instance, maybe this is a lazily-declared special member of an imported
1187 // class).
1188 auto *Parent = cast<NamedDecl>(Entity->getDeclContext());
1189 assert(Parent->isHidden() && "unexpectedly hidden decl");
1190 return getOwningModule(Parent);
1191 }
1192
Richard Smith42413142015-05-15 20:05:43 +00001193 // It's local and hidden; grab or compute its owning module.
1194 M = Entity->getLocalOwningModule();
1195 if (M)
1196 return M;
1197
1198 if (auto *Containing =
1199 PP.getModuleContainingLocation(Entity->getLocation())) {
1200 M = Containing;
1201 } else if (Entity->isInvalidDecl() || Entity->getLocation().isInvalid()) {
1202 // Don't bother tracking visibility for invalid declarations with broken
1203 // locations.
1204 cast<NamedDecl>(Entity)->setHidden(false);
1205 } else {
1206 // We need to assign a module to an entity that exists outside of any
1207 // module, so that we can hide it from modules that we textually enter.
1208 // Invent a fake module for all such entities.
1209 if (!CachedFakeTopLevelModule) {
1210 CachedFakeTopLevelModule =
1211 PP.getHeaderSearchInfo().getModuleMap().findOrCreateModule(
1212 "<top-level>", nullptr, false, false).first;
1213
1214 auto &SrcMgr = PP.getSourceManager();
1215 SourceLocation StartLoc =
1216 SrcMgr.getLocForStartOfFile(SrcMgr.getMainFileID());
1217 auto &TopLevel =
1218 VisibleModulesStack.empty() ? VisibleModules : VisibleModulesStack[0];
1219 TopLevel.setVisible(CachedFakeTopLevelModule, StartLoc);
1220 }
1221
1222 M = CachedFakeTopLevelModule;
1223 }
1224
1225 if (M)
1226 Entity->setLocalOwningModule(M);
1227 return M;
1228}
1229
Richard Smithd9ba2242015-05-07 03:54:19 +00001230void Sema::makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc) {
Richard Smithe7bd6de2015-06-10 20:30:23 +00001231 // FIXME: If ND is a template declaration, make the template parameters
1232 // visible too. They're not (necessarily) within its DeclContext.
Richard Smith87bb5692015-06-09 00:35:49 +00001233 if (auto *M = PP.getModuleContainingLocation(Loc))
1234 Context.mergeDefinitionIntoModule(ND, M);
1235 else
1236 // We're not building a module; just make the definition visible.
1237 ND->setHidden(false);
Richard Smithd9ba2242015-05-07 03:54:19 +00001238}
1239
Richard Smith0e5d7b82013-07-25 23:08:39 +00001240/// \brief Find the module in which the given declaration was defined.
Richard Smith42413142015-05-15 20:05:43 +00001241static Module *getDefiningModule(Sema &S, Decl *Entity) {
Richard Smith0e5d7b82013-07-25 23:08:39 +00001242 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1243 // If this function was instantiated from a template, the defining module is
1244 // the module containing the pattern.
1245 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1246 Entity = Pattern;
1247 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
Reid Klecknere7367d62014-10-14 20:28:40 +00001248 if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
1249 Entity = Pattern;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001250 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1251 if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo())
1252 Entity = getInstantiatedFrom(ED, MSInfo);
1253 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1254 // FIXME: Map from variable template specializations back to the template.
1255 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo())
1256 Entity = getInstantiatedFrom(VD, MSInfo);
1257 }
1258
1259 // Walk up to the containing context. That might also have been instantiated
1260 // from a template.
1261 DeclContext *Context = Entity->getDeclContext();
1262 if (Context->isFileContext())
Richard Smith42413142015-05-15 20:05:43 +00001263 return S.getOwningModule(Entity);
1264 return getDefiningModule(S, cast<Decl>(Context));
Richard Smith0e5d7b82013-07-25 23:08:39 +00001265}
1266
1267llvm::DenseSet<Module*> &Sema::getLookupModules() {
1268 unsigned N = ActiveTemplateInstantiations.size();
1269 for (unsigned I = ActiveTemplateInstantiationLookupModules.size();
1270 I != N; ++I) {
Richard Smith42413142015-05-15 20:05:43 +00001271 Module *M =
1272 getDefiningModule(*this, ActiveTemplateInstantiations[I].Entity);
Richard Smith0e5d7b82013-07-25 23:08:39 +00001273 if (M && !LookupModulesCache.insert(M).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00001274 M = nullptr;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001275 ActiveTemplateInstantiationLookupModules.push_back(M);
1276 }
1277 return LookupModulesCache;
1278}
1279
Richard Smith42413142015-05-15 20:05:43 +00001280bool Sema::hasVisibleMergedDefinition(NamedDecl *Def) {
1281 for (Module *Merged : Context.getModulesWithMergedDefinition(Def))
1282 if (isModuleVisible(Merged))
1283 return true;
1284 return false;
1285}
1286
Richard Smithe7bd6de2015-06-10 20:30:23 +00001287template<typename ParmDecl>
1288static bool hasVisibleDefaultArgument(Sema &S, const ParmDecl *D) {
1289 if (!D->hasDefaultArgument())
1290 return false;
1291
1292 while (D) {
1293 auto &DefaultArg = D->getDefaultArgStorage();
1294 if (!DefaultArg.isInherited() && S.isVisible(D))
1295 return true;
1296
1297 // If there was a previous default argument, maybe its parameter is visible.
1298 D = DefaultArg.getInheritedFrom();
1299 }
1300 return false;
1301}
1302
1303bool Sema::hasVisibleDefaultArgument(const NamedDecl *D) {
1304 if (auto *P = dyn_cast<TemplateTypeParmDecl>(D))
1305 return ::hasVisibleDefaultArgument(*this, P);
1306 if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))
1307 return ::hasVisibleDefaultArgument(*this, P);
1308 return ::hasVisibleDefaultArgument(*this, cast<TemplateTemplateParmDecl>(D));
1309}
1310
Richard Smith0e5d7b82013-07-25 23:08:39 +00001311/// \brief Determine whether a declaration is visible to name lookup.
1312///
1313/// This routine determines whether the declaration D is visible in the current
1314/// lookup context, taking into account the current template instantiation
1315/// stack. During template instantiation, a declaration is visible if it is
1316/// visible from a module containing any entity on the template instantiation
1317/// path (by instantiating a template, you allow it to see the declarations that
1318/// your module can see, including those later on in your module).
1319bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001320 assert(D->isHidden() && "should not call this: not in slow case");
Richard Smith42413142015-05-15 20:05:43 +00001321 Module *DeclModule = SemaRef.getOwningModule(D);
1322 if (!DeclModule) {
1323 // getOwningModule() may have decided the declaration should not be hidden.
1324 assert(!D->isHidden() && "hidden decl not from a module");
1325 return true;
1326 }
1327
1328 // If the owning module is visible, and the decl is not module private,
1329 // then the decl is visible too. (Module private is ignored within the same
1330 // top-level module.)
1331 if (!D->isFromASTFile() || !D->isModulePrivate()) {
1332 if (SemaRef.isModuleVisible(DeclModule))
1333 return true;
1334 // Also check merged definitions.
1335 if (SemaRef.getLangOpts().ModulesLocalVisibility &&
1336 SemaRef.hasVisibleMergedDefinition(D))
1337 return true;
1338 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001339
Richard Smithbe3980b2015-03-27 00:41:57 +00001340 // If this declaration is not at namespace scope nor module-private,
1341 // then it is visible if its lexical parent has a visible definition.
1342 DeclContext *DC = D->getLexicalDeclContext();
1343 if (!D->isModulePrivate() &&
1344 DC && !DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) {
Richard Smithc7d48d12015-05-20 17:50:35 +00001345 // For a parameter, check whether our current template declaration's
1346 // lexical context is visible, not whether there's some other visible
1347 // definition of it, because parameters aren't "within" the definition.
1348 if ((D->isTemplateParameter() || isa<ParmVarDecl>(D))
1349 ? isVisible(SemaRef, cast<NamedDecl>(DC))
1350 : SemaRef.hasVisibleDefinition(cast<NamedDecl>(DC))) {
Richard Smith42413142015-05-15 20:05:43 +00001351 if (SemaRef.ActiveTemplateInstantiations.empty() &&
1352 // FIXME: Do something better in this case.
1353 !SemaRef.getLangOpts().ModulesLocalVisibility) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001354 // Cache the fact that this declaration is implicitly visible because
1355 // its parent has a visible definition.
1356 D->setHidden(false);
1357 }
1358 return true;
1359 }
1360 return false;
1361 }
1362
Richard Smith0e5d7b82013-07-25 23:08:39 +00001363 // Find the extra places where we need to look.
1364 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
1365 if (LookupModules.empty())
1366 return false;
1367
1368 // If our lookup set contains the decl's module, it's visible.
1369 if (LookupModules.count(DeclModule))
1370 return true;
1371
1372 // If the declaration isn't exported, it's not visible in any other module.
1373 if (D->isModulePrivate())
1374 return false;
1375
1376 // Check whether DeclModule is transitively exported to an import of
1377 // the lookup set.
1378 for (llvm::DenseSet<Module *>::iterator I = LookupModules.begin(),
1379 E = LookupModules.end();
1380 I != E; ++I)
1381 if ((*I)->isModuleVisible(DeclModule))
1382 return true;
1383 return false;
1384}
1385
Richard Smith42413142015-05-15 20:05:43 +00001386bool Sema::isVisibleSlow(const NamedDecl *D) {
1387 return LookupResult::isVisible(*this, const_cast<NamedDecl*>(D));
1388}
1389
Douglas Gregor4a814562011-12-14 16:03:29 +00001390/// \brief Retrieve the visible declaration corresponding to D, if any.
1391///
1392/// This routine determines whether the declaration D is visible in the current
1393/// module, with the current imports. If not, it checks whether any
1394/// redeclaration of D is visible, and if so, returns that declaration.
Richard Smith0e5d7b82013-07-25 23:08:39 +00001395///
Douglas Gregor4a814562011-12-14 16:03:29 +00001396/// \returns D, or a visible previous declaration of D, whichever is more recent
1397/// and visible. If no declaration of D is visible, returns null.
Richard Smithe156254d2013-08-20 20:35:18 +00001398static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
1399 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
Richard Smith0e5d7b82013-07-25 23:08:39 +00001400
Aaron Ballman86c93902014-03-06 23:45:36 +00001401 for (auto RD : D->redecls()) {
1402 if (auto ND = dyn_cast<NamedDecl>(RD)) {
Richard Smithe8292b12015-02-10 03:28:10 +00001403 // FIXME: This is wrong in the case where the previous declaration is not
1404 // visible in the same scope as D. This needs to be done much more
1405 // carefully.
Richard Smithe156254d2013-08-20 20:35:18 +00001406 if (LookupResult::isVisible(SemaRef, ND))
Douglas Gregor54079202012-01-06 22:05:37 +00001407 return ND;
1408 }
Douglas Gregor4a814562011-12-14 16:03:29 +00001409 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001410
Craig Topperc3ec1492014-05-26 06:22:03 +00001411 return nullptr;
Douglas Gregor4a814562011-12-14 16:03:29 +00001412}
1413
Richard Smithe156254d2013-08-20 20:35:18 +00001414NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +00001415 return findAcceptableDecl(getSema(), D);
Richard Smithe156254d2013-08-20 20:35:18 +00001416}
1417
Douglas Gregor34074322009-01-14 22:20:51 +00001418/// @brief Perform unqualified name lookup starting from a given
1419/// scope.
1420///
1421/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1422/// used to find names within the current scope. For example, 'x' in
1423/// @code
1424/// int x;
1425/// int f() {
1426/// return x; // unqualified name look finds 'x' in the global scope
1427/// }
1428/// @endcode
1429///
1430/// Different lookup criteria can find different names. For example, a
1431/// particular scope can have both a struct and a function of the same
1432/// name, and each can be found by certain lookup criteria. For more
1433/// information about lookup criteria, see the documentation for the
1434/// class LookupCriteria.
1435///
1436/// @param S The scope from which unqualified name lookup will
1437/// begin. If the lookup criteria permits, name lookup may also search
1438/// in the parent scopes.
1439///
James Dennett91738ff2012-06-22 10:32:46 +00001440/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1441/// look up and the lookup kind), and is updated with the results of lookup
1442/// including zero or more declarations and possibly additional information
1443/// used to diagnose ambiguities.
Douglas Gregor34074322009-01-14 22:20:51 +00001444///
James Dennett91738ff2012-06-22 10:32:46 +00001445/// @returns \c true if lookup succeeded and false otherwise.
John McCall27b18f82009-11-17 02:14:36 +00001446bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1447 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001448 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001449
John McCall27b18f82009-11-17 02:14:36 +00001450 LookupNameKind NameKind = R.getLookupKind();
1451
David Blaikiebbafb8a2012-03-11 07:00:24 +00001452 if (!getLangOpts().CPlusPlus) {
Douglas Gregor34074322009-01-14 22:20:51 +00001453 // Unqualified name lookup in C/Objective-C is purely lexical, so
1454 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001455 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001456 // Find the nearest non-transparent declaration scope.
1457 while (!(S->getFlags() & Scope::DeclScope) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001458 (S->getEntity() && S->getEntity()->isTransparentContext()))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001459 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001460 }
1461
Richard Smith541b38b2013-09-20 01:15:31 +00001462 // When performing a scope lookup, we want to find local extern decls.
1463 FindLocalExternScope FindLocals(R);
1464
Douglas Gregor34074322009-01-14 22:20:51 +00001465 // Scan up the scope chain looking for a decl that matches this
1466 // identifier that is in the appropriate namespace. This search
1467 // should not take long, as shadowing of names is uncommon, and
1468 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001469 bool LeftStartingScope = false;
1470
Douglas Gregored8f2882009-01-30 01:04:22 +00001471 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001472 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001473 I != IEnd; ++I)
Richard Smith0e5d7b82013-07-25 23:08:39 +00001474 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001475 if (NameKind == LookupRedeclarationWithLinkage) {
1476 // Determine whether this (or a previous) declaration is
1477 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001478 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001479 LeftStartingScope = true;
1480
1481 // If we found something outside of our starting scope that
1482 // does not have linkage, skip it.
Richard Smith1c34fb72013-08-13 18:18:50 +00001483 if (LeftStartingScope && !((*I)->hasLinkage())) {
1484 R.setShadowed();
Douglas Gregoreddf4332009-02-24 20:03:32 +00001485 continue;
Richard Smith1c34fb72013-08-13 18:18:50 +00001486 }
Douglas Gregoreddf4332009-02-24 20:03:32 +00001487 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001488 else if (NameKind == LookupObjCImplicitSelfParam &&
1489 !isa<ImplicitParamDecl>(*I))
1490 continue;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001491
Douglas Gregor4a814562011-12-14 16:03:29 +00001492 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001493
Douglas Gregorb59643b2012-01-03 23:26:26 +00001494 // Check whether there are any other declarations with the same name
1495 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001496 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001497 // Find the scope in which this declaration was declared (if it
1498 // actually exists in a Scope).
1499 while (S && !S->isDeclScope(D))
1500 S = S->getParent();
1501
1502 // If the scope containing the declaration is the translation unit,
1503 // then we'll need to perform our checks based on the matching
1504 // DeclContexts rather than matching scopes.
1505 if (S && isNamespaceOrTranslationUnitScope(S))
Craig Topperc3ec1492014-05-26 06:22:03 +00001506 S = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001507
1508 // Compute the DeclContext, if we need it.
Craig Topperc3ec1492014-05-26 06:22:03 +00001509 DeclContext *DC = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001510 if (!S)
1511 DC = (*I)->getDeclContext()->getRedeclContext();
1512
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001513 IdentifierResolver::iterator LastI = I;
1514 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001515 if (S) {
1516 // Match based on scope.
1517 if (!S->isDeclScope(*LastI))
1518 break;
1519 } else {
1520 // Match based on DeclContext.
1521 DeclContext *LastDC
1522 = (*LastI)->getDeclContext()->getRedeclContext();
1523 if (!LastDC->Equals(DC))
1524 break;
1525 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001526
1527 // If the declaration is in the right namespace and visible, add it.
1528 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1529 R.addDecl(LastD);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001530 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001531
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001532 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001533 }
Richard Smith541b38b2013-09-20 01:15:31 +00001534
John McCall9f3059a2009-10-09 21:13:30 +00001535 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001536 }
Douglas Gregor34074322009-01-14 22:20:51 +00001537 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001538 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001539 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001540 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001541 }
1542
1543 // If we didn't find a use of this identifier, and if the identifier
1544 // corresponds to a compiler builtin, create the decl object for the builtin
1545 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001546 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1547 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001548
Axel Naumann016538a2011-02-24 16:47:47 +00001549 // If we didn't find a use of this identifier, the ExternalSource
1550 // may be able to handle the situation.
1551 // Note: some lookup failures are expected!
1552 // See e.g. R.isForRedeclaration().
1553 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001554}
1555
John McCall6538c932009-10-10 05:48:19 +00001556/// @brief Perform qualified name lookup in the namespaces nominated by
1557/// using directives by the given context.
1558///
1559/// C++98 [namespace.qual]p2:
James Dennett51a8d8b2012-06-19 21:05:49 +00001560/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6538c932009-10-10 05:48:19 +00001561/// (where X is the global namespace), let S be the set of all
1562/// declarations of m in X and in the transitive closure of all
1563/// namespaces nominated by using-directives in X and its used
1564/// namespaces, except that using-directives are ignored in any
1565/// namespace, including X, directly containing one or more
1566/// declarations of m. No namespace is searched more than once in
1567/// the lookup of a name. If S is the empty set, the program is
1568/// ill-formed. Otherwise, if S has exactly one member, or if the
1569/// context of the reference is a using-declaration
1570/// (namespace.udecl), S is the required set of declarations of
1571/// m. Otherwise if the use of m is not one that allows a unique
1572/// declaration to be chosen from S, the program is ill-formed.
James Dennett51a8d8b2012-06-19 21:05:49 +00001573///
John McCall6538c932009-10-10 05:48:19 +00001574/// C++98 [namespace.qual]p5:
1575/// During the lookup of a qualified namespace member name, if the
1576/// lookup finds more than one declaration of the member, and if one
1577/// declaration introduces a class name or enumeration name and the
1578/// other declarations either introduce the same object, the same
1579/// enumerator or a set of functions, the non-type name hides the
1580/// class or enumeration name if and only if the declarations are
1581/// from the same namespace; otherwise (the declarations are from
1582/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001583static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001584 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001585 assert(StartDC->isFileContext() && "start context is not a file context");
1586
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001587 DeclContext::udir_range UsingDirectives = StartDC->using_directives();
1588 if (UsingDirectives.begin() == UsingDirectives.end()) return false;
John McCall6538c932009-10-10 05:48:19 +00001589
1590 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001591 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001592 Visited.insert(StartDC);
1593
1594 // We have not yet looked into these namespaces, much less added
1595 // their "using-children" to the queue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001596 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001597
1598 // We have already looked into the initial namespace; seed the queue
1599 // with its using-children.
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001600 for (auto *I : UsingDirectives) {
1601 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +00001602 if (Visited.insert(ND).second)
John McCall6538c932009-10-10 05:48:19 +00001603 Queue.push_back(ND);
1604 }
1605
1606 // The easiest way to implement the restriction in [namespace.qual]p5
1607 // is to check whether any of the individual results found a tag
1608 // and, if so, to declare an ambiguity if the final result is not
1609 // a tag.
1610 bool FoundTag = false;
1611 bool FoundNonTag = false;
1612
John McCall5cebab12009-11-18 07:57:50 +00001613 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001614
1615 bool Found = false;
1616 while (!Queue.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001617 NamespaceDecl *ND = Queue.pop_back_val();
John McCall6538c932009-10-10 05:48:19 +00001618
1619 // We go through some convolutions here to avoid copying results
1620 // between LookupResults.
1621 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001622 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001623 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001624
1625 if (FoundDirect) {
1626 // First do any local hiding.
1627 DirectR.resolveKind();
1628
1629 // If the local result is a tag, remember that.
1630 if (DirectR.isSingleTagDecl())
1631 FoundTag = true;
1632 else
1633 FoundNonTag = true;
1634
1635 // Append the local results to the total results if necessary.
1636 if (UseLocal) {
1637 R.addAllDecls(LocalR);
1638 LocalR.clear();
1639 }
1640 }
1641
1642 // If we find names in this namespace, ignore its using directives.
1643 if (FoundDirect) {
1644 Found = true;
1645 continue;
1646 }
1647
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001648 for (auto I : ND->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00001649 NamespaceDecl *Nom = I->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +00001650 if (Visited.insert(Nom).second)
John McCall6538c932009-10-10 05:48:19 +00001651 Queue.push_back(Nom);
1652 }
1653 }
1654
1655 if (Found) {
1656 if (FoundTag && FoundNonTag)
1657 R.setAmbiguousQualifiedTagHiding();
1658 else
1659 R.resolveKind();
1660 }
1661
1662 return Found;
1663}
1664
Douglas Gregor39982192010-08-15 06:18:01 +00001665/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001666static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor39982192010-08-15 06:18:01 +00001667 CXXBasePath &Path,
1668 void *Name) {
1669 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001670
Douglas Gregor39982192010-08-15 06:18:01 +00001671 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1672 Path.Decls = BaseRecord->lookup(N);
David Blaikieff7d47a2012-12-19 00:45:41 +00001673 return !Path.Decls.empty();
Douglas Gregor39982192010-08-15 06:18:01 +00001674}
1675
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001676/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001677/// static members, nested types, and enumerators.
1678template<typename InputIterator>
1679static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1680 Decl *D = (*First)->getUnderlyingDecl();
1681 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1682 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001683
Douglas Gregorc0d24902010-10-22 22:08:47 +00001684 if (isa<CXXMethodDecl>(D)) {
1685 // Determine whether all of the methods are static.
1686 bool AllMethodsAreStatic = true;
1687 for(; First != Last; ++First) {
1688 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001689
Douglas Gregorc0d24902010-10-22 22:08:47 +00001690 if (!isa<CXXMethodDecl>(D)) {
1691 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1692 break;
1693 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001694
Douglas Gregorc0d24902010-10-22 22:08:47 +00001695 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1696 AllMethodsAreStatic = false;
1697 break;
1698 }
1699 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001700
Douglas Gregorc0d24902010-10-22 22:08:47 +00001701 if (AllMethodsAreStatic)
1702 return true;
1703 }
1704
1705 return false;
1706}
1707
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001708/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001709///
1710/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1711/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001712/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001713///
1714/// Different lookup criteria can find different names. For example, a
1715/// particular scope can have both a struct and a function of the same
1716/// name, and each can be found by certain lookup criteria. For more
1717/// information about lookup criteria, see the documentation for the
1718/// class LookupCriteria.
1719///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001720/// \param R captures both the lookup criteria and any lookup results found.
1721///
1722/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001723/// search. If the lookup criteria permits, name lookup may also search
1724/// in the parent contexts or (for C++ classes) base classes.
1725///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001726/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001727/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001728///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001729/// \returns true if lookup succeeded, false if it failed.
1730bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1731 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001732 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001733
John McCall27b18f82009-11-17 02:14:36 +00001734 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001735 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001736
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001737 // Make sure that the declaration context is complete.
1738 assert((!isa<TagDecl>(LookupCtx) ||
1739 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00001740 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith7d137e32012-03-23 03:33:32 +00001741 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001742 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001743
Douglas Gregor34074322009-01-14 22:20:51 +00001744 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001745 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001746 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001747 if (isa<CXXRecordDecl>(LookupCtx))
1748 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001749 return true;
1750 }
Douglas Gregor34074322009-01-14 22:20:51 +00001751
John McCall6538c932009-10-10 05:48:19 +00001752 // Don't descend into implied contexts for redeclarations.
1753 // C++98 [namespace.qual]p6:
1754 // In a declaration for a namespace member in which the
1755 // declarator-id is a qualified-id, given that the qualified-id
1756 // for the namespace member has the form
1757 // nested-name-specifier unqualified-id
1758 // the unqualified-id shall name a member of the namespace
1759 // designated by the nested-name-specifier.
1760 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001761 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001762 return false;
1763
John McCall27b18f82009-11-17 02:14:36 +00001764 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001765 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001766 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001767
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001768 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001769 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001770 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001771 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001772 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001773
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001774 // If we're performing qualified name lookup into a dependent class,
1775 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001776 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001777 // template instantiation time (at which point all bases will be available)
1778 // or we have to fail.
1779 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1780 LookupRec->hasAnyDependentBases()) {
1781 R.setNotFoundInCurrentInstantiation();
1782 return false;
1783 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001784
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001785 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001786 CXXBasePaths Paths;
1787 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001788
1789 // Look for this member in our base classes
Craig Topperc3ec1492014-05-26 06:22:03 +00001790 CXXRecordDecl::BaseMatchesCallback *BaseCallback = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00001791 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001792 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001793 case LookupOrdinaryName:
1794 case LookupMemberName:
1795 case LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +00001796 case LookupLocalFriendName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001797 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1798 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001799
Douglas Gregor36d1b142009-10-06 17:59:45 +00001800 case LookupTagName:
1801 BaseCallback = &CXXRecordDecl::FindTagMember;
1802 break;
John McCall84d87672009-12-10 09:41:52 +00001803
Douglas Gregor39982192010-08-15 06:18:01 +00001804 case LookupAnyName:
1805 BaseCallback = &LookupAnyMember;
1806 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001807
John McCall84d87672009-12-10 09:41:52 +00001808 case LookupUsingDeclName:
1809 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001810
Douglas Gregor36d1b142009-10-06 17:59:45 +00001811 case LookupOperatorName:
1812 case LookupNamespaceName:
1813 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001814 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001815 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001816 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001817
Douglas Gregor36d1b142009-10-06 17:59:45 +00001818 case LookupNestedNameSpecifierName:
1819 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1820 break;
1821 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001822
John McCall27b18f82009-11-17 02:14:36 +00001823 if (!LookupRec->lookupInBases(BaseCallback,
1824 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001825 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001826
John McCall553c0792010-01-23 00:46:32 +00001827 R.setNamingClass(LookupRec);
1828
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001829 // C++ [class.member.lookup]p2:
1830 // [...] If the resulting set of declarations are not all from
1831 // sub-objects of the same type, or the set has a nonstatic member
1832 // and includes members from distinct sub-objects, there is an
1833 // ambiguity and the program is ill-formed. Otherwise that set is
1834 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001835 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001836 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001837 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001838
Douglas Gregor36d1b142009-10-06 17:59:45 +00001839 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001840 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001841 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001842
John McCall401982f2010-01-20 21:53:11 +00001843 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1844 // across all paths.
1845 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001846
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001847 // Determine whether we're looking at a distinct sub-object or not.
1848 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001849 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001850 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1851 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001852 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001853 }
1854
Douglas Gregorc0d24902010-10-22 22:08:47 +00001855 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001856 != Context.getCanonicalType(PathElement.Base->getType())) {
1857 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001858 // different types. If the declaration sets aren't the same, this
Nikola Smiljanic1c125682014-07-09 05:42:35 +00001859 // lookup is ambiguous.
David Blaikieff7d47a2012-12-19 00:45:41 +00001860 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00001861 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikieff7d47a2012-12-19 00:45:41 +00001862 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
1863 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001864
David Blaikieff7d47a2012-12-19 00:45:41 +00001865 while (FirstD != FirstPath->Decls.end() &&
1866 CurrentD != Path->Decls.end()) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00001867 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1868 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1869 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001870
Douglas Gregorc0d24902010-10-22 22:08:47 +00001871 ++FirstD;
1872 ++CurrentD;
1873 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001874
David Blaikieff7d47a2012-12-19 00:45:41 +00001875 if (FirstD == FirstPath->Decls.end() &&
1876 CurrentD == Path->Decls.end())
Douglas Gregorc0d24902010-10-22 22:08:47 +00001877 continue;
1878 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001879
John McCall9f3059a2009-10-09 21:13:30 +00001880 R.setAmbiguousBaseSubobjectTypes(Paths);
1881 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001882 }
1883
Douglas Gregorc0d24902010-10-22 22:08:47 +00001884 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001885 // We have a different subobject of the same type.
1886
1887 // C++ [class.member.lookup]p5:
1888 // A static member, a nested type or an enumerator defined in
1889 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001890 // has more than one base class subobject of type T.
David Blaikieff7d47a2012-12-19 00:45:41 +00001891 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001892 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001893
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001894 // We have found a nonstatic member name in multiple, distinct
1895 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001896 R.setAmbiguousBaseSubobjects(Paths);
1897 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001898 }
1899 }
1900
1901 // Lookup in a base class succeeded; return these results.
1902
Aaron Ballman1e606f42014-07-15 22:03:49 +00001903 for (auto *D : Paths.front().Decls) {
John McCall553c0792010-01-23 00:46:32 +00001904 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1905 D->getAccess());
1906 R.addDecl(D, AS);
1907 }
John McCall9f3059a2009-10-09 21:13:30 +00001908 R.resolveKind();
1909 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001910}
1911
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00001912/// \brief Performs qualified name lookup or special type of lookup for
1913/// "__super::" scope specifier.
1914///
1915/// This routine is a convenience overload meant to be called from contexts
1916/// that need to perform a qualified name lookup with an optional C++ scope
1917/// specifier that might require special kind of lookup.
1918///
1919/// \param R captures both the lookup criteria and any lookup results found.
1920///
1921/// \param LookupCtx The context in which qualified name lookup will
1922/// search.
1923///
1924/// \param SS An optional C++ scope-specifier.
1925///
1926/// \returns true if lookup succeeded, false if it failed.
1927bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1928 CXXScopeSpec &SS) {
1929 auto *NNS = SS.getScopeRep();
1930 if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
1931 return LookupInSuper(R, NNS->getAsRecordDecl());
1932 else
1933
1934 return LookupQualifiedName(R, LookupCtx);
1935}
1936
Douglas Gregor34074322009-01-14 22:20:51 +00001937/// @brief Performs name lookup for a name that was parsed in the
1938/// source code, and may contain a C++ scope specifier.
1939///
1940/// This routine is a convenience routine meant to be called from
1941/// contexts that receive a name and an optional C++ scope specifier
1942/// (e.g., "N::M::x"). It will then perform either qualified or
1943/// unqualified name lookup (with LookupQualifiedName or LookupName,
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00001944/// respectively) on the given name and return those results. It will
1945/// perform a special type of lookup for "__super::" scope specifier.
Douglas Gregor34074322009-01-14 22:20:51 +00001946///
1947/// @param S The scope from which unqualified name lookup will
1948/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001949///
Douglas Gregore861bac2009-08-25 22:51:20 +00001950/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001951///
Douglas Gregore861bac2009-08-25 22:51:20 +00001952/// @param EnteringContext Indicates whether we are going to enter the
1953/// context of the scope-specifier SS (if present).
1954///
John McCall9f3059a2009-10-09 21:13:30 +00001955/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001956bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001957 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001958 if (SS && SS->isInvalid()) {
1959 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001960 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001961 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001962 }
Mike Stump11289f42009-09-09 15:08:12 +00001963
Douglas Gregore861bac2009-08-25 22:51:20 +00001964 if (SS && SS->isSet()) {
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00001965 NestedNameSpecifier *NNS = SS->getScopeRep();
1966 if (NNS->getKind() == NestedNameSpecifier::Super)
1967 return LookupInSuper(R, NNS->getAsRecordDecl());
1968
Douglas Gregore861bac2009-08-25 22:51:20 +00001969 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001970 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001971 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001972 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001973 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001974
John McCall27b18f82009-11-17 02:14:36 +00001975 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00001976 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001977 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001978
Douglas Gregore861bac2009-08-25 22:51:20 +00001979 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001980 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001981 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00001982 R.setNotFoundInCurrentInstantiation();
1983 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00001984 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001985 }
1986
Mike Stump11289f42009-09-09 15:08:12 +00001987 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001988 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001989}
1990
Nikola Smiljanic67860242014-09-26 00:28:20 +00001991/// \brief Perform qualified name lookup into all base classes of the given
1992/// class.
1993///
1994/// \param R captures both the lookup criteria and any lookup results found.
1995///
1996/// \param Class The context in which qualified name lookup will
1997/// search. Name lookup will search in all base classes merging the results.
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00001998///
1999/// @returns True if any decls were found (but possibly ambiguous)
2000bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
Nikola Smiljanic67860242014-09-26 00:28:20 +00002001 for (const auto &BaseSpec : Class->bases()) {
2002 CXXRecordDecl *RD = cast<CXXRecordDecl>(
2003 BaseSpec.getType()->castAs<RecordType>()->getDecl());
2004 LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
2005 Result.setBaseObjectType(Context.getRecordType(Class));
2006 LookupQualifiedName(Result, RD);
2007 for (auto *Decl : Result)
2008 R.addDecl(Decl);
2009 }
2010
2011 R.resolveKind();
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002012
2013 return !R.empty();
Nikola Smiljanic67860242014-09-26 00:28:20 +00002014}
Douglas Gregor889ceb72009-02-03 19:21:40 +00002015
James Dennett41725122012-06-22 10:16:05 +00002016/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002017/// from name lookup.
2018///
James Dennett41725122012-06-22 10:16:05 +00002019/// \param Result The result of the ambiguous lookup to be diagnosed.
Serge Pavlov99292092013-08-29 07:23:24 +00002020void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002021 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
2022
John McCall27b18f82009-11-17 02:14:36 +00002023 DeclarationName Name = Result.getLookupName();
2024 SourceLocation NameLoc = Result.getNameLoc();
2025 SourceRange LookupRange = Result.getContextRange();
2026
John McCall6538c932009-10-10 05:48:19 +00002027 switch (Result.getAmbiguityKind()) {
2028 case LookupResult::AmbiguousBaseSubobjects: {
2029 CXXBasePaths *Paths = Result.getBasePaths();
2030 QualType SubobjectType = Paths->front().back().Base->getType();
2031 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
2032 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
2033 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002034
David Blaikieff7d47a2012-12-19 00:45:41 +00002035 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6538c932009-10-10 05:48:19 +00002036 while (isa<CXXMethodDecl>(*Found) &&
2037 cast<CXXMethodDecl>(*Found)->isStatic())
2038 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002039
John McCall6538c932009-10-10 05:48:19 +00002040 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
Serge Pavlov99292092013-08-29 07:23:24 +00002041 break;
John McCall6538c932009-10-10 05:48:19 +00002042 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00002043
John McCall6538c932009-10-10 05:48:19 +00002044 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00002045 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
2046 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002047
John McCall6538c932009-10-10 05:48:19 +00002048 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002049 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00002050 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
2051 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002052 Path != PathEnd; ++Path) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002053 Decl *D = Path->Decls.front();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002054 if (DeclsPrinted.insert(D).second)
2055 Diag(D->getLocation(), diag::note_ambiguous_member_found);
2056 }
Serge Pavlov99292092013-08-29 07:23:24 +00002057 break;
Douglas Gregor1c846b02009-01-16 00:38:09 +00002058 }
2059
John McCall6538c932009-10-10 05:48:19 +00002060 case LookupResult::AmbiguousTagHiding: {
2061 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00002062
John McCall6538c932009-10-10 05:48:19 +00002063 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
2064
Aaron Ballman1e606f42014-07-15 22:03:49 +00002065 for (auto *D : Result)
2066 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
John McCall6538c932009-10-10 05:48:19 +00002067 TagDecls.insert(TD);
2068 Diag(TD->getLocation(), diag::note_hidden_tag);
2069 }
2070
Aaron Ballman1e606f42014-07-15 22:03:49 +00002071 for (auto *D : Result)
2072 if (!isa<TagDecl>(D))
2073 Diag(D->getLocation(), diag::note_hiding_object);
John McCall6538c932009-10-10 05:48:19 +00002074
2075 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00002076 LookupResult::Filter F = Result.makeFilter();
2077 while (F.hasNext()) {
2078 if (TagDecls.count(F.next()))
2079 F.erase();
2080 }
2081 F.done();
Serge Pavlov99292092013-08-29 07:23:24 +00002082 break;
John McCall6538c932009-10-10 05:48:19 +00002083 }
2084
2085 case LookupResult::AmbiguousReference: {
2086 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002087
Aaron Ballman1e606f42014-07-15 22:03:49 +00002088 for (auto *D : Result)
2089 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
Serge Pavlov99292092013-08-29 07:23:24 +00002090 break;
John McCall6538c932009-10-10 05:48:19 +00002091 }
Serge Pavlov99292092013-08-29 07:23:24 +00002092 }
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002093}
Douglas Gregore254f902009-02-04 00:32:51 +00002094
John McCallf24d7bb2010-05-28 18:45:08 +00002095namespace {
2096 struct AssociatedLookup {
John McCall7d8b0412012-08-24 20:38:34 +00002097 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallf24d7bb2010-05-28 18:45:08 +00002098 Sema::AssociatedNamespaceSet &Namespaces,
2099 Sema::AssociatedClassSet &Classes)
John McCall7d8b0412012-08-24 20:38:34 +00002100 : S(S), Namespaces(Namespaces), Classes(Classes),
2101 InstantiationLoc(InstantiationLoc) {
John McCallf24d7bb2010-05-28 18:45:08 +00002102 }
2103
2104 Sema &S;
2105 Sema::AssociatedNamespaceSet &Namespaces;
2106 Sema::AssociatedClassSet &Classes;
John McCall7d8b0412012-08-24 20:38:34 +00002107 SourceLocation InstantiationLoc;
John McCallf24d7bb2010-05-28 18:45:08 +00002108 };
2109}
2110
Mike Stump11289f42009-09-09 15:08:12 +00002111static void
John McCallf24d7bb2010-05-28 18:45:08 +00002112addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00002113
Douglas Gregor8b895222010-04-30 07:08:38 +00002114static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
2115 DeclContext *Ctx) {
2116 // Add the associated namespace for this class.
2117
2118 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
2119 // be a locally scoped record.
2120
Sebastian Redlbd595762010-08-31 20:53:31 +00002121 // We skip out of inline namespaces. The innermost non-inline namespace
2122 // contains all names of all its nested inline namespaces anyway, so we can
2123 // replace the entire inline namespace tree with its root.
2124 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
2125 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00002126 Ctx = Ctx->getParent();
2127
John McCallc7e8e792009-08-07 22:18:02 +00002128 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00002129 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00002130}
Douglas Gregor197e5f72009-07-08 07:51:57 +00002131
Mike Stump11289f42009-09-09 15:08:12 +00002132// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00002133// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00002134static void
John McCallf24d7bb2010-05-28 18:45:08 +00002135addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2136 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002137 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00002138 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00002139 switch (Arg.getKind()) {
2140 case TemplateArgument::Null:
2141 break;
Mike Stump11289f42009-09-09 15:08:12 +00002142
Douglas Gregor197e5f72009-07-08 07:51:57 +00002143 case TemplateArgument::Type:
2144 // [...] the namespaces and classes associated with the types of the
2145 // template arguments provided for template type parameters (excluding
2146 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00002147 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00002148 break;
Mike Stump11289f42009-09-09 15:08:12 +00002149
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002150 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002151 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00002152 // [...] the namespaces in which any template template arguments are
2153 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00002154 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002155 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00002156 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002157 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002158 DeclContext *Ctx = ClassTemplate->getDeclContext();
2159 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002160 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002161 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002162 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002163 }
2164 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002165 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002166
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002167 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00002168 case TemplateArgument::Integral:
2169 case TemplateArgument::Expression:
Eli Friedmanb826a002012-09-26 02:36:12 +00002170 case TemplateArgument::NullPtr:
Mike Stump11289f42009-09-09 15:08:12 +00002171 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00002172 // associated namespaces. ]
2173 break;
Mike Stump11289f42009-09-09 15:08:12 +00002174
Douglas Gregor197e5f72009-07-08 07:51:57 +00002175 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00002176 for (const auto &P : Arg.pack_elements())
2177 addAssociatedClassesAndNamespaces(Result, P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002178 break;
2179 }
2180}
2181
Douglas Gregore254f902009-02-04 00:32:51 +00002182// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00002183// argument-dependent lookup with an argument of class type
2184// (C++ [basic.lookup.koenig]p2).
2185static void
John McCallf24d7bb2010-05-28 18:45:08 +00002186addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2187 CXXRecordDecl *Class) {
2188
2189 // Just silently ignore anything whose name is __va_list_tag.
2190 if (Class->getDeclName() == Result.S.VAListTagName)
2191 return;
2192
Douglas Gregore254f902009-02-04 00:32:51 +00002193 // C++ [basic.lookup.koenig]p2:
2194 // [...]
2195 // -- If T is a class type (including unions), its associated
2196 // classes are: the class itself; the class of which it is a
2197 // member, if any; and its direct and indirect base
2198 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00002199 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00002200
2201 // Add the class of which it is a member, if any.
2202 DeclContext *Ctx = Class->getDeclContext();
2203 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002204 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002205 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002206 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002207
Douglas Gregore254f902009-02-04 00:32:51 +00002208 // Add the class itself. If we've already seen this class, we don't
2209 // need to visit base classes.
Richard Smith594461f2014-03-14 22:07:27 +00002210 //
2211 // FIXME: That's not correct, we may have added this class only because it
2212 // was the enclosing class of another class, and in that case we won't have
2213 // added its base classes yet.
David Blaikie82e95a32014-11-19 07:49:47 +00002214 if (!Result.Classes.insert(Class).second)
Douglas Gregore254f902009-02-04 00:32:51 +00002215 return;
2216
Mike Stump11289f42009-09-09 15:08:12 +00002217 // -- If T is a template-id, its associated namespaces and classes are
2218 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002219 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00002220 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00002221 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00002222 // namespaces in which any template template arguments are defined; and
2223 // the classes in which any member templates used as template template
2224 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00002225 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00002226 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00002227 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2228 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2229 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002230 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002231 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002232 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002233
Douglas Gregor197e5f72009-07-08 07:51:57 +00002234 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2235 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00002236 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002237 }
Mike Stump11289f42009-09-09 15:08:12 +00002238
John McCall67da35c2010-02-04 22:26:26 +00002239 // Only recurse into base classes for complete types.
Richard Smith594461f2014-03-14 22:07:27 +00002240 if (!Class->hasDefinition())
2241 return;
John McCall67da35c2010-02-04 22:26:26 +00002242
Douglas Gregore254f902009-02-04 00:32:51 +00002243 // Add direct and indirect base classes along with their associated
2244 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002245 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00002246 Bases.push_back(Class);
2247 while (!Bases.empty()) {
2248 // Pop this class off the stack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002249 Class = Bases.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002250
2251 // Visit the base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +00002252 for (const auto &Base : Class->bases()) {
2253 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00002254 // In dependent contexts, we do ADL twice, and the first time around,
2255 // the base type might be a dependent TemplateSpecializationType, or a
2256 // TemplateTypeParmType. If that happens, simply ignore it.
2257 // FIXME: If we want to support export, we probably need to add the
2258 // namespace of the template in a TemplateSpecializationType, or even
2259 // the classes and namespaces of known non-dependent arguments.
2260 if (!BaseType)
2261 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002262 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
David Blaikie82e95a32014-11-19 07:49:47 +00002263 if (Result.Classes.insert(BaseDecl).second) {
Douglas Gregore254f902009-02-04 00:32:51 +00002264 // Find the associated namespace for this base class.
2265 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00002266 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00002267
2268 // Make sure we visit the bases of this base class.
2269 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2270 Bases.push_back(BaseDecl);
2271 }
2272 }
2273 }
2274}
2275
2276// \brief Add the associated classes and namespaces for
2277// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00002278// (C++ [basic.lookup.koenig]p2).
2279static void
John McCallf24d7bb2010-05-28 18:45:08 +00002280addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00002281 // C++ [basic.lookup.koenig]p2:
2282 //
2283 // For each argument type T in the function call, there is a set
2284 // of zero or more associated namespaces and a set of zero or more
2285 // associated classes to be considered. The sets of namespaces and
2286 // classes is determined entirely by the types of the function
2287 // arguments (and the namespace of any template template
2288 // argument). Typedef names and using-declarations used to specify
2289 // the types do not contribute to this set. The sets of namespaces
2290 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00002291
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002292 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00002293 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2294
Douglas Gregore254f902009-02-04 00:32:51 +00002295 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00002296 switch (T->getTypeClass()) {
2297
2298#define TYPE(Class, Base)
2299#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2300#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2301#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2302#define ABSTRACT_TYPE(Class, Base)
2303#include "clang/AST/TypeNodes.def"
2304 // T is canonical. We can also ignore dependent types because
2305 // we don't need to do ADL at the definition point, but if we
2306 // wanted to implement template export (or if we find some other
2307 // use for associated classes and namespaces...) this would be
2308 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00002309 break;
Douglas Gregore254f902009-02-04 00:32:51 +00002310
John McCall0af3d3b2010-05-28 06:08:54 +00002311 // -- If T is a pointer to U or an array of U, its associated
2312 // namespaces and classes are those associated with U.
2313 case Type::Pointer:
2314 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2315 continue;
2316 case Type::ConstantArray:
2317 case Type::IncompleteArray:
2318 case Type::VariableArray:
2319 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2320 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002321
John McCall0af3d3b2010-05-28 06:08:54 +00002322 // -- If T is a fundamental type, its associated sets of
2323 // namespaces and classes are both empty.
2324 case Type::Builtin:
2325 break;
2326
2327 // -- If T is a class type (including unions), its associated
2328 // classes are: the class itself; the class of which it is a
2329 // member, if any; and its direct and indirect base
2330 // classes. Its associated namespaces are the namespaces in
2331 // which its associated classes are defined.
2332 case Type::Record: {
Richard Smith594461f2014-03-14 22:07:27 +00002333 Result.S.RequireCompleteType(Result.InstantiationLoc, QualType(T, 0),
2334 /*no diagnostic*/ 0);
John McCall0af3d3b2010-05-28 06:08:54 +00002335 CXXRecordDecl *Class
2336 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002337 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00002338 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00002339 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00002340
John McCall0af3d3b2010-05-28 06:08:54 +00002341 // -- If T is an enumeration type, its associated namespace is
2342 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002343 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00002344 // it has no associated class.
2345 case Type::Enum: {
2346 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002347
John McCall0af3d3b2010-05-28 06:08:54 +00002348 DeclContext *Ctx = Enum->getDeclContext();
2349 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002350 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002351
John McCall0af3d3b2010-05-28 06:08:54 +00002352 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002353 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00002354
John McCall0af3d3b2010-05-28 06:08:54 +00002355 break;
2356 }
2357
2358 // -- If T is a function type, its associated namespaces and
2359 // classes are those associated with the function parameter
2360 // types and those associated with the return type.
2361 case Type::FunctionProto: {
2362 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002363 for (const auto &Arg : Proto->param_types())
2364 Queue.push_back(Arg.getTypePtr());
John McCall0af3d3b2010-05-28 06:08:54 +00002365 // fallthrough
2366 }
2367 case Type::FunctionNoProto: {
2368 const FunctionType *FnType = cast<FunctionType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00002369 T = FnType->getReturnType().getTypePtr();
John McCall0af3d3b2010-05-28 06:08:54 +00002370 continue;
2371 }
2372
2373 // -- If T is a pointer to a member function of a class X, its
2374 // associated namespaces and classes are those associated
2375 // with the function parameter types and return type,
2376 // together with those associated with X.
2377 //
2378 // -- If T is a pointer to a data member of class X, its
2379 // associated namespaces and classes are those associated
2380 // with the member type together with those associated with
2381 // X.
2382 case Type::MemberPointer: {
2383 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2384
2385 // Queue up the class type into which this points.
2386 Queue.push_back(MemberPtr->getClass());
2387
2388 // And directly continue with the pointee type.
2389 T = MemberPtr->getPointeeType().getTypePtr();
2390 continue;
2391 }
2392
2393 // As an extension, treat this like a normal pointer.
2394 case Type::BlockPointer:
2395 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2396 continue;
2397
2398 // References aren't covered by the standard, but that's such an
2399 // obvious defect that we cover them anyway.
2400 case Type::LValueReference:
2401 case Type::RValueReference:
2402 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2403 continue;
2404
2405 // These are fundamental types.
2406 case Type::Vector:
2407 case Type::ExtVector:
2408 case Type::Complex:
2409 break;
2410
Richard Smith27d807c2013-04-30 13:56:41 +00002411 // Non-deduced auto types only get here for error cases.
2412 case Type::Auto:
2413 break;
2414
Douglas Gregor8e936662011-04-12 01:02:45 +00002415 // If T is an Objective-C object or interface type, or a pointer to an
2416 // object or interface type, the associated namespace is the global
2417 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002418 case Type::ObjCObject:
2419 case Type::ObjCInterface:
2420 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002421 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002422 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002423
2424 // Atomic types are just wrappers; use the associations of the
2425 // contained type.
2426 case Type::Atomic:
2427 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2428 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002429 }
2430
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002431 if (Queue.empty())
2432 break;
2433 T = Queue.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002434 }
Douglas Gregore254f902009-02-04 00:32:51 +00002435}
2436
2437/// \brief Find the associated classes and namespaces for
2438/// argument-dependent lookup for a call with the given set of
2439/// arguments.
2440///
2441/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002442/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002443/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00002444void Sema::FindAssociatedClassesAndNamespaces(
2445 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2446 AssociatedNamespaceSet &AssociatedNamespaces,
2447 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002448 AssociatedNamespaces.clear();
2449 AssociatedClasses.clear();
2450
John McCall7d8b0412012-08-24 20:38:34 +00002451 AssociatedLookup Result(*this, InstantiationLoc,
2452 AssociatedNamespaces, AssociatedClasses);
John McCallf24d7bb2010-05-28 18:45:08 +00002453
Douglas Gregore254f902009-02-04 00:32:51 +00002454 // C++ [basic.lookup.koenig]p2:
2455 // For each argument type T in the function call, there is a set
2456 // of zero or more associated namespaces and a set of zero or more
2457 // associated classes to be considered. The sets of namespaces and
2458 // classes is determined entirely by the types of the function
2459 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002460 // argument).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002461 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregore254f902009-02-04 00:32:51 +00002462 Expr *Arg = Args[ArgIdx];
2463
2464 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002465 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002466 continue;
2467 }
2468
2469 // [...] In addition, if the argument is the name or address of a
2470 // set of overloaded functions and/or function templates, its
2471 // associated classes and namespaces are the union of those
2472 // associated with each of the members of the set: the namespace
2473 // in which the function or function template is defined and the
2474 // classes and namespaces associated with its (non-dependent)
2475 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002476 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002477 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002478 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002479 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002480
John McCallf24d7bb2010-05-28 18:45:08 +00002481 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2482 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002483
Aaron Ballman1e606f42014-07-15 22:03:49 +00002484 for (const auto *D : ULE->decls()) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002485 // Look through any using declarations to find the underlying function.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002486 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
Douglas Gregore254f902009-02-04 00:32:51 +00002487
2488 // Add the classes and namespaces associated with the parameter
2489 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002490 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002491 }
2492 }
2493}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002494
John McCall5cebab12009-11-18 07:57:50 +00002495NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002496 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002497 LookupNameKind NameKind,
2498 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002499 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002500 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002501 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002502}
2503
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002504/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002505ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002506 SourceLocation IdLoc,
2507 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002508 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002509 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002510 return cast_or_null<ObjCProtocolDecl>(D);
2511}
2512
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002513void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002514 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002515 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002516 // C++ [over.match.oper]p3:
2517 // -- The set of non-member candidates is the result of the
2518 // unqualified lookup of operator@ in the context of the
2519 // expression according to the usual rules for name lookup in
2520 // unqualified function calls (3.4.2) except that all member
Richard Smith100b24a2014-04-17 01:52:14 +00002521 // functions are ignored.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002522 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002523 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2524 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002525
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002526 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
Richard Smith100b24a2014-04-17 01:52:14 +00002527 Functions.append(Operators.begin(), Operators.end());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002528}
2529
Alexis Hunt1da39282011-06-24 02:11:39 +00002530Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002531 CXXSpecialMember SM,
2532 bool ConstArg,
2533 bool VolatileArg,
2534 bool RValueThis,
2535 bool ConstThis,
2536 bool VolatileThis) {
Richard Smith7d125a12012-11-27 21:20:31 +00002537 assert(CanDeclareSpecialMemberFunction(RD) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002538 "doing special member lookup into record that isn't fully complete");
Richard Smith7d125a12012-11-27 21:20:31 +00002539 RD = RD->getDefinition();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002540 if (RValueThis || ConstThis || VolatileThis)
2541 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2542 "constructors and destructors always have unqualified lvalue this");
2543 if (ConstArg || VolatileArg)
2544 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2545 "parameter-less special members can't have qualified arguments");
2546
2547 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002548 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002549 ID.AddInteger(SM);
2550 ID.AddInteger(ConstArg);
2551 ID.AddInteger(VolatileArg);
2552 ID.AddInteger(RValueThis);
2553 ID.AddInteger(ConstThis);
2554 ID.AddInteger(VolatileThis);
2555
2556 void *InsertPoint;
2557 SpecialMemberOverloadResult *Result =
2558 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2559
2560 // This was already cached
2561 if (Result)
2562 return Result;
2563
Alexis Huntba8e18d2011-06-07 00:11:58 +00002564 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2565 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002566 SpecialMemberCache.InsertNode(Result, InsertPoint);
2567
2568 if (SM == CXXDestructor) {
Richard Smith2be35f52012-12-01 02:35:44 +00002569 if (RD->needsImplicitDestructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002570 DeclareImplicitDestructor(RD);
2571 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002572 assert(DD && "record without a destructor");
2573 Result->setMethod(DD);
Richard Smith852265f2012-03-30 20:53:28 +00002574 Result->setKind(DD->isDeleted() ?
2575 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith83c478d2012-04-20 18:46:14 +00002576 SpecialMemberOverloadResult::Success);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002577 return Result;
2578 }
2579
Alexis Hunteef8ee02011-06-10 03:50:41 +00002580 // Prepare for overload resolution. Here we construct a synthetic argument
2581 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002582 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002583 DeclarationName Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002584 Expr *Arg = nullptr;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002585 unsigned NumArgs;
2586
Richard Smith83c478d2012-04-20 18:46:14 +00002587 QualType ArgType = CanTy;
2588 ExprValueKind VK = VK_LValue;
2589
Alexis Hunteef8ee02011-06-10 03:50:41 +00002590 if (SM == CXXDefaultConstructor) {
2591 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2592 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002593 if (RD->needsImplicitDefaultConstructor())
2594 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002595 } else {
2596 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2597 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smith2be35f52012-12-01 02:35:44 +00002598 if (RD->needsImplicitCopyConstructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002599 DeclareImplicitCopyConstructor(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002600 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002601 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002602 } else {
2603 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smith2be35f52012-12-01 02:35:44 +00002604 if (RD->needsImplicitCopyAssignment())
Alexis Hunt1da39282011-06-24 02:11:39 +00002605 DeclareImplicitCopyAssignment(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002606 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002607 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002608 }
2609
Alexis Hunteef8ee02011-06-10 03:50:41 +00002610 if (ConstArg)
2611 ArgType.addConst();
2612 if (VolatileArg)
2613 ArgType.addVolatile();
2614
2615 // This isn't /really/ specified by the standard, but it's implied
2616 // we should be working from an RValue in the case of move to ensure
2617 // that we prefer to bind to rvalue references, and an LValue in the
2618 // case of copy to ensure we don't bind to rvalue references.
2619 // Possibly an XValue is actually correct in the case of move, but
2620 // there is no semantic difference for class types in this restricted
2621 // case.
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002622 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002623 VK = VK_LValue;
2624 else
2625 VK = VK_RValue;
Richard Smith83c478d2012-04-20 18:46:14 +00002626 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00002627
Richard Smith83c478d2012-04-20 18:46:14 +00002628 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2629
2630 if (SM != CXXDefaultConstructor) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002631 NumArgs = 1;
Richard Smith83c478d2012-04-20 18:46:14 +00002632 Arg = &FakeArg;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002633 }
2634
2635 // Create the object argument
2636 QualType ThisTy = CanTy;
2637 if (ConstThis)
2638 ThisTy.addConst();
2639 if (VolatileThis)
2640 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002641 Expr::Classification Classification =
Richard Smith83c478d2012-04-20 18:46:14 +00002642 OpaqueValueExpr(SourceLocation(), ThisTy,
2643 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002644
2645 // Now we perform lookup on the name we computed earlier and do overload
2646 // resolution. Lookup is only performed directly into the class since there
2647 // will always be a (possibly implicit) declaration to shadow any others.
Richard Smith100b24a2014-04-17 01:52:14 +00002648 OverloadCandidateSet OCS(RD->getLocation(), OverloadCandidateSet::CSK_Normal);
David Blaikieff7d47a2012-12-19 00:45:41 +00002649 DeclContext::lookup_result R = RD->lookup(Name);
Richard Smith8c37ab52015-02-11 01:48:47 +00002650
2651 if (R.empty()) {
2652 // We might have no default constructor because we have a lambda's closure
2653 // type, rather than because there's some other declared constructor.
2654 // Every class has a copy/move constructor, copy/move assignment, and
2655 // destructor.
2656 assert(SM == CXXDefaultConstructor &&
2657 "lookup for a constructor or assignment operator was empty");
2658 Result->setMethod(nullptr);
2659 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
2660 return Result;
2661 }
Chandler Carruth7deaae72013-08-18 07:20:52 +00002662
2663 // Copy the candidates as our processing of them may load new declarations
2664 // from an external source and invalidate lookup_result.
2665 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2666
Aaron Ballman1e606f42014-07-15 22:03:49 +00002667 for (auto *Cand : Candidates) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002668 if (Cand->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002669 continue;
2670
Alexis Hunt1da39282011-06-24 02:11:39 +00002671 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2672 // FIXME: [namespace.udecl]p15 says that we should only consider a
2673 // using declaration here if it does not match a declaration in the
2674 // derived class. We do not implement this correctly in other cases
2675 // either.
2676 Cand = U->getTargetDecl();
2677
2678 if (Cand->isInvalidDecl())
2679 continue;
2680 }
2681
2682 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002683 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Alexis Hunt1da39282011-06-24 02:11:39 +00002684 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002685 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2686 OCS, true);
Alexis Hunt080709f2011-06-23 00:26:20 +00002687 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002688 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2689 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt2949f022011-06-22 02:58:46 +00002690 } else if (FunctionTemplateDecl *Tmpl =
Alexis Hunt1da39282011-06-24 02:11:39 +00002691 dyn_cast<FunctionTemplateDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002692 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2693 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Craig Topperc3ec1492014-05-26 06:22:03 +00002694 RD, nullptr, ThisTy, Classification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002695 llvm::makeArrayRef(&Arg, NumArgs),
Alexis Hunt080709f2011-06-23 00:26:20 +00002696 OCS, true);
2697 else
2698 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Craig Topperc3ec1492014-05-26 06:22:03 +00002699 nullptr, llvm::makeArrayRef(&Arg, NumArgs),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002700 OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002701 } else {
2702 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002703 }
2704 }
2705
2706 OverloadCandidateSet::iterator Best;
2707 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2708 case OR_Success:
2709 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith83c478d2012-04-20 18:46:14 +00002710 Result->setKind(SpecialMemberOverloadResult::Success);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002711 break;
2712
2713 case OR_Deleted:
2714 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith852265f2012-03-30 20:53:28 +00002715 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002716 break;
2717
2718 case OR_Ambiguous:
Craig Topperc3ec1492014-05-26 06:22:03 +00002719 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00002720 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2721 break;
2722
Alexis Hunteef8ee02011-06-10 03:50:41 +00002723 case OR_No_Viable_Function:
Craig Topperc3ec1492014-05-26 06:22:03 +00002724 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00002725 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002726 break;
2727 }
2728
2729 return Result;
2730}
2731
2732/// \brief Look up the default constructor for the given class.
2733CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002734 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002735 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2736 false, false);
2737
2738 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002739}
2740
Alexis Hunt491ec602011-06-21 23:42:56 +00002741/// \brief Look up the copying constructor for the given class.
2742CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith83c478d2012-04-20 18:46:14 +00002743 unsigned Quals) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002744 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2745 "non-const, non-volatile qualifiers for copy ctor arg");
2746 SpecialMemberOverloadResult *Result =
2747 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2748 Quals & Qualifiers::Volatile, false, false, false);
2749
Alexis Hunt899bd442011-06-10 04:44:37 +00002750 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2751}
2752
Sebastian Redl22653ba2011-08-30 19:58:05 +00002753/// \brief Look up the moving constructor for the given class.
Richard Smith1c6461e2012-07-18 03:36:00 +00002754CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2755 unsigned Quals) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002756 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002757 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2758 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002759
2760 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2761}
2762
Douglas Gregor52b72822010-07-02 23:12:18 +00002763/// \brief Look up the constructors for the given class.
2764DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002765 // If the implicit constructors have not yet been declared, do so now.
Richard Smith7d125a12012-11-27 21:20:31 +00002766 if (CanDeclareSpecialMemberFunction(Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00002767 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002768 DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +00002769 if (Class->needsImplicitCopyConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002770 DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002771 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002772 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00002773 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002774
Douglas Gregor52b72822010-07-02 23:12:18 +00002775 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2776 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2777 return Class->lookup(Name);
2778}
2779
Alexis Hunt491ec602011-06-21 23:42:56 +00002780/// \brief Look up the copying assignment operator for the given class.
2781CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2782 unsigned Quals, bool RValueThis,
Richard Smith83c478d2012-04-20 18:46:14 +00002783 unsigned ThisQuals) {
Alexis Hunt491ec602011-06-21 23:42:56 +00002784 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2785 "non-const, non-volatile qualifiers for copy assignment arg");
2786 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2787 "non-const, non-volatile qualifiers for copy assignment this");
2788 SpecialMemberOverloadResult *Result =
2789 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2790 Quals & Qualifiers::Volatile, RValueThis,
2791 ThisQuals & Qualifiers::Const,
2792 ThisQuals & Qualifiers::Volatile);
2793
Alexis Hunt491ec602011-06-21 23:42:56 +00002794 return Result->getMethod();
2795}
2796
Sebastian Redl22653ba2011-08-30 19:58:05 +00002797/// \brief Look up the moving assignment operator for the given class.
2798CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith1c6461e2012-07-18 03:36:00 +00002799 unsigned Quals,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002800 bool RValueThis,
2801 unsigned ThisQuals) {
2802 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2803 "non-const, non-volatile qualifiers for copy assignment this");
2804 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002805 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2806 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002807 ThisQuals & Qualifiers::Const,
2808 ThisQuals & Qualifiers::Volatile);
2809
2810 return Result->getMethod();
2811}
2812
Douglas Gregore71edda2010-07-01 22:47:18 +00002813/// \brief Look for the destructor of the given class.
2814///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00002815/// During semantic analysis, this routine should be used in lieu of
2816/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00002817///
2818/// \returns The destructor for this class.
2819CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002820 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2821 false, false, false,
2822 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00002823}
2824
Richard Smithbcc22fc2012-03-09 08:00:36 +00002825/// LookupLiteralOperator - Determine which literal operator should be used for
2826/// a user-defined literal, per C++11 [lex.ext].
2827///
2828/// Normal overload resolution is not used to select which literal operator to
2829/// call for a user-defined literal. Look up the provided literal operator name,
2830/// and filter the results to the appropriate set for the given argument types.
2831Sema::LiteralOperatorLookupResult
2832Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2833 ArrayRef<QualType> ArgTys,
Richard Smithb8b41d32013-10-07 19:57:58 +00002834 bool AllowRaw, bool AllowTemplate,
2835 bool AllowStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002836 LookupName(R, S);
2837 assert(R.getResultKind() != LookupResult::Ambiguous &&
2838 "literal operator lookup can't be ambiguous");
2839
2840 // Filter the lookup results appropriately.
2841 LookupResult::Filter F = R.makeFilter();
2842
Richard Smithbcc22fc2012-03-09 08:00:36 +00002843 bool FoundRaw = false;
Richard Smithb8b41d32013-10-07 19:57:58 +00002844 bool FoundTemplate = false;
2845 bool FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002846 bool FoundExactMatch = false;
2847
2848 while (F.hasNext()) {
2849 Decl *D = F.next();
2850 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2851 D = USD->getTargetDecl();
2852
Douglas Gregorc1970572013-04-10 05:18:00 +00002853 // If the declaration we found is invalid, skip it.
2854 if (D->isInvalidDecl()) {
2855 F.erase();
2856 continue;
2857 }
2858
Richard Smithb8b41d32013-10-07 19:57:58 +00002859 bool IsRaw = false;
2860 bool IsTemplate = false;
2861 bool IsStringTemplate = false;
2862 bool IsExactMatch = false;
2863
Richard Smithbcc22fc2012-03-09 08:00:36 +00002864 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2865 if (FD->getNumParams() == 1 &&
2866 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2867 IsRaw = true;
Richard Smith550de452013-01-15 07:12:59 +00002868 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002869 IsExactMatch = true;
2870 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2871 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2872 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2873 IsExactMatch = false;
2874 break;
2875 }
2876 }
2877 }
2878 }
Richard Smithb8b41d32013-10-07 19:57:58 +00002879 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
2880 TemplateParameterList *Params = FD->getTemplateParameters();
2881 if (Params->size() == 1)
2882 IsTemplate = true;
2883 else
2884 IsStringTemplate = true;
2885 }
Richard Smithbcc22fc2012-03-09 08:00:36 +00002886
2887 if (IsExactMatch) {
2888 FoundExactMatch = true;
Richard Smithb8b41d32013-10-07 19:57:58 +00002889 AllowRaw = false;
2890 AllowTemplate = false;
2891 AllowStringTemplate = false;
2892 if (FoundRaw || FoundTemplate || FoundStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002893 // Go through again and remove the raw and template decls we've
2894 // already found.
2895 F.restart();
Richard Smithb8b41d32013-10-07 19:57:58 +00002896 FoundRaw = FoundTemplate = FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002897 }
Richard Smithb8b41d32013-10-07 19:57:58 +00002898 } else if (AllowRaw && IsRaw) {
2899 FoundRaw = true;
2900 } else if (AllowTemplate && IsTemplate) {
2901 FoundTemplate = true;
2902 } else if (AllowStringTemplate && IsStringTemplate) {
2903 FoundStringTemplate = true;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002904 } else {
2905 F.erase();
2906 }
2907 }
2908
2909 F.done();
2910
2911 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2912 // parameter type, that is used in preference to a raw literal operator
2913 // or literal operator template.
2914 if (FoundExactMatch)
2915 return LOLR_Cooked;
2916
2917 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2918 // operator template, but not both.
2919 if (FoundRaw && FoundTemplate) {
2920 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
Alp Tokera2794f92014-01-22 07:29:52 +00002921 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2922 NoteOverloadCandidate((*I)->getUnderlyingDecl()->getAsFunction());
Richard Smithbcc22fc2012-03-09 08:00:36 +00002923 return LOLR_Error;
2924 }
2925
2926 if (FoundRaw)
2927 return LOLR_Raw;
2928
2929 if (FoundTemplate)
2930 return LOLR_Template;
2931
Richard Smithb8b41d32013-10-07 19:57:58 +00002932 if (FoundStringTemplate)
2933 return LOLR_StringTemplate;
2934
Richard Smithbcc22fc2012-03-09 08:00:36 +00002935 // Didn't find anything we could use.
2936 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2937 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
Richard Smithb8b41d32013-10-07 19:57:58 +00002938 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
2939 << (AllowTemplate || AllowStringTemplate);
Richard Smithbcc22fc2012-03-09 08:00:36 +00002940 return LOLR_Error;
2941}
2942
John McCall8fe68082010-01-26 07:16:45 +00002943void ADLResult::insert(NamedDecl *New) {
2944 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2945
2946 // If we haven't yet seen a decl for this key, or the last decl
2947 // was exactly this one, we're done.
Craig Topperc3ec1492014-05-26 06:22:03 +00002948 if (Old == nullptr || Old == New) {
John McCall8fe68082010-01-26 07:16:45 +00002949 Old = New;
2950 return;
2951 }
2952
2953 // Otherwise, decide which is a more recent redeclaration.
Alp Tokera2794f92014-01-22 07:29:52 +00002954 FunctionDecl *OldFD = Old->getAsFunction();
2955 FunctionDecl *NewFD = New->getAsFunction();
John McCall8fe68082010-01-26 07:16:45 +00002956
2957 FunctionDecl *Cursor = NewFD;
2958 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002959 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00002960
2961 // If we got to the end without finding OldFD, OldFD is the newer
2962 // declaration; leave things as they are.
2963 if (!Cursor) return;
2964
2965 // If we do find OldFD, then NewFD is newer.
2966 if (Cursor == OldFD) break;
2967
2968 // Otherwise, keep looking.
2969 }
2970
2971 Old = New;
2972}
2973
Richard Smith100b24a2014-04-17 01:52:14 +00002974void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
2975 ArrayRef<Expr *> Args, ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002976 // Find all of the associated namespaces and classes based on the
2977 // arguments we have.
2978 AssociatedNamespaceSet AssociatedNamespaces;
2979 AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00002980 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCallc7e8e792009-08-07 22:18:02 +00002981 AssociatedNamespaces,
2982 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002983
2984 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002985 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2986 // and let Y be the lookup set produced by argument dependent
2987 // lookup (defined as follows). If X contains [...] then Y is
2988 // empty. Otherwise Y is the set of declarations found in the
2989 // namespaces associated with the argument types as described
2990 // below. The set of declarations found by the lookup of the name
2991 // is the union of X and Y.
2992 //
2993 // Here, we compute Y and add its members to the overloaded
2994 // candidate set.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002995 for (auto *NS : AssociatedNamespaces) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002996 // When considering an associated namespace, the lookup is the
2997 // same as the lookup performed when the associated namespace is
2998 // used as a qualifier (3.4.3.2) except that:
2999 //
3000 // -- Any using-directives in the associated namespace are
3001 // ignored.
3002 //
John McCallc7e8e792009-08-07 22:18:02 +00003003 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003004 // associated classes are visible within their respective
3005 // namespaces even if they are not visible during an ordinary
3006 // lookup (11.4).
Aaron Ballman1e606f42014-07-15 22:03:49 +00003007 DeclContext::lookup_result R = NS->lookup(Name);
3008 for (auto *D : R) {
John McCallaa74a0c2009-08-28 07:59:38 +00003009 // If the only declaration here is an ordinary friend, consider
3010 // it only if it was declared in an associated classes.
Richard Smith541b38b2013-09-20 01:15:31 +00003011 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) {
3012 // If it's neither ordinarily visible nor a friend, we can't find it.
3013 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0)
3014 continue;
3015
Richard Smith64017682013-07-17 23:53:16 +00003016 bool DeclaredInAssociatedClass = false;
3017 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
3018 DeclContext *LexDC = DI->getLexicalDeclContext();
3019 if (isa<CXXRecordDecl>(LexDC) &&
3020 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) {
3021 DeclaredInAssociatedClass = true;
3022 break;
3023 }
3024 }
3025 if (!DeclaredInAssociatedClass)
John McCalld1e9d832009-08-11 06:59:38 +00003026 continue;
3027 }
Mike Stump11289f42009-09-09 15:08:12 +00003028
John McCall91f61fc2010-01-26 06:04:06 +00003029 if (isa<UsingShadowDecl>(D))
3030 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00003031
Richard Smith100b24a2014-04-17 01:52:14 +00003032 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D))
John McCall8fe68082010-01-26 07:16:45 +00003033 continue;
3034
3035 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00003036 }
3037 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003038}
Douglas Gregor2d435302009-12-30 17:04:44 +00003039
3040//----------------------------------------------------------------------------
3041// Search for all visible declarations.
3042//----------------------------------------------------------------------------
3043VisibleDeclConsumer::~VisibleDeclConsumer() { }
3044
Richard Smithe156254d2013-08-20 20:35:18 +00003045bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
3046
Douglas Gregor2d435302009-12-30 17:04:44 +00003047namespace {
3048
3049class ShadowContextRAII;
3050
3051class VisibleDeclsRecord {
3052public:
3053 /// \brief An entry in the shadow map, which is optimized to store a
3054 /// single declaration (the common case) but can also store a list
3055 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00003056 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00003057
3058private:
3059 /// \brief A mapping from declaration names to the declarations that have
3060 /// this name within a particular scope.
3061 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
3062
3063 /// \brief A list of shadow maps, which is used to model name hiding.
3064 std::list<ShadowMap> ShadowMaps;
3065
3066 /// \brief The declaration contexts we have already visited.
3067 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
3068
3069 friend class ShadowContextRAII;
3070
3071public:
3072 /// \brief Determine whether we have already visited this context
3073 /// (and, if not, note that we are going to visit that context now).
3074 bool visitedContext(DeclContext *Ctx) {
David Blaikie82e95a32014-11-19 07:49:47 +00003075 return !VisitedContexts.insert(Ctx).second;
Douglas Gregor2d435302009-12-30 17:04:44 +00003076 }
3077
Douglas Gregor39982192010-08-15 06:18:01 +00003078 bool alreadyVisitedContext(DeclContext *Ctx) {
3079 return VisitedContexts.count(Ctx);
3080 }
3081
Douglas Gregor2d435302009-12-30 17:04:44 +00003082 /// \brief Determine whether the given declaration is hidden in the
3083 /// current scope.
3084 ///
3085 /// \returns the declaration that hides the given declaration, or
3086 /// NULL if no such declaration exists.
3087 NamedDecl *checkHidden(NamedDecl *ND);
3088
3089 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00003090 void add(NamedDecl *ND) {
3091 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
3092 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003093};
3094
3095/// \brief RAII object that records when we've entered a shadow context.
3096class ShadowContextRAII {
3097 VisibleDeclsRecord &Visible;
3098
3099 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
3100
3101public:
3102 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
Benjamin Kramer3204b152015-05-29 19:42:19 +00003103 Visible.ShadowMaps.emplace_back();
Douglas Gregor2d435302009-12-30 17:04:44 +00003104 }
3105
3106 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00003107 Visible.ShadowMaps.pop_back();
3108 }
3109};
3110
3111} // end anonymous namespace
3112
Douglas Gregor2d435302009-12-30 17:04:44 +00003113NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00003114 // Look through using declarations.
3115 ND = ND->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003116
Douglas Gregor2d435302009-12-30 17:04:44 +00003117 unsigned IDNS = ND->getIdentifierNamespace();
3118 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
3119 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3120 SM != SMEnd; ++SM) {
3121 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
3122 if (Pos == SM->end())
3123 continue;
3124
Aaron Ballman1e606f42014-07-15 22:03:49 +00003125 for (auto *D : Pos->second) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003126 // A tag declaration does not hide a non-tag declaration.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003127 if (D->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003128 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00003129 Decl::IDNS_ObjCProtocol)))
3130 continue;
3131
3132 // Protocols are in distinct namespaces from everything else.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003133 if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor2d435302009-12-30 17:04:44 +00003134 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Aaron Ballman1e606f42014-07-15 22:03:49 +00003135 D->getIdentifierNamespace() != IDNS)
Douglas Gregor2d435302009-12-30 17:04:44 +00003136 continue;
3137
Douglas Gregor09bbc652010-01-14 15:47:35 +00003138 // Functions and function templates in the same scope overload
3139 // rather than hide. FIXME: Look for hiding based on function
3140 // signatures!
Aaron Ballman1e606f42014-07-15 22:03:49 +00003141 if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Alp Tokera2794f92014-01-22 07:29:52 +00003142 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00003143 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00003144 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003145
Douglas Gregor2d435302009-12-30 17:04:44 +00003146 // We've found a declaration that hides this one.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003147 return D;
Douglas Gregor2d435302009-12-30 17:04:44 +00003148 }
3149 }
3150
Craig Topperc3ec1492014-05-26 06:22:03 +00003151 return nullptr;
Douglas Gregor2d435302009-12-30 17:04:44 +00003152}
3153
3154static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
3155 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003156 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00003157 VisibleDeclConsumer &Consumer,
3158 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00003159 if (!Ctx)
3160 return;
3161
Douglas Gregor2d435302009-12-30 17:04:44 +00003162 // Make sure we don't visit the same context twice.
3163 if (Visited.visitedContext(Ctx->getPrimaryContext()))
3164 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003165
Richard Smith9e2341d2015-03-23 03:25:59 +00003166 // Outside C++, lookup results for the TU live on identifiers.
3167 if (isa<TranslationUnitDecl>(Ctx) &&
3168 !Result.getSema().getLangOpts().CPlusPlus) {
3169 auto &S = Result.getSema();
3170 auto &Idents = S.Context.Idents;
3171
3172 // Ensure all external identifiers are in the identifier table.
3173 if (IdentifierInfoLookup *External = Idents.getExternalIdentifierLookup()) {
3174 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
3175 for (StringRef Name = Iter->Next(); !Name.empty(); Name = Iter->Next())
3176 Idents.get(Name);
3177 }
3178
3179 // Walk all lookup results in the TU for each identifier.
3180 for (const auto &Ident : Idents) {
3181 for (auto I = S.IdResolver.begin(Ident.getValue()),
3182 E = S.IdResolver.end();
3183 I != E; ++I) {
3184 if (S.IdResolver.isDeclInScope(*I, Ctx)) {
3185 if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
3186 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3187 Visited.add(ND);
3188 }
3189 }
3190 }
3191 }
3192
3193 return;
3194 }
3195
Douglas Gregor7454c562010-07-02 20:37:36 +00003196 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3197 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3198
Douglas Gregor2d435302009-12-30 17:04:44 +00003199 // Enumerate all of the results in this context.
Richard Trieu20abd6b2015-04-15 03:48:48 +00003200 for (DeclContextLookupResult R : Ctx->lookups()) {
Richard Smith9e2341d2015-03-23 03:25:59 +00003201 for (auto *D : R) {
3202 if (auto *ND = Result.getAcceptableDecl(D)) {
3203 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3204 Visited.add(ND);
Douglas Gregora3b23b02010-12-09 21:44:02 +00003205 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003206 }
3207 }
3208
3209 // Traverse using directives for qualified name lookup.
3210 if (QualifiedNameLookup) {
3211 ShadowContextRAII Shadow(Visited);
Aaron Ballman804a7fb2014-03-17 17:14:12 +00003212 for (auto I : Ctx->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00003213 LookupVisibleDecls(I->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003214 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003215 }
3216 }
3217
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003218 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00003219 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00003220 if (!Record->hasDefinition())
3221 return;
3222
Aaron Ballman574705e2014-03-13 15:41:46 +00003223 for (const auto &B : Record->bases()) {
3224 QualType BaseType = B.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003225
Douglas Gregor2d435302009-12-30 17:04:44 +00003226 // Don't look into dependent bases, because name lookup can't look
3227 // there anyway.
3228 if (BaseType->isDependentType())
3229 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003230
Douglas Gregor2d435302009-12-30 17:04:44 +00003231 const RecordType *Record = BaseType->getAs<RecordType>();
3232 if (!Record)
3233 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003234
Douglas Gregor2d435302009-12-30 17:04:44 +00003235 // FIXME: It would be nice to be able to determine whether referencing
3236 // a particular member would be ambiguous. For example, given
3237 //
3238 // struct A { int member; };
3239 // struct B { int member; };
3240 // struct C : A, B { };
3241 //
3242 // void f(C *c) { c->### }
3243 //
3244 // accessing 'member' would result in an ambiguity. However, we
3245 // could be smart enough to qualify the member with the base
3246 // class, e.g.,
3247 //
3248 // c->B::member
3249 //
3250 // or
3251 //
3252 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003253
Douglas Gregor2d435302009-12-30 17:04:44 +00003254 // Find results in this base class (and its bases).
3255 ShadowContextRAII Shadow(Visited);
3256 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003257 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003258 }
3259 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003260
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003261 // Traverse the contexts of Objective-C classes.
3262 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3263 // Traverse categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003264 for (auto *Cat : IFace->visible_categories()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003265 ShadowContextRAII Shadow(Visited);
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003266 LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003267 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003268 }
3269
3270 // Traverse protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003271 for (auto *I : IFace->all_referenced_protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003272 ShadowContextRAII Shadow(Visited);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003273 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003274 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003275 }
3276
3277 // Traverse the superclass.
3278 if (IFace->getSuperClass()) {
3279 ShadowContextRAII Shadow(Visited);
3280 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003281 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003282 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003283
Douglas Gregor0b59e802010-04-19 18:02:19 +00003284 // If there is an implementation, traverse it. We do this to find
3285 // synthesized ivars.
3286 if (IFace->getImplementation()) {
3287 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003288 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky13668f22012-04-03 20:26:45 +00003289 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor0b59e802010-04-19 18:02:19 +00003290 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003291 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003292 for (auto *I : Protocol->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003293 ShadowContextRAII Shadow(Visited);
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003294 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003295 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003296 }
3297 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003298 for (auto *I : Category->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003299 ShadowContextRAII Shadow(Visited);
Aaron Ballman19a41762014-03-14 12:55:57 +00003300 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003301 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003302 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003303
Douglas Gregor0b59e802010-04-19 18:02:19 +00003304 // If there is an implementation, traverse it.
3305 if (Category->getImplementation()) {
3306 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003307 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00003308 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003309 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003310 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003311}
3312
3313static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3314 UnqualUsingDirectiveSet &UDirs,
3315 VisibleDeclConsumer &Consumer,
3316 VisibleDeclsRecord &Visited) {
3317 if (!S)
3318 return;
3319
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003320 if (!S->getEntity() ||
3321 (!S->getParent() &&
Ted Kremenekc37877d2013-10-08 17:08:03 +00003322 !Visited.alreadyVisitedContext(S->getEntity())) ||
3323 (S->getEntity())->isFunctionOrMethod()) {
Richard Smith541b38b2013-09-20 01:15:31 +00003324 FindLocalExternScope FindLocals(Result);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003325 // Walk through the declarations in this Scope.
Aaron Ballman35c54952014-03-17 16:55:25 +00003326 for (auto *D : S->decls()) {
3327 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Douglas Gregor4a814562011-12-14 16:03:29 +00003328 if ((ND = Result.getAcceptableDecl(ND))) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003329 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003330 Visited.add(ND);
3331 }
3332 }
3333 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003334
Douglas Gregor66230062010-03-15 14:33:29 +00003335 // FIXME: C++ [temp.local]p8
Craig Topperc3ec1492014-05-26 06:22:03 +00003336 DeclContext *Entity = nullptr;
Douglas Gregor4f248632010-01-01 17:44:25 +00003337 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003338 // Look into this scope's declaration context, along with any of its
3339 // parent lookup contexts (e.g., enclosing classes), up to the point
3340 // where we hit the context stored in the next outer scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00003341 Entity = S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00003342 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003343
Douglas Gregorea166062010-03-15 15:26:48 +00003344 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00003345 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003346 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3347 if (Method->isInstanceMethod()) {
3348 // For instance methods, look for ivars in the method's interface.
3349 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3350 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003351 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003352 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Richard Smithe156254d2013-08-20 20:35:18 +00003353 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003354 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003355 }
3356
3357 // We've already performed all of the name lookup that we need
3358 // to for Objective-C methods; the next context will be the
3359 // outer scope.
3360 break;
3361 }
3362
Douglas Gregor2d435302009-12-30 17:04:44 +00003363 if (Ctx->isFunctionOrMethod())
3364 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003365
3366 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003367 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003368 }
3369 } else if (!S->getParent()) {
3370 // Look into the translation unit scope. We walk through the translation
3371 // unit's declaration context, because the Scope itself won't have all of
3372 // the declarations if we loaded a precompiled header.
3373 // FIXME: We would like the translation unit's Scope object to point to the
3374 // translation unit, so we don't need this special "if" branch. However,
3375 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003376 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00003377 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003378 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00003379 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003380 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003381 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003382 }
3383
Douglas Gregor2d435302009-12-30 17:04:44 +00003384 if (Entity) {
3385 // Lookup visible declarations in any namespaces found by using
3386 // directives.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003387 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
3388 LookupVisibleDecls(const_cast<DeclContext *>(UUE.getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003389 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003390 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003391 }
3392
3393 // Lookup names in the parent scope.
3394 ShadowContextRAII Shadow(Visited);
3395 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3396}
3397
3398void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003399 VisibleDeclConsumer &Consumer,
3400 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003401 // Determine the set of using directives available during
3402 // unqualified name lookup.
3403 Scope *Initial = S;
3404 UnqualUsingDirectiveSet UDirs;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003405 if (getLangOpts().CPlusPlus) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003406 // Find the first namespace or translation-unit scope.
3407 while (S && !isNamespaceOrTranslationUnitScope(S))
3408 S = S->getParent();
3409
3410 UDirs.visitScopeChain(Initial, S);
3411 }
3412 UDirs.done();
3413
3414 // Look for visible declarations.
3415 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003416 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003417 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003418 if (!IncludeGlobalScope)
3419 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003420 ShadowContextRAII Shadow(Visited);
3421 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3422}
3423
3424void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003425 VisibleDeclConsumer &Consumer,
3426 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003427 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003428 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003429 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003430 if (!IncludeGlobalScope)
3431 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003432 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003433 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003434 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003435}
3436
Chris Lattner43e7f312011-02-18 02:08:43 +00003437/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003438/// If GnuLabelLoc is a valid source location, then this is a definition
3439/// of an __label__ label name, otherwise it is a normal label definition
3440/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003441LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003442 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003443 // Do a lookup to see if we have a label with this name already.
Craig Topperc3ec1492014-05-26 06:22:03 +00003444 NamedDecl *Res = nullptr;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003445
3446 if (GnuLabelLoc.isValid()) {
3447 // Local label definitions always shadow existing labels.
3448 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3449 Scope *S = CurScope;
3450 PushOnScopeChains(Res, S, true);
3451 return cast<LabelDecl>(Res);
3452 }
3453
3454 // Not a GNU local label.
3455 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3456 // If we found a label, check to see if it is in the same context as us.
3457 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003458 if (Res && Res->getDeclContext() != CurContext)
Craig Topperc3ec1492014-05-26 06:22:03 +00003459 Res = nullptr;
3460 if (!Res) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003461 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003462 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3463 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003464 assert(S && "Not in a function?");
3465 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003466 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003467 return cast<LabelDecl>(Res);
3468}
3469
3470//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003471// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003472//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003473
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003474static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3475 TypoCorrection &Candidate) {
3476 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3477 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3478}
3479
3480static void LookupPotentialTypoResult(Sema &SemaRef,
3481 LookupResult &Res,
3482 IdentifierInfo *Name,
3483 Scope *S, CXXScopeSpec *SS,
3484 DeclContext *MemberContext,
3485 bool EnteringContext,
3486 bool isObjCIvarLookup,
3487 bool FindHidden);
3488
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003489/// \brief Check whether the declarations found for a typo correction are
3490/// visible, and if none of them are, convert the correction to an 'import
3491/// a module' correction.
3492static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
3493 if (TC.begin() == TC.end())
3494 return;
3495
3496 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3497
3498 for (/**/; DI != DE; ++DI)
3499 if (!LookupResult::isVisible(SemaRef, *DI))
3500 break;
3501 // Nothing to do if all decls are visible.
3502 if (DI == DE)
3503 return;
3504
3505 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3506 bool AnyVisibleDecls = !NewDecls.empty();
3507
3508 for (/**/; DI != DE; ++DI) {
3509 NamedDecl *VisibleDecl = *DI;
3510 if (!LookupResult::isVisible(SemaRef, *DI))
3511 VisibleDecl = findAcceptableDecl(SemaRef, *DI);
3512
3513 if (VisibleDecl) {
3514 if (!AnyVisibleDecls) {
3515 // Found a visible decl, discard all hidden ones.
3516 AnyVisibleDecls = true;
3517 NewDecls.clear();
3518 }
3519 NewDecls.push_back(VisibleDecl);
3520 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
3521 NewDecls.push_back(*DI);
3522 }
3523
3524 if (NewDecls.empty())
3525 TC = TypoCorrection();
3526 else {
3527 TC.setCorrectionDecls(NewDecls);
3528 TC.setRequiresImport(!AnyVisibleDecls);
3529 }
3530}
3531
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003532// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3533// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3534// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3535static void getNestedNameSpecifierIdentifiers(
3536 NestedNameSpecifier *NNS,
3537 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3538 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3539 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3540 else
3541 Identifiers.clear();
3542
3543 const IdentifierInfo *II = nullptr;
3544
3545 switch (NNS->getKind()) {
3546 case NestedNameSpecifier::Identifier:
3547 II = NNS->getAsIdentifier();
3548 break;
3549
3550 case NestedNameSpecifier::Namespace:
3551 if (NNS->getAsNamespace()->isAnonymousNamespace())
3552 return;
3553 II = NNS->getAsNamespace()->getIdentifier();
3554 break;
3555
3556 case NestedNameSpecifier::NamespaceAlias:
3557 II = NNS->getAsNamespaceAlias()->getIdentifier();
3558 break;
3559
3560 case NestedNameSpecifier::TypeSpecWithTemplate:
3561 case NestedNameSpecifier::TypeSpec:
3562 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3563 break;
3564
3565 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00003566 case NestedNameSpecifier::Super:
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003567 return;
3568 }
3569
3570 if (II)
3571 Identifiers.push_back(II);
3572}
3573
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003574void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003575 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003576 // Don't consider hidden names for typo correction.
3577 if (Hiding)
3578 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003579
Douglas Gregor2d435302009-12-30 17:04:44 +00003580 // Only consider entities with identifiers for names, ignoring
3581 // special names (constructors, overloaded operators, selectors,
3582 // etc.).
3583 IdentifierInfo *Name = ND->getIdentifier();
3584 if (!Name)
3585 return;
3586
Richard Smithe156254d2013-08-20 20:35:18 +00003587 // Only consider visible declarations and declarations from modules with
3588 // names that exactly match.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003589 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo &&
Richard Smithe156254d2013-08-20 20:35:18 +00003590 !findAcceptableDecl(SemaRef, ND))
3591 return;
3592
Douglas Gregor57756ea2010-10-14 22:11:03 +00003593 FoundName(Name->getName());
3594}
3595
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003596void TypoCorrectionConsumer::FoundName(StringRef Name) {
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003597 // Compute the edit distance between the typo and the name of this
3598 // entity, and add the identifier to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003599 addName(Name, nullptr);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003600}
3601
3602void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3603 // Compute the edit distance between the typo and this keyword,
3604 // and add the keyword to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003605 addName(Keyword, nullptr, nullptr, true);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003606}
3607
3608void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
3609 NestedNameSpecifier *NNS, bool isKeyword) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003610 // Use a simple length-based heuristic to determine the minimum possible
3611 // edit distance. If the minimum isn't good enough, bail out early.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003612 StringRef TypoStr = Typo->getName();
3613 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
3614 if (MinED && TypoStr.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00003615 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003616
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003617 // Compute an upper bound on the allowable edit distance, so that the
3618 // edit-distance algorithm can short-circuit.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003619 unsigned UpperBound = (TypoStr.size() + 2) / 3 + 1;
3620 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003621 if (ED >= UpperBound) return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003622
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003623 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003624 if (isKeyword) TC.makeKeyword();
Kaelyn Takata0a313022014-11-20 22:06:26 +00003625 TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003626 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003627}
3628
Kaelyn Takatad2287c32014-10-27 18:07:13 +00003629static const unsigned MaxTypoDistanceResultSets = 5;
3630
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003631void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003632 StringRef TypoStr = Typo->getName();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003633 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003634
3635 // For very short typos, ignore potential corrections that have a different
3636 // base identifier from the typo or which have a normalized edit distance
3637 // longer than the typo itself.
3638 if (TypoStr.size() < 3 &&
3639 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
3640 return;
3641
3642 // If the correction is resolved but is not viable, ignore it.
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003643 if (Correction.isResolved()) {
3644 checkCorrectionVisibility(SemaRef, Correction);
3645 if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
3646 return;
3647 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003648
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003649 TypoResultList &CList =
3650 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003651
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003652 if (!CList.empty() && !CList.back().isResolved())
3653 CList.pop_back();
3654 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3655 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3656 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3657 RI != RIEnd; ++RI) {
3658 // If the Correction refers to a decl already in the result list,
3659 // replace the existing result if the string representation of Correction
3660 // comes before the current result alphabetically, then stop as there is
3661 // nothing more to be done to add Correction to the candidate set.
3662 if (RI->getCorrectionDecl() == NewND) {
3663 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3664 *RI = Correction;
3665 return;
3666 }
3667 }
3668 }
3669 if (CList.empty() || Correction.isResolved())
3670 CList.push_back(Correction);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003671
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003672 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003673 CorrectionResults.erase(std::prev(CorrectionResults.end()));
3674}
3675
3676void TypoCorrectionConsumer::addNamespaces(
3677 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
3678 SearchNamespaces = true;
3679
3680 for (auto KNPair : KnownNamespaces)
3681 Namespaces.addNameSpecifier(KNPair.first);
3682
3683 bool SSIsTemplate = false;
3684 if (NestedNameSpecifier *NNS =
3685 (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
3686 if (const Type *T = NNS->getAsType())
3687 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
3688 }
3689 for (const auto *TI : SemaRef.getASTContext().types()) {
3690 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
3691 CD = CD->getCanonicalDecl();
3692 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
3693 !CD->isUnion() && CD->getIdentifier() &&
3694 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
3695 (CD->isBeingDefined() || CD->isCompleteDefinition()))
3696 Namespaces.addNameSpecifier(CD);
3697 }
3698 }
3699}
3700
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003701const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
3702 if (++CurrentTCIndex < ValidatedCorrections.size())
3703 return ValidatedCorrections[CurrentTCIndex];
3704
3705 CurrentTCIndex = ValidatedCorrections.size();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003706 while (!CorrectionResults.empty()) {
3707 auto DI = CorrectionResults.begin();
3708 if (DI->second.empty()) {
3709 CorrectionResults.erase(DI);
3710 continue;
3711 }
3712
3713 auto RI = DI->second.begin();
3714 if (RI->second.empty()) {
3715 DI->second.erase(RI);
3716 performQualifiedLookups();
3717 continue;
3718 }
3719
3720 TypoCorrection TC = RI->second.pop_back_val();
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003721 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003722 ValidatedCorrections.push_back(TC);
3723 return ValidatedCorrections[CurrentTCIndex];
3724 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003725 }
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003726 return ValidatedCorrections[0]; // The empty correction.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003727}
3728
3729bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
3730 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
3731 DeclContext *TempMemberContext = MemberContext;
Kaelyn Takata6c759512014-10-27 18:07:37 +00003732 CXXScopeSpec *TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003733retry_lookup:
3734 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
3735 EnteringContext,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00003736 CorrectionValidator->IsObjCIvarLookup,
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003737 Name == Typo && !Candidate.WillReplaceSpecifier());
3738 switch (Result.getResultKind()) {
3739 case LookupResult::NotFound:
3740 case LookupResult::NotFoundInCurrentInstantiation:
3741 case LookupResult::FoundUnresolvedValue:
3742 if (TempSS) {
3743 // Immediately retry the lookup without the given CXXScopeSpec
3744 TempSS = nullptr;
3745 Candidate.WillReplaceSpecifier(true);
3746 goto retry_lookup;
3747 }
3748 if (TempMemberContext) {
3749 if (SS && !TempSS)
Kaelyn Takata6c759512014-10-27 18:07:37 +00003750 TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003751 TempMemberContext = nullptr;
3752 goto retry_lookup;
3753 }
3754 if (SearchNamespaces)
3755 QualifiedResults.push_back(Candidate);
3756 break;
3757
3758 case LookupResult::Ambiguous:
3759 // We don't deal with ambiguities.
3760 break;
3761
3762 case LookupResult::Found:
3763 case LookupResult::FoundOverloaded:
3764 // Store all of the Decls for overloaded symbols
3765 for (auto *TRD : Result)
3766 Candidate.addCorrectionDecl(TRD);
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003767 checkCorrectionVisibility(SemaRef, Candidate);
Kaelyn Takata89c881b2014-10-27 18:07:29 +00003768 if (!isCandidateViable(*CorrectionValidator, Candidate)) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003769 if (SearchNamespaces)
3770 QualifiedResults.push_back(Candidate);
3771 break;
3772 }
Kaelyn Takata20deb1d2015-01-28 00:46:09 +00003773 Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003774 return true;
3775 }
3776 return false;
3777}
3778
3779void TypoCorrectionConsumer::performQualifiedLookups() {
3780 unsigned TypoLen = Typo->getName().size();
3781 for (auto QR : QualifiedResults) {
3782 for (auto NSI : Namespaces) {
3783 DeclContext *Ctx = NSI.DeclCtx;
3784 const Type *NSType = NSI.NameSpecifier->getAsType();
3785
3786 // If the current NestedNameSpecifier refers to a class and the
3787 // current correction candidate is the name of that class, then skip
3788 // it as it is unlikely a qualified version of the class' constructor
3789 // is an appropriate correction.
3790 if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() : 0) {
3791 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
3792 continue;
3793 }
3794
3795 TypoCorrection TC(QR);
3796 TC.ClearCorrectionDecls();
3797 TC.setCorrectionSpecifier(NSI.NameSpecifier);
3798 TC.setQualifierDistance(NSI.EditDistance);
3799 TC.setCallbackDistance(0); // Reset the callback distance
3800
3801 // If the current correction candidate and namespace combination are
3802 // too far away from the original typo based on the normalized edit
3803 // distance, then skip performing a qualified name lookup.
3804 unsigned TmpED = TC.getEditDistance(true);
3805 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
3806 TypoLen / TmpED < 3)
3807 continue;
3808
3809 Result.clear();
3810 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
3811 if (!SemaRef.LookupQualifiedName(Result, Ctx))
3812 continue;
3813
3814 // Any corrections added below will be validated in subsequent
3815 // iterations of the main while() loop over the Consumer's contents.
3816 switch (Result.getResultKind()) {
3817 case LookupResult::Found:
3818 case LookupResult::FoundOverloaded: {
3819 if (SS && SS->isValid()) {
3820 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
3821 std::string OldQualified;
3822 llvm::raw_string_ostream OldOStream(OldQualified);
3823 SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
3824 OldOStream << Typo->getName();
3825 // If correction candidate would be an identical written qualified
3826 // identifer, then the existing CXXScopeSpec probably included a
3827 // typedef that didn't get accounted for properly.
3828 if (OldOStream.str() == NewQualified)
3829 break;
3830 }
3831 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
3832 TRD != TRDEnd; ++TRD) {
3833 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
3834 NSType ? NSType->getAsCXXRecordDecl()
3835 : nullptr,
3836 TRD.getPair()) == Sema::AR_accessible)
3837 TC.addCorrectionDecl(*TRD);
3838 }
Kaelyn Takata0a313022014-11-20 22:06:26 +00003839 if (TC.isResolved()) {
3840 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003841 addCorrection(TC);
Kaelyn Takata0a313022014-11-20 22:06:26 +00003842 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003843 break;
3844 }
3845 case LookupResult::NotFound:
3846 case LookupResult::NotFoundInCurrentInstantiation:
3847 case LookupResult::Ambiguous:
3848 case LookupResult::FoundUnresolvedValue:
3849 break;
3850 }
3851 }
3852 }
3853 QualifiedResults.clear();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003854}
3855
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00003856TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
3857 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
Benjamin Kramer15537272015-03-13 16:10:42 +00003858 : Context(Context), CurContextChain(buildContextChain(CurContext)) {
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00003859 if (NestedNameSpecifier *NNS =
3860 CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
3861 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
3862 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3863
3864 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
3865 }
3866 // Build the list of identifiers that would be used for an absolute
3867 // (from the global context) NestedNameSpecifier referring to the current
3868 // context.
3869 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3870 CEnd = CurContextChain.rend();
3871 C != CEnd; ++C) {
3872 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3873 CurContextIdentifiers.push_back(ND->getIdentifier());
3874 }
3875
3876 // Add the global context as a NestedNameSpecifier
Hans Wennborg66010132014-06-11 21:24:13 +00003877 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
3878 NestedNameSpecifier::GlobalSpecifier(Context), 1};
3879 DistanceMap[1].push_back(SI);
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00003880}
3881
Kaelyn Takata7dcc0e62014-06-11 18:07:08 +00003882auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
3883 DeclContext *Start) -> DeclContextList {
Nick Lewycky0d9b3192013-04-08 21:55:21 +00003884 assert(Start && "Building a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003885 DeclContextList Chain;
Craig Topperc3ec1492014-05-26 06:22:03 +00003886 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003887 DC = DC->getLookupParent()) {
3888 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3889 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3890 !(ND && ND->isAnonymousNamespace()))
3891 Chain.push_back(DC->getPrimaryContext());
3892 }
3893 return Chain;
3894}
3895
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003896unsigned
3897TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
3898 DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003899 unsigned NumSpecifiers = 0;
3900 for (DeclContextList::reverse_iterator C = DeclChain.rbegin(),
3901 CEnd = DeclChain.rend();
3902 C != CEnd; ++C) {
3903 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) {
3904 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3905 ++NumSpecifiers;
3906 } else if (RecordDecl *RD = dyn_cast_or_null<RecordDecl>(*C)) {
3907 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
3908 RD->getTypeForDecl());
3909 ++NumSpecifiers;
3910 }
3911 }
3912 return NumSpecifiers;
3913}
3914
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003915void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
3916 DeclContext *Ctx) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003917 NestedNameSpecifier *NNS = nullptr;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003918 unsigned NumSpecifiers = 0;
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003919 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003920 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
3921
3922 // Eliminate common elements from the two DeclContext chains.
3923 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3924 CEnd = CurContextChain.rend();
3925 C != CEnd && !NamespaceDeclChain.empty() &&
3926 NamespaceDeclChain.back() == *C; ++C) {
3927 NamespaceDeclChain.pop_back();
3928 }
3929
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003930 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003931 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003932
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003933 // Add an explicit leading '::' specifier if needed.
3934 if (NamespaceDeclChain.empty()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003935 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003936 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003937 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003938 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003939 } else if (NamedDecl *ND =
3940 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003941 IdentifierInfo *Name = ND->getIdentifier();
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003942 bool SameNameSpecifier = false;
3943 if (std::find(CurNameSpecifierIdentifiers.begin(),
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003944 CurNameSpecifierIdentifiers.end(),
3945 Name) != CurNameSpecifierIdentifiers.end()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003946 std::string NewNameSpecifier;
3947 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
3948 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
3949 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3950 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3951 SpecifierOStream.flush();
3952 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003953 }
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003954 if (SameNameSpecifier ||
3955 std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3956 Name) != CurContextIdentifiers.end()) {
3957 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
3958 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3959 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003960 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003961 }
3962 }
3963
3964 // If the built NestedNameSpecifier would be replacing an existing
3965 // NestedNameSpecifier, use the number of component identifiers that
3966 // would need to be changed as the edit distance instead of the number
3967 // of components in the built NestedNameSpecifier.
3968 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3969 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3970 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3971 NumSpecifiers = llvm::ComputeEditDistance(
Craig Topper8c2a2a02014-08-30 16:55:39 +00003972 llvm::makeArrayRef(CurNameSpecifierIdentifiers),
3973 llvm::makeArrayRef(NewNameSpecifierIdentifiers));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003974 }
3975
Hans Wennborg66010132014-06-11 21:24:13 +00003976 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
3977 DistanceMap[NumSpecifiers].push_back(SI);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003978}
3979
Douglas Gregord507d772010-10-20 03:06:34 +00003980/// \brief Perform name lookup for a possible result for typo correction.
3981static void LookupPotentialTypoResult(Sema &SemaRef,
3982 LookupResult &Res,
3983 IdentifierInfo *Name,
3984 Scope *S, CXXScopeSpec *SS,
3985 DeclContext *MemberContext,
3986 bool EnteringContext,
Richard Smithe156254d2013-08-20 20:35:18 +00003987 bool isObjCIvarLookup,
3988 bool FindHidden) {
Douglas Gregord507d772010-10-20 03:06:34 +00003989 Res.suppressDiagnostics();
3990 Res.clear();
3991 Res.setLookupName(Name);
Richard Smithe156254d2013-08-20 20:35:18 +00003992 Res.setAllowHidden(FindHidden);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003993 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00003994 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003995 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00003996 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3997 Res.addDecl(Ivar);
3998 Res.resolveKind();
3999 return;
4000 }
4001 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004002
Douglas Gregord507d772010-10-20 03:06:34 +00004003 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
4004 Res.addDecl(Prop);
4005 Res.resolveKind();
4006 return;
4007 }
4008 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004009
Douglas Gregord507d772010-10-20 03:06:34 +00004010 SemaRef.LookupQualifiedName(Res, MemberContext);
4011 return;
4012 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004013
4014 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00004015 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004016
Douglas Gregord507d772010-10-20 03:06:34 +00004017 // Fake ivar lookup; this should really be part of
4018 // LookupParsedName.
4019 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
4020 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004021 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00004022 (Res.isSingleResult() &&
4023 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004024 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00004025 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
4026 Res.addDecl(IV);
4027 Res.resolveKind();
4028 }
4029 }
4030 }
4031}
4032
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004033/// \brief Add keywords to the consumer as possible typo corrections.
4034static void AddKeywordsToConsumer(Sema &SemaRef,
4035 TypoCorrectionConsumer &Consumer,
Richard Smithb3a1df02012-06-08 21:35:42 +00004036 Scope *S, CorrectionCandidateCallback &CCC,
4037 bool AfterNestedNameSpecifier) {
4038 if (AfterNestedNameSpecifier) {
4039 // For 'X::', we know exactly which keywords can appear next.
4040 Consumer.addKeywordResult("template");
4041 if (CCC.WantExpressionKeywords)
4042 Consumer.addKeywordResult("operator");
4043 return;
4044 }
4045
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004046 if (CCC.WantObjCSuper)
4047 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004048
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004049 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004050 // Add type-specifier keywords to the set of results.
Craig Topperd6d31ac2013-07-15 08:24:27 +00004051 static const char *const CTypeSpecs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004052 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00004053 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004054 "_Complex", "_Imaginary",
4055 // storage-specifiers as well
4056 "extern", "inline", "static", "typedef"
4057 };
4058
Craig Toppere5ce8312013-07-15 03:38:40 +00004059 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004060 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
4061 Consumer.addKeywordResult(CTypeSpecs[I]);
4062
David Blaikiebbafb8a2012-03-11 07:00:24 +00004063 if (SemaRef.getLangOpts().C99)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004064 Consumer.addKeywordResult("restrict");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004065 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004066 Consumer.addKeywordResult("bool");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004067 else if (SemaRef.getLangOpts().C99)
Douglas Gregor3b22a882011-07-01 21:27:45 +00004068 Consumer.addKeywordResult("_Bool");
4069
David Blaikiebbafb8a2012-03-11 07:00:24 +00004070 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004071 Consumer.addKeywordResult("class");
4072 Consumer.addKeywordResult("typename");
4073 Consumer.addKeywordResult("wchar_t");
4074
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004075 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004076 Consumer.addKeywordResult("char16_t");
4077 Consumer.addKeywordResult("char32_t");
4078 Consumer.addKeywordResult("constexpr");
4079 Consumer.addKeywordResult("decltype");
4080 Consumer.addKeywordResult("thread_local");
4081 }
4082 }
4083
David Blaikiebbafb8a2012-03-11 07:00:24 +00004084 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004085 Consumer.addKeywordResult("typeof");
Kaelyn Takatab04846b2014-07-28 18:14:02 +00004086 } else if (CCC.WantFunctionLikeCasts) {
4087 static const char *const CastableTypeSpecs[] = {
4088 "char", "double", "float", "int", "long", "short",
4089 "signed", "unsigned", "void"
4090 };
4091 for (auto *kw : CastableTypeSpecs)
4092 Consumer.addKeywordResult(kw);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004093 }
4094
David Blaikiebbafb8a2012-03-11 07:00:24 +00004095 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004096 Consumer.addKeywordResult("const_cast");
4097 Consumer.addKeywordResult("dynamic_cast");
4098 Consumer.addKeywordResult("reinterpret_cast");
4099 Consumer.addKeywordResult("static_cast");
4100 }
4101
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004102 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004103 Consumer.addKeywordResult("sizeof");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004104 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004105 Consumer.addKeywordResult("false");
4106 Consumer.addKeywordResult("true");
4107 }
4108
David Blaikiebbafb8a2012-03-11 07:00:24 +00004109 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topperd6d31ac2013-07-15 08:24:27 +00004110 static const char *const CXXExprs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004111 "delete", "new", "operator", "throw", "typeid"
4112 };
Craig Toppere5ce8312013-07-15 03:38:40 +00004113 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004114 for (unsigned I = 0; I != NumCXXExprs; ++I)
4115 Consumer.addKeywordResult(CXXExprs[I]);
4116
4117 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
4118 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
4119 Consumer.addKeywordResult("this");
4120
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004121 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004122 Consumer.addKeywordResult("alignof");
4123 Consumer.addKeywordResult("nullptr");
4124 }
4125 }
Jordan Rose58d54722012-06-30 21:33:57 +00004126
4127 if (SemaRef.getLangOpts().C11) {
4128 // FIXME: We should not suggest _Alignof if the alignof macro
4129 // is present.
4130 Consumer.addKeywordResult("_Alignof");
4131 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004132 }
4133
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004134 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004135 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
4136 // Statements.
Craig Topperd6d31ac2013-07-15 08:24:27 +00004137 static const char *const CStmts[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004138 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Toppere5ce8312013-07-15 03:38:40 +00004139 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004140 for (unsigned I = 0; I != NumCStmts; ++I)
4141 Consumer.addKeywordResult(CStmts[I]);
4142
David Blaikiebbafb8a2012-03-11 07:00:24 +00004143 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004144 Consumer.addKeywordResult("catch");
4145 Consumer.addKeywordResult("try");
4146 }
4147
4148 if (S && S->getBreakParent())
4149 Consumer.addKeywordResult("break");
4150
4151 if (S && S->getContinueParent())
4152 Consumer.addKeywordResult("continue");
4153
4154 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
4155 Consumer.addKeywordResult("case");
4156 Consumer.addKeywordResult("default");
4157 }
4158 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004159 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004160 Consumer.addKeywordResult("namespace");
4161 Consumer.addKeywordResult("template");
4162 }
4163
4164 if (S && S->isClassScope()) {
4165 Consumer.addKeywordResult("explicit");
4166 Consumer.addKeywordResult("friend");
4167 Consumer.addKeywordResult("mutable");
4168 Consumer.addKeywordResult("private");
4169 Consumer.addKeywordResult("protected");
4170 Consumer.addKeywordResult("public");
4171 Consumer.addKeywordResult("virtual");
4172 }
4173 }
4174
David Blaikiebbafb8a2012-03-11 07:00:24 +00004175 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004176 Consumer.addKeywordResult("using");
4177
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004178 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004179 Consumer.addKeywordResult("static_assert");
4180 }
4181 }
4182}
4183
Kaelyn Takata6c759512014-10-27 18:07:37 +00004184std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
4185 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4186 Scope *S, CXXScopeSpec *SS,
4187 std::unique_ptr<CorrectionCandidateCallback> CCC,
4188 DeclContext *MemberContext, bool EnteringContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004189 const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00004190
4191 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4192 DisableTypoCorrection)
4193 return nullptr;
4194
4195 // In Microsoft mode, don't perform typo correction in a template member
4196 // function dependent context because it interferes with the "lookup into
4197 // dependent bases of class templates" feature.
4198 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
4199 isa<CXXMethodDecl>(CurContext))
4200 return nullptr;
4201
4202 // We only attempt to correct typos for identifiers.
4203 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4204 if (!Typo)
4205 return nullptr;
4206
4207 // If the scope specifier itself was invalid, don't try to correct
4208 // typos.
4209 if (SS && SS->isInvalid())
4210 return nullptr;
4211
4212 // Never try to correct typos during template deduction or
4213 // instantiation.
4214 if (!ActiveTemplateInstantiations.empty())
4215 return nullptr;
4216
4217 // Don't try to correct 'super'.
4218 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4219 return nullptr;
4220
4221 // Abort if typo correction already failed for this specific typo.
4222 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4223 if (locs != TypoCorrectionFailures.end() &&
4224 locs->second.count(TypoName.getLoc()))
4225 return nullptr;
4226
4227 // Don't try to correct the identifier "vector" when in AltiVec mode.
4228 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4229 // remove this workaround.
4230 if (getLangOpts().AltiVec && Typo->isStr("vector"))
4231 return nullptr;
4232
Nick Lewycky24653262014-12-16 21:39:02 +00004233 // Provide a stop gap for files that are just seriously broken. Trying
4234 // to correct all typos can turn into a HUGE performance penalty, causing
4235 // some files to take minutes to get rejected by the parser.
4236 unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
4237 if (Limit && TyposCorrected >= Limit)
4238 return nullptr;
4239 ++TyposCorrected;
4240
Kaelyn Takata6c759512014-10-27 18:07:37 +00004241 // If we're handling a missing symbol error, using modules, and the
4242 // special search all modules option is used, look for a missing import.
4243 if (ErrorRecovery && getLangOpts().Modules &&
4244 getLangOpts().ModulesSearchAll) {
4245 // The following has the side effect of loading the missing module.
4246 getModuleLoader().lookupMissingImports(Typo->getName(),
4247 TypoName.getLocStart());
4248 }
4249
4250 CorrectionCandidateCallback &CCCRef = *CCC;
4251 auto Consumer = llvm::make_unique<TypoCorrectionConsumer>(
4252 *this, TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
4253 EnteringContext);
4254
Kaelyn Takata6c759512014-10-27 18:07:37 +00004255 // Perform name lookup to find visible, similarly-named entities.
Nick Lewycky24653262014-12-16 21:39:02 +00004256 bool IsUnqualifiedLookup = false;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004257 DeclContext *QualifiedDC = MemberContext;
4258 if (MemberContext) {
4259 LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
4260
4261 // Look in qualified interfaces.
4262 if (OPT) {
4263 for (auto *I : OPT->quals())
4264 LookupVisibleDecls(I, LookupKind, *Consumer);
4265 }
4266 } else if (SS && SS->isSet()) {
4267 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4268 if (!QualifiedDC)
4269 return nullptr;
4270
Kaelyn Takata6c759512014-10-27 18:07:37 +00004271 LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
4272 } else {
4273 IsUnqualifiedLookup = true;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004274 }
4275
4276 // Determine whether we are going to search in the various namespaces for
4277 // corrections.
4278 bool SearchNamespaces
4279 = getLangOpts().CPlusPlus &&
4280 (IsUnqualifiedLookup || (SS && SS->isSet()));
4281
4282 if (IsUnqualifiedLookup || SearchNamespaces) {
4283 // For unqualified lookup, look through all of the names that we have
4284 // seen in this translation unit.
4285 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4286 for (const auto &I : Context.Idents)
4287 Consumer->FoundName(I.getKey());
4288
4289 // Walk through identifiers in external identifier sources.
4290 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4291 if (IdentifierInfoLookup *External
4292 = Context.Idents.getExternalIdentifierLookup()) {
4293 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4294 do {
4295 StringRef Name = Iter->Next();
4296 if (Name.empty())
4297 break;
4298
4299 Consumer->FoundName(Name);
4300 } while (true);
4301 }
4302 }
4303
4304 AddKeywordsToConsumer(*this, *Consumer, S, CCCRef, SS && SS->isNotEmpty());
4305
4306 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4307 // to search those namespaces.
4308 if (SearchNamespaces) {
4309 // Load any externally-known namespaces.
4310 if (ExternalSource && !LoadedExternalKnownNamespaces) {
4311 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
4312 LoadedExternalKnownNamespaces = true;
4313 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4314 for (auto *N : ExternalKnownNamespaces)
4315 KnownNamespaces[N] = true;
4316 }
4317
4318 Consumer->addNamespaces(KnownNamespaces);
4319 }
4320
4321 return Consumer;
4322}
4323
Douglas Gregor2d435302009-12-30 17:04:44 +00004324/// \brief Try to "correct" a typo in the source code by finding
4325/// visible declarations whose names are similar to the name that was
4326/// present in the source code.
4327///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004328/// \param TypoName the \c DeclarationNameInfo structure that contains
4329/// the name that was present in the source code along with its location.
4330///
4331/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00004332///
4333/// \param S the scope in which name lookup occurs.
4334///
4335/// \param SS the nested-name-specifier that precedes the name we're
4336/// looking for, if present.
4337///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004338/// \param CCC A CorrectionCandidateCallback object that provides further
4339/// validation of typo correction candidates. It also provides flags for
4340/// determining the set of keywords permitted.
4341///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00004342/// \param MemberContext if non-NULL, the context in which to look for
4343/// a member access expression.
4344///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004345/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00004346/// the nested-name-specifier SS.
4347///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004348/// \param OPT when non-NULL, the search for visible declarations will
4349/// also walk the protocols in the qualified interfaces of \p OPT.
4350///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004351/// \returns a \c TypoCorrection containing the corrected name if the typo
4352/// along with information such as the \c NamedDecl where the corrected name
4353/// was declared, and any additional \c NestedNameSpecifier needed to access
4354/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
4355TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
4356 Sema::LookupNameKind LookupKind,
4357 Scope *S, CXXScopeSpec *SS,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004358 std::unique_ptr<CorrectionCandidateCallback> CCC,
John Thompson2255f2c2014-04-23 12:57:01 +00004359 CorrectTypoKind Mode,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004360 DeclContext *MemberContext,
4361 bool EnteringContext,
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004362 const ObjCObjectPointerType *OPT,
4363 bool RecordFailure) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004364 assert(CCC && "CorrectTypo requires a CorrectionCandidateCallback");
4365
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004366 // Always let the ExternalSource have the first chance at correction, even
4367 // if we would otherwise have given up.
4368 if (ExternalSource) {
4369 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004370 TypoName, LookupKind, S, SS, *CCC, MemberContext, EnteringContext, OPT))
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004371 return Correction;
4372 }
4373
Kaelyn Takata6c759512014-10-27 18:07:37 +00004374 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4375 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4376 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4377 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
4378 bool ObjCMessageReceiver = CCC->WantObjCSuper && !CCC->WantRemainingKeywords;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004379
Kaelyn Takata6c759512014-10-27 18:07:37 +00004380 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Kaelyn Takata6c759512014-10-27 18:07:37 +00004381 auto Consumer = makeTypoCorrectionConsumer(
4382 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004383 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004384
Kaelyn Takata6c759512014-10-27 18:07:37 +00004385 if (!Consumer)
4386 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004387
Douglas Gregor280e1ee2010-04-14 20:04:41 +00004388 // If we haven't found anything, we're done.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004389 if (Consumer->empty())
Nick Lewycky24653262014-12-16 21:39:02 +00004390 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregor2d435302009-12-30 17:04:44 +00004391
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004392 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4393 // is not more that about a third of the length of the typo's identifier.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004394 unsigned ED = Consumer->getBestEditDistance(true);
4395 unsigned TypoLen = Typo->getName().size();
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004396 if (ED > 0 && TypoLen / ED < 3)
Nick Lewycky24653262014-12-16 21:39:02 +00004397 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004398
Kaelyn Takata6c759512014-10-27 18:07:37 +00004399 TypoCorrection BestTC = Consumer->getNextCorrection();
4400 TypoCorrection SecondBestTC = Consumer->getNextCorrection();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004401 if (!BestTC)
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004402 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004403
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004404 ED = BestTC.getEditDistance();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004405
Kaelyn Takata6c759512014-10-27 18:07:37 +00004406 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004407 // If this was an unqualified lookup and we believe the callback
4408 // object wouldn't have filtered out possible corrections, note
4409 // that no correction was found.
Nick Lewycky24653262014-12-16 21:39:02 +00004410 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004411 }
4412
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004413 // If only a single name remains, return that result.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004414 if (!SecondBestTC ||
4415 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
4416 const TypoCorrection &Result = BestTC;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004417
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00004418 // Don't correct to a keyword that's the same as the typo; the keyword
4419 // wasn't actually in scope.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004420 if (ED == 0 && Result.isKeyword())
4421 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004422
David Blaikie04ea41c2012-10-12 20:00:44 +00004423 TypoCorrection TC = Result;
4424 TC.setCorrectionRange(SS, TypoName);
Kaelyn Takataa95ebc62014-06-17 23:47:29 +00004425 checkCorrectionVisibility(*this, TC);
David Blaikie04ea41c2012-10-12 20:00:44 +00004426 return TC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004427 } else if (SecondBestTC && ObjCMessageReceiver) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004428 // Prefer 'super' when we're completing in a message-receiver
4429 // context.
4430
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004431 if (BestTC.getCorrection().getAsString() != "super") {
4432 if (SecondBestTC.getCorrection().getAsString() == "super")
4433 BestTC = SecondBestTC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004434 else if ((*Consumer)["super"].front().isKeyword())
4435 BestTC = (*Consumer)["super"].front();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004436 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004437 // Don't correct to a keyword that's the same as the typo; the keyword
4438 // wasn't actually in scope.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004439 if (BestTC.getEditDistance() == 0 ||
4440 BestTC.getCorrection().getAsString() != "super")
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004441 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004442
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004443 BestTC.setCorrectionRange(SS, TypoName);
4444 return BestTC;
Douglas Gregoraf9eb592010-10-15 13:35:25 +00004445 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004446
Kaelyn Takata73429fd2014-06-10 21:03:49 +00004447 // Record the failure's location if needed and return an empty correction. If
4448 // this was an unqualified lookup and we believe the callback object did not
4449 // filter out possible corrections, also cache the failure for the typo.
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004450 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004451}
4452
Kaelyn Takata6c759512014-10-27 18:07:37 +00004453/// \brief Try to "correct" a typo in the source code by finding
4454/// visible declarations whose names are similar to the name that was
4455/// present in the source code.
4456///
4457/// \param TypoName the \c DeclarationNameInfo structure that contains
4458/// the name that was present in the source code along with its location.
4459///
4460/// \param LookupKind the name-lookup criteria used to search for the name.
4461///
4462/// \param S the scope in which name lookup occurs.
4463///
4464/// \param SS the nested-name-specifier that precedes the name we're
4465/// looking for, if present.
4466///
4467/// \param CCC A CorrectionCandidateCallback object that provides further
4468/// validation of typo correction candidates. It also provides flags for
4469/// determining the set of keywords permitted.
4470///
4471/// \param TDG A TypoDiagnosticGenerator functor that will be used to print
4472/// diagnostics when the actual typo correction is attempted.
4473///
Kaelyn Takata8363f042014-10-27 18:07:42 +00004474/// \param TRC A TypoRecoveryCallback functor that will be used to build an
4475/// Expr from a typo correction candidate.
4476///
Kaelyn Takata6c759512014-10-27 18:07:37 +00004477/// \param MemberContext if non-NULL, the context in which to look for
4478/// a member access expression.
4479///
4480/// \param EnteringContext whether we're entering the context described by
4481/// the nested-name-specifier SS.
4482///
4483/// \param OPT when non-NULL, the search for visible declarations will
4484/// also walk the protocols in the qualified interfaces of \p OPT.
4485///
4486/// \returns a new \c TypoExpr that will later be replaced in the AST with an
4487/// Expr representing the result of performing typo correction, or nullptr if
4488/// typo correction is not possible. If nullptr is returned, no diagnostics will
4489/// be emitted and it is the responsibility of the caller to emit any that are
4490/// needed.
4491TypoExpr *Sema::CorrectTypoDelayed(
4492 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4493 Scope *S, CXXScopeSpec *SS,
4494 std::unique_ptr<CorrectionCandidateCallback> CCC,
Kaelyn Takata8363f042014-10-27 18:07:42 +00004495 TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,
Kaelyn Takata6c759512014-10-27 18:07:37 +00004496 DeclContext *MemberContext, bool EnteringContext,
4497 const ObjCObjectPointerType *OPT) {
4498 assert(CCC && "CorrectTypoDelayed requires a CorrectionCandidateCallback");
4499
4500 TypoCorrection Empty;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004501 auto Consumer = makeTypoCorrectionConsumer(
4502 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004503 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Kaelyn Takata6c759512014-10-27 18:07:37 +00004504
4505 if (!Consumer || Consumer->empty())
4506 return nullptr;
4507
4508 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4509 // is not more that about a third of the length of the typo's identifier.
4510 unsigned ED = Consumer->getBestEditDistance(true);
4511 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4512 if (ED > 0 && Typo->getName().size() / ED < 3)
4513 return nullptr;
4514
4515 ExprEvalContexts.back().NumTypos++;
Kaelyn Takata8363f042014-10-27 18:07:42 +00004516 return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC));
Kaelyn Takata6c759512014-10-27 18:07:37 +00004517}
4518
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004519void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4520 if (!CDecl) return;
4521
4522 if (isKeyword())
4523 CorrectionDecls.clear();
4524
Kaelyn Uhrainf60b55a2012-11-19 18:49:53 +00004525 CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004526
4527 if (!CorrectionName)
4528 CorrectionName = CDecl->getDeclName();
4529}
4530
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004531std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4532 if (CorrectionNameSpec) {
4533 std::string tmpBuffer;
4534 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4535 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikied4da8722013-05-14 21:04:00 +00004536 PrefixOStream << CorrectionName;
Benjamin Kramer73faad62012-04-14 08:26:28 +00004537 return PrefixOStream.str();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004538 }
4539
4540 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00004541}
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004542
Nico Weberb58e51c2014-11-19 05:21:39 +00004543bool CorrectionCandidateCallback::ValidateCandidate(
4544 const TypoCorrection &candidate) {
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004545 if (!candidate.isResolved())
4546 return true;
4547
4548 if (candidate.isKeyword())
4549 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4550 WantRemainingKeywords || WantObjCSuper;
4551
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004552 bool HasNonType = false;
4553 bool HasStaticMethod = false;
4554 bool HasNonStaticMethod = false;
4555 for (Decl *D : candidate) {
4556 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
4557 D = FTD->getTemplatedDecl();
4558 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4559 if (Method->isStatic())
4560 HasStaticMethod = true;
4561 else
4562 HasNonStaticMethod = true;
4563 }
4564 if (!isa<TypeDecl>(D))
4565 HasNonType = true;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004566 }
4567
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004568 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
4569 !candidate.getCorrectionSpecifier())
4570 return false;
4571
4572 return WantTypeSpecifiers || HasNonType;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004573}
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004574
4575FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004576 bool HasExplicitTemplateArgs,
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004577 MemberExpr *ME)
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004578 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004579 CurContext(SemaRef.CurContext), MemberFn(ME) {
Kaelyn Takatab04846b2014-07-28 18:14:02 +00004580 WantTypeSpecifiers = false;
4581 WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus && NumArgs == 1;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004582 WantRemainingKeywords = false;
4583}
4584
4585bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4586 if (!candidate.getCorrectionDecl())
4587 return candidate.isKeyword();
4588
Aaron Ballman1e606f42014-07-15 22:03:49 +00004589 for (auto *C : candidate) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004590 FunctionDecl *FD = nullptr;
Aaron Ballman1e606f42014-07-15 22:03:49 +00004591 NamedDecl *ND = C->getUnderlyingDecl();
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004592 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4593 FD = FTD->getTemplatedDecl();
4594 if (!HasExplicitTemplateArgs && !FD) {
4595 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4596 // If the Decl is neither a function nor a template function,
4597 // determine if it is a pointer or reference to a function. If so,
4598 // check against the number of arguments expected for the pointee.
4599 QualType ValType = cast<ValueDecl>(ND)->getType();
4600 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4601 ValType = ValType->getPointeeType();
4602 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
Alp Toker9cacbab2014-01-20 20:26:09 +00004603 if (FPT->getNumParams() == NumArgs)
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004604 return true;
4605 }
4606 }
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004607
4608 // Skip the current candidate if it is not a FunctionDecl or does not accept
4609 // the current number of arguments.
4610 if (!FD || !(FD->getNumParams() >= NumArgs &&
4611 FD->getMinRequiredArguments() <= NumArgs))
4612 continue;
4613
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004614 // If the current candidate is a non-static C++ method, skip the candidate
4615 // unless the method being corrected--or the current DeclContext, if the
4616 // function being corrected is not a method--is a method in the same class
4617 // or a descendent class of the candidate's parent class.
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004618 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004619 if (MemberFn || !MD->isStatic()) {
4620 CXXMethodDecl *CurMD =
4621 MemberFn
4622 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
4623 : dyn_cast_or_null<CXXMethodDecl>(CurContext);
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004624 CXXRecordDecl *CurRD =
Craig Topperc3ec1492014-05-26 06:22:03 +00004625 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004626 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
4627 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
4628 continue;
4629 }
4630 }
4631 return true;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004632 }
4633 return false;
4634}
Richard Smithf9b15102013-08-17 00:46:16 +00004635
4636void Sema::diagnoseTypo(const TypoCorrection &Correction,
4637 const PartialDiagnostic &TypoDiag,
4638 bool ErrorRecovery) {
4639 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
4640 ErrorRecovery);
4641}
4642
Richard Smithe156254d2013-08-20 20:35:18 +00004643/// Find which declaration we should import to provide the definition of
4644/// the given declaration.
Richard Smith42413142015-05-15 20:05:43 +00004645static NamedDecl *getDefinitionToImport(NamedDecl *D) {
4646 if (VarDecl *VD = dyn_cast<VarDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004647 return VD->getDefinition();
4648 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Richard Smith42413142015-05-15 20:05:43 +00004649 return FD->isDefined(FD) ? const_cast<FunctionDecl*>(FD) : nullptr;
4650 if (TagDecl *TD = dyn_cast<TagDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004651 return TD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00004652 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004653 return ID->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00004654 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004655 return PD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00004656 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004657 return getDefinitionToImport(TD->getTemplatedDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004658 return nullptr;
Richard Smithe156254d2013-08-20 20:35:18 +00004659}
4660
Richard Smithf9b15102013-08-17 00:46:16 +00004661/// \brief Diagnose a successfully-corrected typo. Separated from the correction
4662/// itself to allow external validation of the result, etc.
4663///
4664/// \param Correction The result of performing typo correction.
4665/// \param TypoDiag The diagnostic to produce. This will have the corrected
4666/// string added to it (and usually also a fixit).
4667/// \param PrevNote A note to use when indicating the location of the entity to
4668/// which we are correcting. Will have the correction string added to it.
4669/// \param ErrorRecovery If \c true (the default), the caller is going to
4670/// recover from the typo as if the corrected string had been typed.
4671/// In this case, \c PDiag must be an error, and we will attach a fixit
4672/// to it.
4673void Sema::diagnoseTypo(const TypoCorrection &Correction,
4674 const PartialDiagnostic &TypoDiag,
4675 const PartialDiagnostic &PrevNote,
4676 bool ErrorRecovery) {
4677 std::string CorrectedStr = Correction.getAsString(getLangOpts());
4678 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
4679 FixItHint FixTypo = FixItHint::CreateReplacement(
4680 Correction.getCorrectionRange(), CorrectedStr);
4681
Richard Smithe156254d2013-08-20 20:35:18 +00004682 // Maybe we're just missing a module import.
4683 if (Correction.requiresImport()) {
4684 NamedDecl *Decl = Correction.getCorrectionDecl();
4685 assert(Decl && "import required but no declaration to import");
4686
4687 // Suggest importing a module providing the definition of this entity, if
4688 // possible.
Richard Smith42413142015-05-15 20:05:43 +00004689 NamedDecl *Def = getDefinitionToImport(Decl);
Richard Smithe156254d2013-08-20 20:35:18 +00004690 if (!Def)
4691 Def = Decl;
Richard Smith42413142015-05-15 20:05:43 +00004692 Module *Owner = getOwningModule(Def);
Richard Smithe156254d2013-08-20 20:35:18 +00004693 assert(Owner && "definition of hidden declaration is not in a module");
4694
4695 Diag(Correction.getCorrectionRange().getBegin(),
4696 diag::err_module_private_declaration)
4697 << Def << Owner->getFullModuleName();
4698 Diag(Def->getLocation(), diag::note_previous_declaration);
4699
4700 // Recover by implicitly importing this module.
Richard Smith3d23c422014-05-07 02:25:43 +00004701 if (ErrorRecovery)
4702 createImplicitModuleImportForErrorRecovery(
4703 Correction.getCorrectionRange().getBegin(), Owner);
Richard Smithe156254d2013-08-20 20:35:18 +00004704 return;
4705 }
4706
Richard Smithf9b15102013-08-17 00:46:16 +00004707 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
4708 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
4709
4710 NamedDecl *ChosenDecl =
Craig Topperc3ec1492014-05-26 06:22:03 +00004711 Correction.isKeyword() ? nullptr : Correction.getCorrectionDecl();
Richard Smithf9b15102013-08-17 00:46:16 +00004712 if (PrevNote.getDiagID() && ChosenDecl)
4713 Diag(ChosenDecl->getLocation(), PrevNote)
4714 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
4715}
Kaelyn Takata6c759512014-10-27 18:07:37 +00004716
Kaelyn Takata8363f042014-10-27 18:07:42 +00004717TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
4718 TypoDiagnosticGenerator TDG,
4719 TypoRecoveryCallback TRC) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00004720 assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
4721 auto TE = new (Context) TypoExpr(Context.DependentTy);
4722 auto &State = DelayedTypos[TE];
4723 State.Consumer = std::move(TCC);
4724 State.DiagHandler = std::move(TDG);
Kaelyn Takata8363f042014-10-27 18:07:42 +00004725 State.RecoveryHandler = std::move(TRC);
Kaelyn Takata6c759512014-10-27 18:07:37 +00004726 return TE;
4727}
4728
4729const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
4730 auto Entry = DelayedTypos.find(TE);
4731 assert(Entry != DelayedTypos.end() &&
4732 "Failed to get the state for a TypoExpr!");
4733 return Entry->second;
4734}
4735
4736void Sema::clearDelayedTypo(TypoExpr *TE) {
4737 DelayedTypos.erase(TE);
4738}