blob: 99b945597bc7dabeb70410fa94ed632a1b8c90f0 [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 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000207}
Douglas Gregor889ceb72009-02-03 19:21:40 +0000208
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
Richard Smitha534a312015-07-21 23:54:07 +0000381 llvm::SmallDenseMap<NamedDecl*, unsigned, 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
Richard Smitha534a312015-07-21 23:54:07 +0000417 auto UniqueResult = Unique.insert(std::make_pair(D, I));
418 if (!UniqueResult.second) {
John McCall9f3059a2009-10-09 21:13:30 +0000419 // If it's not unique, pull something off the back (and
420 // continue at this index).
Richard Smitha534a312015-07-21 23:54:07 +0000421 auto ExistingI = UniqueResult.first->second;
422 auto *Existing = Decls[ExistingI]->getUnderlyingDecl();
423 for (Decl *Prev = Decls[I]->getUnderlyingDecl()->getPreviousDecl(); /**/;
424 Prev = Prev->getPreviousDecl()) {
425 if (Prev == Existing) {
426 // Existing result is older. Replace it with the new one.
427 Decls[ExistingI] = Decls[I];
428 Decls[I] = Decls[--N];
429 break;
430 }
431 if (!Prev) {
432 // New decl is older. Keep the existing one.
433 Decls[I] = Decls[--N];
434 break;
435 }
436 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000437 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000438 }
439
Douglas Gregor13e65872010-08-11 14:45:53 +0000440 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000441
Douglas Gregor13e65872010-08-11 14:45:53 +0000442 if (isa<UnresolvedUsingValueDecl>(D)) {
443 HasUnresolved = true;
444 } else if (isa<TagDecl>(D)) {
445 if (HasTag)
446 Ambiguous = true;
447 UniqueTagIndex = I;
448 HasTag = true;
449 } else if (isa<FunctionTemplateDecl>(D)) {
450 HasFunction = true;
451 HasFunctionTemplate = true;
452 } else if (isa<FunctionDecl>(D)) {
453 HasFunction = true;
454 } else {
455 if (HasNonFunction)
456 Ambiguous = true;
457 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000458 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000459 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000460 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000461
John McCall9f3059a2009-10-09 21:13:30 +0000462 // C++ [basic.scope.hiding]p2:
463 // A class name or enumeration name can be hidden by the name of
464 // an object, function, or enumerator declared in the same
465 // scope. If a class or enumeration name and an object, function,
466 // or enumerator are declared in the same scope (in any order)
467 // with the same name, the class or enumeration name is hidden
468 // wherever the object, function, or enumerator name is visible.
469 // But it's still an error if there are distinct tag types found,
470 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000471 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000472 (HasFunction || HasNonFunction || HasUnresolved)) {
Richard Smith3876cc82013-10-30 01:02:04 +0000473 if (getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
474 getContextForScopeMatching(Decls[UniqueTagIndex ? 0 : N - 1])))
Douglas Gregore63d0872010-10-23 16:06:17 +0000475 Decls[UniqueTagIndex] = Decls[--N];
476 else
477 Ambiguous = true;
478 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000479
John McCall9f3059a2009-10-09 21:13:30 +0000480 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000481
John McCall80053822009-12-03 00:58:24 +0000482 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000483 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000484
John McCall9f3059a2009-10-09 21:13:30 +0000485 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000486 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000487 else if (HasUnresolved)
488 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000489 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000490 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000491 else
John McCall27b18f82009-11-17 02:14:36 +0000492 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000493}
494
John McCall5cebab12009-11-18 07:57:50 +0000495void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000496 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000497 for (I = P.begin(), E = P.end(); I != E; ++I)
David Blaikieff7d47a2012-12-19 00:45:41 +0000498 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
499 DE = I->Decls.end(); DI != DE; ++DI)
John McCall9f3059a2009-10-09 21:13:30 +0000500 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000501}
502
John McCall5cebab12009-11-18 07:57:50 +0000503void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000504 Paths = new CXXBasePaths;
505 Paths->swap(P);
506 addDeclsFromBasePaths(*Paths);
507 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000508 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000509}
510
John McCall5cebab12009-11-18 07:57:50 +0000511void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000512 Paths = new CXXBasePaths;
513 Paths->swap(P);
514 addDeclsFromBasePaths(*Paths);
515 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000516 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000517}
518
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000519void LookupResult::print(raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000520 Out << Decls.size() << " result(s)";
521 if (isAmbiguous()) Out << ", ambiguous";
522 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000523
John McCall9f3059a2009-10-09 21:13:30 +0000524 for (iterator I = begin(), E = end(); I != E; ++I) {
525 Out << "\n";
526 (*I)->print(Out, 2);
527 }
528}
529
Douglas Gregord3a59182010-02-12 05:48:04 +0000530/// \brief Lookup a builtin function, when name lookup would otherwise
531/// fail.
532static bool LookupBuiltin(Sema &S, LookupResult &R) {
533 Sema::LookupNameKind NameKind = R.getLookupKind();
534
535 // If we didn't find a use of this identifier, and if the identifier
536 // corresponds to a compiler builtin, create the decl object for the builtin
537 // now, injecting it into translation unit scope, and return it.
538 if (NameKind == Sema::LookupOrdinaryName ||
539 NameKind == Sema::LookupRedeclarationWithLinkage) {
540 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
541 if (II) {
Nico Webere1687c52013-06-20 21:44:55 +0000542 if (S.getLangOpts().CPlusPlus11 && S.getLangOpts().GNUMode &&
543 II == S.getFloat128Identifier()) {
544 // libstdc++4.7's type_traits expects type __float128 to exist, so
545 // insert a dummy type to make that header build in gnu++11 mode.
546 R.addDecl(S.getASTContext().getFloat128StubType());
547 return true;
548 }
549
Douglas Gregord3a59182010-02-12 05:48:04 +0000550 // If this is a builtin on this (or all) targets, create the decl.
551 if (unsigned BuiltinID = II->getBuiltinID()) {
552 // In C++, we don't have any predefined library functions like
553 // 'malloc'. Instead, we'll just error.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000554 if (S.getLangOpts().CPlusPlus &&
Douglas Gregord3a59182010-02-12 05:48:04 +0000555 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
556 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000557
558 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
559 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000560 R.isForRedeclaration(),
561 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000562 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000563 return true;
564 }
Douglas Gregord3a59182010-02-12 05:48:04 +0000565 }
566 }
567 }
568
569 return false;
570}
571
Douglas Gregor7454c562010-07-02 20:37:36 +0000572/// \brief Determine whether we can declare a special member function within
573/// the class at this point.
Richard Smith7d125a12012-11-27 21:20:31 +0000574static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +0000575 // We need to have a definition for the class.
576 if (!Class->getDefinition() || Class->isDependentContext())
577 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000578
Douglas Gregor7454c562010-07-02 20:37:36 +0000579 // We can't be in the middle of defining the class.
Richard Smith7d125a12012-11-27 21:20:31 +0000580 return !Class->isBeingDefined();
Douglas Gregor7454c562010-07-02 20:37:36 +0000581}
582
583void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smith7d125a12012-11-27 21:20:31 +0000584 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregora6d69502010-07-02 23:41:54 +0000585 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000586
587 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000588 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000589 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000590
Douglas Gregora6d69502010-07-02 23:41:54 +0000591 // If the copy constructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000592 if (Class->needsImplicitCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +0000593 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000594
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000595 // If the copy assignment operator has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000596 if (Class->needsImplicitCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000597 DeclareImplicitCopyAssignment(Class);
598
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000599 if (getLangOpts().CPlusPlus11) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000600 // If the move constructor has not yet been declared, do so now.
601 if (Class->needsImplicitMoveConstructor())
602 DeclareImplicitMoveConstructor(Class); // might not actually do it
603
604 // If the move assignment operator has not yet been declared, do so now.
605 if (Class->needsImplicitMoveAssignment())
606 DeclareImplicitMoveAssignment(Class); // might not actually do it
607 }
608
Douglas Gregor7454c562010-07-02 20:37:36 +0000609 // If the destructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000610 if (Class->needsImplicitDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000611 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000612}
613
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000614/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000615/// special member function.
616static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
617 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000618 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000619 case DeclarationName::CXXDestructorName:
620 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000621
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000622 case DeclarationName::CXXOperatorName:
623 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000624
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000625 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000626 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000627 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000628
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000629 return false;
630}
631
632/// \brief If there are any implicit member functions with the given name
633/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000634static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000635 DeclarationName Name,
636 const DeclContext *DC) {
637 if (!DC)
638 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000639
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000640 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000641 case DeclarationName::CXXConstructorName:
642 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith7d125a12012-11-27 21:20:31 +0000643 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000644 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000645 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000646 S.DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +0000647 if (Record->needsImplicitCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000648 S.DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000649 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000650 Record->needsImplicitMoveConstructor())
651 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000652 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000653 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000654
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000655 case DeclarationName::CXXDestructorName:
656 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith2be35f52012-12-01 02:35:44 +0000657 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smith7d125a12012-11-27 21:20:31 +0000658 CanDeclareSpecialMemberFunction(Record))
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000659 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000660 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000661
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000662 case DeclarationName::CXXOperatorName:
663 if (Name.getCXXOverloadedOperator() != OO_Equal)
664 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000665
Sebastian Redl22653ba2011-08-30 19:58:05 +0000666 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smith7d125a12012-11-27 21:20:31 +0000667 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000668 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smith2be35f52012-12-01 02:35:44 +0000669 if (Record->needsImplicitCopyAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000670 S.DeclareImplicitCopyAssignment(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000671 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000672 Record->needsImplicitMoveAssignment())
673 S.DeclareImplicitMoveAssignment(Class);
674 }
675 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000676 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000677
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000678 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000679 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000680 }
681}
Douglas Gregor7454c562010-07-02 20:37:36 +0000682
John McCall9f3059a2009-10-09 21:13:30 +0000683// Adds all qualifying matches for a name within a decl context to the
684// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000685static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000686 bool Found = false;
687
Douglas Gregor7454c562010-07-02 20:37:36 +0000688 // Lazily declare C++ special member functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000689 if (S.getLangOpts().CPlusPlus)
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000690 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000691
Douglas Gregor7454c562010-07-02 20:37:36 +0000692 // Perform lookup into this declaration context.
Richard Smithcf4bdde2015-02-21 02:45:19 +0000693 DeclContext::lookup_result DR = DC->lookup(R.getLookupName());
694 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E;
David Blaikieff7d47a2012-12-19 00:45:41 +0000695 ++I) {
John McCall401982f2010-01-20 21:53:11 +0000696 NamedDecl *D = *I;
Douglas Gregor4a814562011-12-14 16:03:29 +0000697 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000698 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000699 Found = true;
700 }
701 }
John McCall9f3059a2009-10-09 21:13:30 +0000702
Douglas Gregord3a59182010-02-12 05:48:04 +0000703 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
704 return true;
705
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000706 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000707 != DeclarationName::CXXConversionFunctionName ||
708 R.getLookupName().getCXXNameType()->isDependentType() ||
709 !isa<CXXRecordDecl>(DC))
710 return Found;
711
712 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000713 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000714 // name lookup. Instead, any conversion function templates visible in the
715 // context of the use are considered. [...]
716 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000717 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000718 return Found;
719
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +0000720 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
721 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruth3a693b72010-01-31 11:44:02 +0000722 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
723 if (!ConvTemplate)
724 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000725
Chandler Carruth3a693b72010-01-31 11:44:02 +0000726 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000727 // add the conversion function template. When we deduce template
728 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000729 // type of the new declaration with the type of the function template.
730 if (R.isForRedeclaration()) {
731 R.addDecl(ConvTemplate);
732 Found = true;
733 continue;
734 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000735
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000736 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000737 // [...] For each such operator, if argument deduction succeeds
738 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000739 // name lookup.
740 //
741 // When referencing a conversion function for any purpose other than
742 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000743 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000744 // specialization into the result set. We do this to avoid forcing all
745 // callers to perform special deduction for conversion functions.
Craig Toppere6706e42012-09-19 02:26:47 +0000746 TemplateDeductionInfo Info(R.getNameLoc());
Craig Topperc3ec1492014-05-26 06:22:03 +0000747 FunctionDecl *Specialization = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000748
749 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000750 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
751 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000752
Chandler Carruth3a693b72010-01-31 11:44:02 +0000753 // Compute the type of the function that we would expect the conversion
754 // function to have, if it were to match the name given.
755 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000756 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
Reid Kleckner78af0702013-08-27 23:08:25 +0000757 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
Richard Smith8acb4282014-07-31 21:57:55 +0000758 EPI.ExceptionSpec = EST_None;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000759 QualType ExpectedType
760 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000761 None, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000762
Chandler Carruth3a693b72010-01-31 11:44:02 +0000763 // Perform template argument deduction against the type that we would
764 // expect the function to have.
Craig Topperc3ec1492014-05-26 06:22:03 +0000765 if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
Chandler Carruth3a693b72010-01-31 11:44:02 +0000766 Specialization, Info)
767 == Sema::TDK_Success) {
768 R.addDecl(Specialization);
769 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000770 }
771 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000772
John McCall9f3059a2009-10-09 21:13:30 +0000773 return Found;
774}
775
John McCallf6c8a4e2009-11-10 07:01:13 +0000776// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000777static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000778CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000779 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000780
781 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
782
John McCallf6c8a4e2009-11-10 07:01:13 +0000783 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000784 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000785
John McCallf6c8a4e2009-11-10 07:01:13 +0000786 // Perform direct name lookup into the namespaces nominated by the
787 // using directives whose common ancestor is this namespace.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000788 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
789 if (LookupDirect(S, R, UUE.getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000790 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000791
792 R.resolveKind();
793
794 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000795}
796
797static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000798 if (DeclContext *Ctx = S->getEntity())
Douglas Gregor700792c2009-02-05 19:25:20 +0000799 return Ctx->isFileContext();
800 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000801}
Douglas Gregored8f2882009-01-30 01:04:22 +0000802
Douglas Gregor66230062010-03-15 14:33:29 +0000803// Find the next outer declaration context from this scope. This
804// routine actually returns the semantic outer context, which may
805// differ from the lexical context (encoded directly in the Scope
806// stack) when we are parsing a member of a class template. In this
807// case, the second element of the pair will be true, to indicate that
808// name lookup should continue searching in this semantic context when
809// it leaves the current template parameter scope.
810static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000811 DeclContext *DC = S->getEntity();
Craig Topperc3ec1492014-05-26 06:22:03 +0000812 DeclContext *Lexical = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000813 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000814 OuterS = OuterS->getParent()) {
815 if (OuterS->getEntity()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000816 Lexical = OuterS->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +0000817 break;
818 }
819 }
820
821 // C++ [temp.local]p8:
822 // In the definition of a member of a class template that appears
823 // outside of the namespace containing the class template
824 // definition, the name of a template-parameter hides the name of
825 // a member of this namespace.
826 //
827 // Example:
828 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000829 // namespace N {
830 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000831 //
832 // template<class T> class B {
833 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000834 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000835 // }
836 //
837 // template<class C> void N::B<C>::f(C) {
838 // C b; // C is the template parameter, not N::C
839 // }
840 //
841 // In this example, the lexical context we return is the
842 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000843 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000844 !S->getParent()->isTemplateParamScope())
845 return std::make_pair(Lexical, false);
846
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000847 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000848 // For the example, this is the scope for the template parameters of
849 // template<class C>.
850 Scope *OutermostTemplateScope = S->getParent();
851 while (OutermostTemplateScope->getParent() &&
852 OutermostTemplateScope->getParent()->isTemplateParamScope())
853 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000854
Douglas Gregor66230062010-03-15 14:33:29 +0000855 // Find the namespace context in which the original scope occurs. In
856 // the example, this is namespace N.
857 DeclContext *Semantic = DC;
858 while (!Semantic->isFileContext())
859 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000860
Douglas Gregor66230062010-03-15 14:33:29 +0000861 // Find the declaration context just outside of the template
862 // parameter scope. This is the context in which the template is
863 // being lexically declaration (a namespace context). In the
864 // example, this is the global scope.
865 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
866 Lexical->Encloses(Semantic))
867 return std::make_pair(Semantic, true);
868
869 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000870}
871
Richard Smith541b38b2013-09-20 01:15:31 +0000872namespace {
873/// An RAII object to specify that we want to find block scope extern
874/// declarations.
875struct FindLocalExternScope {
876 FindLocalExternScope(LookupResult &R)
877 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
878 Decl::IDNS_LocalExtern) {
879 R.setFindLocalExtern(R.getIdentifierNamespace() & Decl::IDNS_Ordinary);
880 }
881 void restore() {
882 R.setFindLocalExtern(OldFindLocalExtern);
883 }
884 ~FindLocalExternScope() {
885 restore();
886 }
887 LookupResult &R;
888 bool OldFindLocalExtern;
889};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000890}
Richard Smith541b38b2013-09-20 01:15:31 +0000891
John McCall27b18f82009-11-17 02:14:36 +0000892bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000893 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000894
895 DeclarationName Name = R.getLookupName();
Richard Smith1c34fb72013-08-13 18:18:50 +0000896 Sema::LookupNameKind NameKind = R.getLookupKind();
John McCall27b18f82009-11-17 02:14:36 +0000897
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000898 // If this is the name of an implicitly-declared special member function,
899 // go through the scope stack to implicitly declare
900 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
901 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +0000902 if (DeclContext *DC = PreS->getEntity())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000903 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
904 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000905
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000906 // Implicitly declare member functions with the name we're looking for, if in
907 // fact we are in a scope where it matters.
908
Douglas Gregor889ceb72009-02-03 19:21:40 +0000909 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000910 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000911 I = IdResolver.begin(Name),
912 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000913
Douglas Gregor889ceb72009-02-03 19:21:40 +0000914 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000915 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000916 // ...During unqualified name lookup (3.4.1), the names appear as if
917 // they were declared in the nearest enclosing namespace which contains
918 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000919 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000920 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000921 //
922 // For example:
923 // namespace A { int i; }
924 // void foo() {
925 // int i;
926 // {
927 // using namespace A;
928 // ++i; // finds local 'i', A::i appears at global scope
929 // }
930 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000931 //
Douglas Gregorcc9406c2013-04-08 23:11:25 +0000932 UnqualUsingDirectiveSet UDirs;
933 bool VisitedUsingDirectives = false;
Richard Smith1c34fb72013-08-13 18:18:50 +0000934 bool LeftStartingScope = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000935 DeclContext *OutsideOfTemplateParamDC = nullptr;
Richard Smith541b38b2013-09-20 01:15:31 +0000936
937 // When performing a scope lookup, we want to find local extern decls.
938 FindLocalExternScope FindLocals(R);
939
Douglas Gregor700792c2009-02-05 19:25:20 +0000940 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000941 DeclContext *Ctx = S->getEntity();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000942
Douglas Gregor889ceb72009-02-03 19:21:40 +0000943 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000944 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000945 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000946 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Richard Smith1c34fb72013-08-13 18:18:50 +0000947 if (NameKind == LookupRedeclarationWithLinkage) {
948 // Determine whether this (or a previous) declaration is
949 // out-of-scope.
950 if (!LeftStartingScope && !Initial->isDeclScope(*I))
951 LeftStartingScope = true;
952
953 // If we found something outside of our starting scope that
Richard Smith9a00bbf2013-10-16 21:12:00 +0000954 // does not have linkage, skip it. If it's a template parameter,
955 // we still find it, so we can diagnose the invalid redeclaration.
956 if (LeftStartingScope && !((*I)->hasLinkage()) &&
957 !(*I)->isTemplateParameter()) {
Richard Smith1c34fb72013-08-13 18:18:50 +0000958 R.setShadowed();
959 continue;
960 }
961 }
962
John McCall9f3059a2009-10-09 21:13:30 +0000963 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +0000964 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000965 }
966 }
John McCall9f3059a2009-10-09 21:13:30 +0000967 if (Found) {
968 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000969 if (S->isClassScope())
970 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
971 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000972 return true;
973 }
974
Richard Smith1c34fb72013-08-13 18:18:50 +0000975 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
Richard Smith114394f2013-08-09 04:35:01 +0000976 // C++11 [class.friend]p11:
977 // If a friend declaration appears in a local class and the name
978 // specified is an unqualified name, a prior declaration is
979 // looked up without considering scopes that are outside the
980 // innermost enclosing non-class scope.
981 return false;
982 }
983
Douglas Gregor66230062010-03-15 14:33:29 +0000984 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
985 S->getParent() && !S->getParent()->isTemplateParamScope()) {
986 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000987 // found nothing, so look into the contexts between the
Douglas Gregor66230062010-03-15 14:33:29 +0000988 // lexical and semantic declaration contexts returned by
989 // findOuterContext(). This implements the name lookup behavior
990 // of C++ [temp.local]p8.
991 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +0000992 OutsideOfTemplateParamDC = nullptr;
Douglas Gregor66230062010-03-15 14:33:29 +0000993 }
994
995 if (Ctx) {
996 DeclContext *OuterCtx;
997 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000998 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregor66230062010-03-15 14:33:29 +0000999 if (SearchAfterTemplateScope)
1000 OutsideOfTemplateParamDC = OuterCtx;
1001
Douglas Gregorea166062010-03-15 15:26:48 +00001002 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +00001003 // We do not directly look into transparent contexts, since
1004 // those entities will be found in the nearest enclosing
1005 // non-transparent context.
1006 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +00001007 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +00001008
1009 // We do not look directly into function or method contexts,
1010 // since all of the local variables and parameters of the
1011 // function/method are present within the Scope.
1012 if (Ctx->isFunctionOrMethod()) {
1013 // If we have an Objective-C instance method, look for ivars
1014 // in the corresponding interface.
1015 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
1016 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1017 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1018 ObjCInterfaceDecl *ClassDeclared;
1019 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001020 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +00001021 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001022 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1023 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +00001024 R.resolveKind();
1025 return true;
1026 }
1027 }
1028 }
1029 }
1030
1031 continue;
1032 }
1033
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001034 // If this is a file context, we need to perform unqualified name
1035 // lookup considering using directives.
1036 if (Ctx->isFileContext()) {
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001037 // If we haven't handled using directives yet, do so now.
1038 if (!VisitedUsingDirectives) {
1039 // Add using directives from this context up to the top level.
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001040 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1041 if (UCtx->isTransparentContext())
1042 continue;
1043
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001044 UDirs.visit(UCtx, UCtx);
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001045 }
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001046
1047 // Find the innermost file scope, so we can add using directives
1048 // from local scopes.
1049 Scope *InnermostFileScope = S;
1050 while (InnermostFileScope &&
1051 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1052 InnermostFileScope = InnermostFileScope->getParent();
1053 UDirs.visitScopeChain(Initial, InnermostFileScope);
1054
1055 UDirs.done();
1056
1057 VisitedUsingDirectives = true;
1058 }
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001059
1060 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1061 R.resolveKind();
1062 return true;
1063 }
1064
1065 continue;
1066 }
1067
Douglas Gregor7f737c02009-09-10 16:57:35 +00001068 // Perform qualified name lookup into this context.
1069 // FIXME: In some cases, we know that every name that could be found by
1070 // this qualified name lookup will also be on the identifier chain. For
1071 // example, inside a class without any base classes, we never need to
1072 // perform qualified lookup because all of the members are on top of the
1073 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001074 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +00001075 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +00001076 }
Douglas Gregor700792c2009-02-05 19:25:20 +00001077 }
Douglas Gregored8f2882009-01-30 01:04:22 +00001078 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001079
John McCallf6c8a4e2009-11-10 07:01:13 +00001080 // Stop if we ran out of scopes.
1081 // FIXME: This really, really shouldn't be happening.
1082 if (!S) return false;
1083
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001084 // If we are looking for members, no need to look into global/namespace scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00001085 if (NameKind == LookupMemberName)
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001086 return false;
1087
Douglas Gregor700792c2009-02-05 19:25:20 +00001088 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +00001089 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +00001090 //
Mike Stump87c57ac2009-05-16 07:39:55 +00001091 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1092 // don't build it for each lookup!
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001093 if (!VisitedUsingDirectives) {
1094 UDirs.visitScopeChain(Initial, S);
1095 UDirs.done();
1096 }
Richard Smith541b38b2013-09-20 01:15:31 +00001097
1098 // If we're not performing redeclaration lookup, do not look for local
1099 // extern declarations outside of a function scope.
1100 if (!R.isForRedeclaration())
1101 FindLocals.restore();
1102
Douglas Gregor700792c2009-02-05 19:25:20 +00001103 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +00001104 // Unqualified name lookup in C++ requires looking into scopes
1105 // that aren't strictly lexical, and therefore we walk through the
1106 // context as well as walking through the scopes.
1107 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001108 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +00001109 bool Found = false;
John McCall48871652010-08-21 09:40:31 +00001110 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001111 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001112 // We found something. Look for anything else in our scope
1113 // with this same name and in an acceptable identifier
1114 // namespace, so that we can construct an overload set if we
1115 // need to.
John McCall9f3059a2009-10-09 21:13:30 +00001116 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +00001117 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001118 }
1119 }
1120
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001121 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +00001122 R.resolveKind();
1123 return true;
1124 }
1125
Ted Kremenekc37877d2013-10-08 17:08:03 +00001126 DeclContext *Ctx = S->getEntity();
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001127 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1128 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1129 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001130 // found nothing, so look into the contexts between the
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001131 // lexical and semantic declaration contexts returned by
1132 // findOuterContext(). This implements the name lookup behavior
1133 // of C++ [temp.local]p8.
1134 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +00001135 OutsideOfTemplateParamDC = nullptr;
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001136 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001137
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001138 if (Ctx) {
1139 DeclContext *OuterCtx;
1140 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001141 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001142 if (SearchAfterTemplateScope)
1143 OutsideOfTemplateParamDC = OuterCtx;
1144
1145 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1146 // We do not directly look into transparent contexts, since
1147 // those entities will be found in the nearest enclosing
1148 // non-transparent context.
1149 if (Ctx->isTransparentContext())
1150 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001151
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001152 // If we have a context, and it's not a context stashed in the
1153 // template parameter scope for an out-of-line definition, also
1154 // look into that context.
1155 if (!(Found && S && S->isTemplateParamScope())) {
1156 assert(Ctx->isFileContext() &&
1157 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001158
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001159 // Look into context considering using-directives.
1160 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1161 Found = true;
1162 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001163
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001164 if (Found) {
1165 R.resolveKind();
1166 return true;
1167 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001168
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001169 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1170 return false;
1171 }
1172 }
1173
Douglas Gregor3ce74932010-02-05 07:07:10 +00001174 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001175 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001176 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001177
John McCall9f3059a2009-10-09 21:13:30 +00001178 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001179}
1180
Richard Smith0e5d7b82013-07-25 23:08:39 +00001181/// \brief Find the declaration that a class temploid member specialization was
1182/// instantiated from, or the member itself if it is an explicit specialization.
1183static Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) {
1184 return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom();
1185}
1186
Richard Smith42413142015-05-15 20:05:43 +00001187Module *Sema::getOwningModule(Decl *Entity) {
1188 // If it's imported, grab its owning module.
1189 Module *M = Entity->getImportedOwningModule();
1190 if (M || !isa<NamedDecl>(Entity) || !cast<NamedDecl>(Entity)->isHidden())
1191 return M;
1192 assert(!Entity->isFromASTFile() &&
1193 "hidden entity from AST file has no owning module");
1194
Richard Smith87bb5692015-06-09 00:35:49 +00001195 if (!getLangOpts().ModulesLocalVisibility) {
1196 // If we're not tracking visibility locally, the only way a declaration
1197 // can be hidden and local is if it's hidden because it's parent is (for
1198 // instance, maybe this is a lazily-declared special member of an imported
1199 // class).
1200 auto *Parent = cast<NamedDecl>(Entity->getDeclContext());
1201 assert(Parent->isHidden() && "unexpectedly hidden decl");
1202 return getOwningModule(Parent);
1203 }
1204
Richard Smith42413142015-05-15 20:05:43 +00001205 // It's local and hidden; grab or compute its owning module.
1206 M = Entity->getLocalOwningModule();
1207 if (M)
1208 return M;
1209
1210 if (auto *Containing =
1211 PP.getModuleContainingLocation(Entity->getLocation())) {
1212 M = Containing;
1213 } else if (Entity->isInvalidDecl() || Entity->getLocation().isInvalid()) {
1214 // Don't bother tracking visibility for invalid declarations with broken
1215 // locations.
1216 cast<NamedDecl>(Entity)->setHidden(false);
1217 } else {
1218 // We need to assign a module to an entity that exists outside of any
1219 // module, so that we can hide it from modules that we textually enter.
1220 // Invent a fake module for all such entities.
1221 if (!CachedFakeTopLevelModule) {
1222 CachedFakeTopLevelModule =
1223 PP.getHeaderSearchInfo().getModuleMap().findOrCreateModule(
1224 "<top-level>", nullptr, false, false).first;
1225
1226 auto &SrcMgr = PP.getSourceManager();
1227 SourceLocation StartLoc =
1228 SrcMgr.getLocForStartOfFile(SrcMgr.getMainFileID());
1229 auto &TopLevel =
1230 VisibleModulesStack.empty() ? VisibleModules : VisibleModulesStack[0];
1231 TopLevel.setVisible(CachedFakeTopLevelModule, StartLoc);
1232 }
1233
1234 M = CachedFakeTopLevelModule;
1235 }
1236
1237 if (M)
1238 Entity->setLocalOwningModule(M);
1239 return M;
1240}
1241
Richard Smithd9ba2242015-05-07 03:54:19 +00001242void Sema::makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc) {
Richard Smith87bb5692015-06-09 00:35:49 +00001243 if (auto *M = PP.getModuleContainingLocation(Loc))
1244 Context.mergeDefinitionIntoModule(ND, M);
1245 else
1246 // We're not building a module; just make the definition visible.
1247 ND->setHidden(false);
Richard Smith63e09bf2015-06-17 20:39:41 +00001248
1249 // If ND is a template declaration, make the template parameters
1250 // visible too. They're not (necessarily) within a mergeable DeclContext.
1251 if (auto *TD = dyn_cast<TemplateDecl>(ND))
1252 for (auto *Param : *TD->getTemplateParameters())
1253 makeMergedDefinitionVisible(Param, Loc);
Richard Smithd9ba2242015-05-07 03:54:19 +00001254}
1255
Richard Smith0e5d7b82013-07-25 23:08:39 +00001256/// \brief Find the module in which the given declaration was defined.
Richard Smith42413142015-05-15 20:05:43 +00001257static Module *getDefiningModule(Sema &S, Decl *Entity) {
Richard Smith0e5d7b82013-07-25 23:08:39 +00001258 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1259 // If this function was instantiated from a template, the defining module is
1260 // the module containing the pattern.
1261 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1262 Entity = Pattern;
1263 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
Reid Klecknere7367d62014-10-14 20:28:40 +00001264 if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
1265 Entity = Pattern;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001266 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1267 if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo())
1268 Entity = getInstantiatedFrom(ED, MSInfo);
1269 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1270 // FIXME: Map from variable template specializations back to the template.
1271 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo())
1272 Entity = getInstantiatedFrom(VD, MSInfo);
1273 }
1274
1275 // Walk up to the containing context. That might also have been instantiated
1276 // from a template.
1277 DeclContext *Context = Entity->getDeclContext();
1278 if (Context->isFileContext())
Richard Smith42413142015-05-15 20:05:43 +00001279 return S.getOwningModule(Entity);
1280 return getDefiningModule(S, cast<Decl>(Context));
Richard Smith0e5d7b82013-07-25 23:08:39 +00001281}
1282
1283llvm::DenseSet<Module*> &Sema::getLookupModules() {
1284 unsigned N = ActiveTemplateInstantiations.size();
1285 for (unsigned I = ActiveTemplateInstantiationLookupModules.size();
1286 I != N; ++I) {
Richard Smith42413142015-05-15 20:05:43 +00001287 Module *M =
1288 getDefiningModule(*this, ActiveTemplateInstantiations[I].Entity);
Richard Smith0e5d7b82013-07-25 23:08:39 +00001289 if (M && !LookupModulesCache.insert(M).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00001290 M = nullptr;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001291 ActiveTemplateInstantiationLookupModules.push_back(M);
1292 }
1293 return LookupModulesCache;
1294}
1295
Richard Smith42413142015-05-15 20:05:43 +00001296bool Sema::hasVisibleMergedDefinition(NamedDecl *Def) {
1297 for (Module *Merged : Context.getModulesWithMergedDefinition(Def))
1298 if (isModuleVisible(Merged))
1299 return true;
1300 return false;
1301}
1302
Richard Smithe7bd6de2015-06-10 20:30:23 +00001303template<typename ParmDecl>
Richard Smith35c1df52015-06-17 20:16:32 +00001304static bool
1305hasVisibleDefaultArgument(Sema &S, const ParmDecl *D,
1306 llvm::SmallVectorImpl<Module *> *Modules) {
Richard Smithe7bd6de2015-06-10 20:30:23 +00001307 if (!D->hasDefaultArgument())
1308 return false;
1309
1310 while (D) {
1311 auto &DefaultArg = D->getDefaultArgStorage();
1312 if (!DefaultArg.isInherited() && S.isVisible(D))
1313 return true;
1314
Richard Smith63e09bf2015-06-17 20:39:41 +00001315 if (!DefaultArg.isInherited() && Modules) {
1316 auto *NonConstD = const_cast<ParmDecl*>(D);
1317 Modules->push_back(S.getOwningModule(NonConstD));
1318 const auto &Merged = S.Context.getModulesWithMergedDefinition(NonConstD);
1319 Modules->insert(Modules->end(), Merged.begin(), Merged.end());
1320 }
Richard Smith35c1df52015-06-17 20:16:32 +00001321
Richard Smithe7bd6de2015-06-10 20:30:23 +00001322 // If there was a previous default argument, maybe its parameter is visible.
1323 D = DefaultArg.getInheritedFrom();
1324 }
1325 return false;
1326}
1327
Richard Smith35c1df52015-06-17 20:16:32 +00001328bool Sema::hasVisibleDefaultArgument(const NamedDecl *D,
1329 llvm::SmallVectorImpl<Module *> *Modules) {
Richard Smithe7bd6de2015-06-10 20:30:23 +00001330 if (auto *P = dyn_cast<TemplateTypeParmDecl>(D))
Richard Smith35c1df52015-06-17 20:16:32 +00001331 return ::hasVisibleDefaultArgument(*this, P, Modules);
Richard Smithe7bd6de2015-06-10 20:30:23 +00001332 if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))
Richard Smith35c1df52015-06-17 20:16:32 +00001333 return ::hasVisibleDefaultArgument(*this, P, Modules);
1334 return ::hasVisibleDefaultArgument(*this, cast<TemplateTemplateParmDecl>(D),
1335 Modules);
Richard Smithe7bd6de2015-06-10 20:30:23 +00001336}
1337
Richard Smith0e5d7b82013-07-25 23:08:39 +00001338/// \brief Determine whether a declaration is visible to name lookup.
1339///
1340/// This routine determines whether the declaration D is visible in the current
1341/// lookup context, taking into account the current template instantiation
1342/// stack. During template instantiation, a declaration is visible if it is
1343/// visible from a module containing any entity on the template instantiation
1344/// path (by instantiating a template, you allow it to see the declarations that
1345/// your module can see, including those later on in your module).
1346bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001347 assert(D->isHidden() && "should not call this: not in slow case");
Richard Smith42413142015-05-15 20:05:43 +00001348 Module *DeclModule = SemaRef.getOwningModule(D);
1349 if (!DeclModule) {
1350 // getOwningModule() may have decided the declaration should not be hidden.
1351 assert(!D->isHidden() && "hidden decl not from a module");
1352 return true;
1353 }
1354
1355 // If the owning module is visible, and the decl is not module private,
1356 // then the decl is visible too. (Module private is ignored within the same
1357 // top-level module.)
1358 if (!D->isFromASTFile() || !D->isModulePrivate()) {
1359 if (SemaRef.isModuleVisible(DeclModule))
1360 return true;
1361 // Also check merged definitions.
1362 if (SemaRef.getLangOpts().ModulesLocalVisibility &&
1363 SemaRef.hasVisibleMergedDefinition(D))
1364 return true;
1365 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001366
Richard Smithbe3980b2015-03-27 00:41:57 +00001367 // If this declaration is not at namespace scope nor module-private,
1368 // then it is visible if its lexical parent has a visible definition.
1369 DeclContext *DC = D->getLexicalDeclContext();
1370 if (!D->isModulePrivate() &&
1371 DC && !DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) {
Richard Smithc7d48d12015-05-20 17:50:35 +00001372 // For a parameter, check whether our current template declaration's
1373 // lexical context is visible, not whether there's some other visible
1374 // definition of it, because parameters aren't "within" the definition.
1375 if ((D->isTemplateParameter() || isa<ParmVarDecl>(D))
1376 ? isVisible(SemaRef, cast<NamedDecl>(DC))
1377 : SemaRef.hasVisibleDefinition(cast<NamedDecl>(DC))) {
Richard Smith42413142015-05-15 20:05:43 +00001378 if (SemaRef.ActiveTemplateInstantiations.empty() &&
1379 // FIXME: Do something better in this case.
1380 !SemaRef.getLangOpts().ModulesLocalVisibility) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001381 // Cache the fact that this declaration is implicitly visible because
1382 // its parent has a visible definition.
1383 D->setHidden(false);
1384 }
1385 return true;
1386 }
1387 return false;
1388 }
1389
Richard Smith0e5d7b82013-07-25 23:08:39 +00001390 // Find the extra places where we need to look.
1391 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
1392 if (LookupModules.empty())
1393 return false;
1394
1395 // If our lookup set contains the decl's module, it's visible.
1396 if (LookupModules.count(DeclModule))
1397 return true;
1398
1399 // If the declaration isn't exported, it's not visible in any other module.
1400 if (D->isModulePrivate())
1401 return false;
1402
1403 // Check whether DeclModule is transitively exported to an import of
1404 // the lookup set.
1405 for (llvm::DenseSet<Module *>::iterator I = LookupModules.begin(),
1406 E = LookupModules.end();
1407 I != E; ++I)
1408 if ((*I)->isModuleVisible(DeclModule))
1409 return true;
1410 return false;
1411}
1412
Richard Smith42413142015-05-15 20:05:43 +00001413bool Sema::isVisibleSlow(const NamedDecl *D) {
1414 return LookupResult::isVisible(*this, const_cast<NamedDecl*>(D));
1415}
1416
Douglas Gregor4a814562011-12-14 16:03:29 +00001417/// \brief Retrieve the visible declaration corresponding to D, if any.
1418///
1419/// This routine determines whether the declaration D is visible in the current
1420/// module, with the current imports. If not, it checks whether any
1421/// redeclaration of D is visible, and if so, returns that declaration.
Richard Smith0e5d7b82013-07-25 23:08:39 +00001422///
Douglas Gregor4a814562011-12-14 16:03:29 +00001423/// \returns D, or a visible previous declaration of D, whichever is more recent
1424/// and visible. If no declaration of D is visible, returns null.
Richard Smithe156254d2013-08-20 20:35:18 +00001425static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
1426 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
Richard Smith0e5d7b82013-07-25 23:08:39 +00001427
Aaron Ballman86c93902014-03-06 23:45:36 +00001428 for (auto RD : D->redecls()) {
1429 if (auto ND = dyn_cast<NamedDecl>(RD)) {
Richard Smithe8292b12015-02-10 03:28:10 +00001430 // FIXME: This is wrong in the case where the previous declaration is not
1431 // visible in the same scope as D. This needs to be done much more
1432 // carefully.
Richard Smithe156254d2013-08-20 20:35:18 +00001433 if (LookupResult::isVisible(SemaRef, ND))
Douglas Gregor54079202012-01-06 22:05:37 +00001434 return ND;
1435 }
Douglas Gregor4a814562011-12-14 16:03:29 +00001436 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001437
Craig Topperc3ec1492014-05-26 06:22:03 +00001438 return nullptr;
Douglas Gregor4a814562011-12-14 16:03:29 +00001439}
1440
Richard Smithe156254d2013-08-20 20:35:18 +00001441NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +00001442 return findAcceptableDecl(getSema(), D);
Richard Smithe156254d2013-08-20 20:35:18 +00001443}
1444
Douglas Gregor34074322009-01-14 22:20:51 +00001445/// @brief Perform unqualified name lookup starting from a given
1446/// scope.
1447///
1448/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1449/// used to find names within the current scope. For example, 'x' in
1450/// @code
1451/// int x;
1452/// int f() {
1453/// return x; // unqualified name look finds 'x' in the global scope
1454/// }
1455/// @endcode
1456///
1457/// Different lookup criteria can find different names. For example, a
1458/// particular scope can have both a struct and a function of the same
1459/// name, and each can be found by certain lookup criteria. For more
1460/// information about lookup criteria, see the documentation for the
1461/// class LookupCriteria.
1462///
1463/// @param S The scope from which unqualified name lookup will
1464/// begin. If the lookup criteria permits, name lookup may also search
1465/// in the parent scopes.
1466///
James Dennett91738ff2012-06-22 10:32:46 +00001467/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1468/// look up and the lookup kind), and is updated with the results of lookup
1469/// including zero or more declarations and possibly additional information
1470/// used to diagnose ambiguities.
Douglas Gregor34074322009-01-14 22:20:51 +00001471///
James Dennett91738ff2012-06-22 10:32:46 +00001472/// @returns \c true if lookup succeeded and false otherwise.
John McCall27b18f82009-11-17 02:14:36 +00001473bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1474 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001475 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001476
John McCall27b18f82009-11-17 02:14:36 +00001477 LookupNameKind NameKind = R.getLookupKind();
1478
David Blaikiebbafb8a2012-03-11 07:00:24 +00001479 if (!getLangOpts().CPlusPlus) {
Douglas Gregor34074322009-01-14 22:20:51 +00001480 // Unqualified name lookup in C/Objective-C is purely lexical, so
1481 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001482 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001483 // Find the nearest non-transparent declaration scope.
1484 while (!(S->getFlags() & Scope::DeclScope) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001485 (S->getEntity() && S->getEntity()->isTransparentContext()))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001486 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001487 }
1488
Richard Smith541b38b2013-09-20 01:15:31 +00001489 // When performing a scope lookup, we want to find local extern decls.
1490 FindLocalExternScope FindLocals(R);
1491
Douglas Gregor34074322009-01-14 22:20:51 +00001492 // Scan up the scope chain looking for a decl that matches this
1493 // identifier that is in the appropriate namespace. This search
1494 // should not take long, as shadowing of names is uncommon, and
1495 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001496 bool LeftStartingScope = false;
1497
Douglas Gregored8f2882009-01-30 01:04:22 +00001498 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001499 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001500 I != IEnd; ++I)
Richard Smith0e5d7b82013-07-25 23:08:39 +00001501 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001502 if (NameKind == LookupRedeclarationWithLinkage) {
1503 // Determine whether this (or a previous) declaration is
1504 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001505 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001506 LeftStartingScope = true;
1507
1508 // If we found something outside of our starting scope that
1509 // does not have linkage, skip it.
Richard Smith1c34fb72013-08-13 18:18:50 +00001510 if (LeftStartingScope && !((*I)->hasLinkage())) {
1511 R.setShadowed();
Douglas Gregoreddf4332009-02-24 20:03:32 +00001512 continue;
Richard Smith1c34fb72013-08-13 18:18:50 +00001513 }
Douglas Gregoreddf4332009-02-24 20:03:32 +00001514 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001515 else if (NameKind == LookupObjCImplicitSelfParam &&
1516 !isa<ImplicitParamDecl>(*I))
1517 continue;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001518
Douglas Gregor4a814562011-12-14 16:03:29 +00001519 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001520
Douglas Gregorb59643b2012-01-03 23:26:26 +00001521 // Check whether there are any other declarations with the same name
1522 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001523 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001524 // Find the scope in which this declaration was declared (if it
1525 // actually exists in a Scope).
1526 while (S && !S->isDeclScope(D))
1527 S = S->getParent();
1528
1529 // If the scope containing the declaration is the translation unit,
1530 // then we'll need to perform our checks based on the matching
1531 // DeclContexts rather than matching scopes.
1532 if (S && isNamespaceOrTranslationUnitScope(S))
Craig Topperc3ec1492014-05-26 06:22:03 +00001533 S = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001534
1535 // Compute the DeclContext, if we need it.
Craig Topperc3ec1492014-05-26 06:22:03 +00001536 DeclContext *DC = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001537 if (!S)
1538 DC = (*I)->getDeclContext()->getRedeclContext();
1539
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001540 IdentifierResolver::iterator LastI = I;
1541 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001542 if (S) {
1543 // Match based on scope.
1544 if (!S->isDeclScope(*LastI))
1545 break;
1546 } else {
1547 // Match based on DeclContext.
1548 DeclContext *LastDC
1549 = (*LastI)->getDeclContext()->getRedeclContext();
1550 if (!LastDC->Equals(DC))
1551 break;
1552 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001553
1554 // If the declaration is in the right namespace and visible, add it.
1555 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1556 R.addDecl(LastD);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001557 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001558
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001559 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001560 }
Richard Smith541b38b2013-09-20 01:15:31 +00001561
John McCall9f3059a2009-10-09 21:13:30 +00001562 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001563 }
Douglas Gregor34074322009-01-14 22:20:51 +00001564 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001565 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001566 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001567 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001568 }
1569
1570 // If we didn't find a use of this identifier, and if the identifier
1571 // corresponds to a compiler builtin, create the decl object for the builtin
1572 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001573 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1574 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001575
Axel Naumann016538a2011-02-24 16:47:47 +00001576 // If we didn't find a use of this identifier, the ExternalSource
1577 // may be able to handle the situation.
1578 // Note: some lookup failures are expected!
1579 // See e.g. R.isForRedeclaration().
1580 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001581}
1582
John McCall6538c932009-10-10 05:48:19 +00001583/// @brief Perform qualified name lookup in the namespaces nominated by
1584/// using directives by the given context.
1585///
1586/// C++98 [namespace.qual]p2:
James Dennett51a8d8b2012-06-19 21:05:49 +00001587/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6538c932009-10-10 05:48:19 +00001588/// (where X is the global namespace), let S be the set of all
1589/// declarations of m in X and in the transitive closure of all
1590/// namespaces nominated by using-directives in X and its used
1591/// namespaces, except that using-directives are ignored in any
1592/// namespace, including X, directly containing one or more
1593/// declarations of m. No namespace is searched more than once in
1594/// the lookup of a name. If S is the empty set, the program is
1595/// ill-formed. Otherwise, if S has exactly one member, or if the
1596/// context of the reference is a using-declaration
1597/// (namespace.udecl), S is the required set of declarations of
1598/// m. Otherwise if the use of m is not one that allows a unique
1599/// declaration to be chosen from S, the program is ill-formed.
James Dennett51a8d8b2012-06-19 21:05:49 +00001600///
John McCall6538c932009-10-10 05:48:19 +00001601/// C++98 [namespace.qual]p5:
1602/// During the lookup of a qualified namespace member name, if the
1603/// lookup finds more than one declaration of the member, and if one
1604/// declaration introduces a class name or enumeration name and the
1605/// other declarations either introduce the same object, the same
1606/// enumerator or a set of functions, the non-type name hides the
1607/// class or enumeration name if and only if the declarations are
1608/// from the same namespace; otherwise (the declarations are from
1609/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001610static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001611 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001612 assert(StartDC->isFileContext() && "start context is not a file context");
1613
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001614 DeclContext::udir_range UsingDirectives = StartDC->using_directives();
1615 if (UsingDirectives.begin() == UsingDirectives.end()) return false;
John McCall6538c932009-10-10 05:48:19 +00001616
1617 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001618 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001619 Visited.insert(StartDC);
1620
1621 // We have not yet looked into these namespaces, much less added
1622 // their "using-children" to the queue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001623 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001624
1625 // We have already looked into the initial namespace; seed the queue
1626 // with its using-children.
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001627 for (auto *I : UsingDirectives) {
1628 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +00001629 if (Visited.insert(ND).second)
John McCall6538c932009-10-10 05:48:19 +00001630 Queue.push_back(ND);
1631 }
1632
1633 // The easiest way to implement the restriction in [namespace.qual]p5
1634 // is to check whether any of the individual results found a tag
1635 // and, if so, to declare an ambiguity if the final result is not
1636 // a tag.
1637 bool FoundTag = false;
1638 bool FoundNonTag = false;
1639
John McCall5cebab12009-11-18 07:57:50 +00001640 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001641
1642 bool Found = false;
1643 while (!Queue.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001644 NamespaceDecl *ND = Queue.pop_back_val();
John McCall6538c932009-10-10 05:48:19 +00001645
1646 // We go through some convolutions here to avoid copying results
1647 // between LookupResults.
1648 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001649 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001650 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001651
1652 if (FoundDirect) {
1653 // First do any local hiding.
1654 DirectR.resolveKind();
1655
1656 // If the local result is a tag, remember that.
1657 if (DirectR.isSingleTagDecl())
1658 FoundTag = true;
1659 else
1660 FoundNonTag = true;
1661
1662 // Append the local results to the total results if necessary.
1663 if (UseLocal) {
1664 R.addAllDecls(LocalR);
1665 LocalR.clear();
1666 }
1667 }
1668
1669 // If we find names in this namespace, ignore its using directives.
1670 if (FoundDirect) {
1671 Found = true;
1672 continue;
1673 }
1674
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001675 for (auto I : ND->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00001676 NamespaceDecl *Nom = I->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +00001677 if (Visited.insert(Nom).second)
John McCall6538c932009-10-10 05:48:19 +00001678 Queue.push_back(Nom);
1679 }
1680 }
1681
1682 if (Found) {
1683 if (FoundTag && FoundNonTag)
1684 R.setAmbiguousQualifiedTagHiding();
1685 else
1686 R.resolveKind();
1687 }
1688
1689 return Found;
1690}
1691
Douglas Gregor39982192010-08-15 06:18:01 +00001692/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001693static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor39982192010-08-15 06:18:01 +00001694 CXXBasePath &Path,
1695 void *Name) {
1696 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001697
Douglas Gregor39982192010-08-15 06:18:01 +00001698 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1699 Path.Decls = BaseRecord->lookup(N);
David Blaikieff7d47a2012-12-19 00:45:41 +00001700 return !Path.Decls.empty();
Douglas Gregor39982192010-08-15 06:18:01 +00001701}
1702
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001703/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001704/// static members, nested types, and enumerators.
1705template<typename InputIterator>
1706static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1707 Decl *D = (*First)->getUnderlyingDecl();
1708 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1709 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001710
Douglas Gregorc0d24902010-10-22 22:08:47 +00001711 if (isa<CXXMethodDecl>(D)) {
1712 // Determine whether all of the methods are static.
1713 bool AllMethodsAreStatic = true;
1714 for(; First != Last; ++First) {
1715 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001716
Douglas Gregorc0d24902010-10-22 22:08:47 +00001717 if (!isa<CXXMethodDecl>(D)) {
1718 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1719 break;
1720 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001721
Douglas Gregorc0d24902010-10-22 22:08:47 +00001722 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1723 AllMethodsAreStatic = false;
1724 break;
1725 }
1726 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001727
Douglas Gregorc0d24902010-10-22 22:08:47 +00001728 if (AllMethodsAreStatic)
1729 return true;
1730 }
1731
1732 return false;
1733}
1734
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001735/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001736///
1737/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1738/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001739/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001740///
1741/// Different lookup criteria can find different names. For example, a
1742/// particular scope can have both a struct and a function of the same
1743/// name, and each can be found by certain lookup criteria. For more
1744/// information about lookup criteria, see the documentation for the
1745/// class LookupCriteria.
1746///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001747/// \param R captures both the lookup criteria and any lookup results found.
1748///
1749/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001750/// search. If the lookup criteria permits, name lookup may also search
1751/// in the parent contexts or (for C++ classes) base classes.
1752///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001753/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001754/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001755///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001756/// \returns true if lookup succeeded, false if it failed.
1757bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1758 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001759 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001760
John McCall27b18f82009-11-17 02:14:36 +00001761 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001762 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001763
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001764 // Make sure that the declaration context is complete.
1765 assert((!isa<TagDecl>(LookupCtx) ||
1766 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00001767 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith7d137e32012-03-23 03:33:32 +00001768 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001769 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001770
Douglas Gregor34074322009-01-14 22:20:51 +00001771 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001772 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001773 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001774 if (isa<CXXRecordDecl>(LookupCtx))
1775 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001776 return true;
1777 }
Douglas Gregor34074322009-01-14 22:20:51 +00001778
John McCall6538c932009-10-10 05:48:19 +00001779 // Don't descend into implied contexts for redeclarations.
1780 // C++98 [namespace.qual]p6:
1781 // In a declaration for a namespace member in which the
1782 // declarator-id is a qualified-id, given that the qualified-id
1783 // for the namespace member has the form
1784 // nested-name-specifier unqualified-id
1785 // the unqualified-id shall name a member of the namespace
1786 // designated by the nested-name-specifier.
1787 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001788 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001789 return false;
1790
John McCall27b18f82009-11-17 02:14:36 +00001791 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001792 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001793 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001794
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001795 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001796 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001797 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001798 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001799 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001800
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001801 // If we're performing qualified name lookup into a dependent class,
1802 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001803 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001804 // template instantiation time (at which point all bases will be available)
1805 // or we have to fail.
1806 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1807 LookupRec->hasAnyDependentBases()) {
1808 R.setNotFoundInCurrentInstantiation();
1809 return false;
1810 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001811
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001812 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001813 CXXBasePaths Paths;
1814 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001815
1816 // Look for this member in our base classes
Craig Topperc3ec1492014-05-26 06:22:03 +00001817 CXXRecordDecl::BaseMatchesCallback *BaseCallback = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00001818 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001819 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001820 case LookupOrdinaryName:
1821 case LookupMemberName:
1822 case LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +00001823 case LookupLocalFriendName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001824 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1825 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001826
Douglas Gregor36d1b142009-10-06 17:59:45 +00001827 case LookupTagName:
1828 BaseCallback = &CXXRecordDecl::FindTagMember;
1829 break;
John McCall84d87672009-12-10 09:41:52 +00001830
Douglas Gregor39982192010-08-15 06:18:01 +00001831 case LookupAnyName:
1832 BaseCallback = &LookupAnyMember;
1833 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001834
John McCall84d87672009-12-10 09:41:52 +00001835 case LookupUsingDeclName:
1836 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001837
Douglas Gregor36d1b142009-10-06 17:59:45 +00001838 case LookupOperatorName:
1839 case LookupNamespaceName:
1840 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001841 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001842 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001843 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001844
Douglas Gregor36d1b142009-10-06 17:59:45 +00001845 case LookupNestedNameSpecifierName:
1846 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1847 break;
1848 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001849
John McCall27b18f82009-11-17 02:14:36 +00001850 if (!LookupRec->lookupInBases(BaseCallback,
1851 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001852 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001853
John McCall553c0792010-01-23 00:46:32 +00001854 R.setNamingClass(LookupRec);
1855
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001856 // C++ [class.member.lookup]p2:
1857 // [...] If the resulting set of declarations are not all from
1858 // sub-objects of the same type, or the set has a nonstatic member
1859 // and includes members from distinct sub-objects, there is an
1860 // ambiguity and the program is ill-formed. Otherwise that set is
1861 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001862 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001863 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001864 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001865
Douglas Gregor36d1b142009-10-06 17:59:45 +00001866 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001867 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001868 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001869
John McCall401982f2010-01-20 21:53:11 +00001870 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1871 // across all paths.
1872 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001873
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001874 // Determine whether we're looking at a distinct sub-object or not.
1875 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001876 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001877 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1878 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001879 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001880 }
1881
Douglas Gregorc0d24902010-10-22 22:08:47 +00001882 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001883 != Context.getCanonicalType(PathElement.Base->getType())) {
1884 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001885 // different types. If the declaration sets aren't the same, this
Nikola Smiljanic1c125682014-07-09 05:42:35 +00001886 // lookup is ambiguous.
David Blaikieff7d47a2012-12-19 00:45:41 +00001887 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00001888 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikieff7d47a2012-12-19 00:45:41 +00001889 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
1890 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001891
David Blaikieff7d47a2012-12-19 00:45:41 +00001892 while (FirstD != FirstPath->Decls.end() &&
1893 CurrentD != Path->Decls.end()) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00001894 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1895 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1896 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001897
Douglas Gregorc0d24902010-10-22 22:08:47 +00001898 ++FirstD;
1899 ++CurrentD;
1900 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001901
David Blaikieff7d47a2012-12-19 00:45:41 +00001902 if (FirstD == FirstPath->Decls.end() &&
1903 CurrentD == Path->Decls.end())
Douglas Gregorc0d24902010-10-22 22:08:47 +00001904 continue;
1905 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001906
John McCall9f3059a2009-10-09 21:13:30 +00001907 R.setAmbiguousBaseSubobjectTypes(Paths);
1908 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001909 }
1910
Douglas Gregorc0d24902010-10-22 22:08:47 +00001911 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001912 // We have a different subobject of the same type.
1913
1914 // C++ [class.member.lookup]p5:
1915 // A static member, a nested type or an enumerator defined in
1916 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001917 // has more than one base class subobject of type T.
David Blaikieff7d47a2012-12-19 00:45:41 +00001918 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001919 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001920
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001921 // We have found a nonstatic member name in multiple, distinct
1922 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001923 R.setAmbiguousBaseSubobjects(Paths);
1924 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001925 }
1926 }
1927
1928 // Lookup in a base class succeeded; return these results.
1929
Aaron Ballman1e606f42014-07-15 22:03:49 +00001930 for (auto *D : Paths.front().Decls) {
John McCall553c0792010-01-23 00:46:32 +00001931 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1932 D->getAccess());
1933 R.addDecl(D, AS);
1934 }
John McCall9f3059a2009-10-09 21:13:30 +00001935 R.resolveKind();
1936 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001937}
1938
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00001939/// \brief Performs qualified name lookup or special type of lookup for
1940/// "__super::" scope specifier.
1941///
1942/// This routine is a convenience overload meant to be called from contexts
1943/// that need to perform a qualified name lookup with an optional C++ scope
1944/// specifier that might require special kind of lookup.
1945///
1946/// \param R captures both the lookup criteria and any lookup results found.
1947///
1948/// \param LookupCtx The context in which qualified name lookup will
1949/// search.
1950///
1951/// \param SS An optional C++ scope-specifier.
1952///
1953/// \returns true if lookup succeeded, false if it failed.
1954bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1955 CXXScopeSpec &SS) {
1956 auto *NNS = SS.getScopeRep();
1957 if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
1958 return LookupInSuper(R, NNS->getAsRecordDecl());
1959 else
1960
1961 return LookupQualifiedName(R, LookupCtx);
1962}
1963
Douglas Gregor34074322009-01-14 22:20:51 +00001964/// @brief Performs name lookup for a name that was parsed in the
1965/// source code, and may contain a C++ scope specifier.
1966///
1967/// This routine is a convenience routine meant to be called from
1968/// contexts that receive a name and an optional C++ scope specifier
1969/// (e.g., "N::M::x"). It will then perform either qualified or
1970/// unqualified name lookup (with LookupQualifiedName or LookupName,
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00001971/// respectively) on the given name and return those results. It will
1972/// perform a special type of lookup for "__super::" scope specifier.
Douglas Gregor34074322009-01-14 22:20:51 +00001973///
1974/// @param S The scope from which unqualified name lookup will
1975/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001976///
Douglas Gregore861bac2009-08-25 22:51:20 +00001977/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001978///
Douglas Gregore861bac2009-08-25 22:51:20 +00001979/// @param EnteringContext Indicates whether we are going to enter the
1980/// context of the scope-specifier SS (if present).
1981///
John McCall9f3059a2009-10-09 21:13:30 +00001982/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001983bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001984 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001985 if (SS && SS->isInvalid()) {
1986 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001987 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001988 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001989 }
Mike Stump11289f42009-09-09 15:08:12 +00001990
Douglas Gregore861bac2009-08-25 22:51:20 +00001991 if (SS && SS->isSet()) {
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00001992 NestedNameSpecifier *NNS = SS->getScopeRep();
1993 if (NNS->getKind() == NestedNameSpecifier::Super)
1994 return LookupInSuper(R, NNS->getAsRecordDecl());
1995
Douglas Gregore861bac2009-08-25 22:51:20 +00001996 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001997 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001998 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001999 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00002000 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002001
John McCall27b18f82009-11-17 02:14:36 +00002002 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00002003 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00002004 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002005
Douglas Gregore861bac2009-08-25 22:51:20 +00002006 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00002007 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00002008 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00002009 R.setNotFoundInCurrentInstantiation();
2010 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00002011 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00002012 }
2013
Mike Stump11289f42009-09-09 15:08:12 +00002014 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00002015 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00002016}
2017
Nikola Smiljanic67860242014-09-26 00:28:20 +00002018/// \brief Perform qualified name lookup into all base classes of the given
2019/// class.
2020///
2021/// \param R captures both the lookup criteria and any lookup results found.
2022///
2023/// \param Class The context in which qualified name lookup will
2024/// search. Name lookup will search in all base classes merging the results.
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002025///
2026/// @returns True if any decls were found (but possibly ambiguous)
2027bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
Nikola Smiljanic67860242014-09-26 00:28:20 +00002028 for (const auto &BaseSpec : Class->bases()) {
2029 CXXRecordDecl *RD = cast<CXXRecordDecl>(
2030 BaseSpec.getType()->castAs<RecordType>()->getDecl());
2031 LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
2032 Result.setBaseObjectType(Context.getRecordType(Class));
2033 LookupQualifiedName(Result, RD);
2034 for (auto *Decl : Result)
2035 R.addDecl(Decl);
2036 }
2037
2038 R.resolveKind();
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002039
2040 return !R.empty();
Nikola Smiljanic67860242014-09-26 00:28:20 +00002041}
Douglas Gregor889ceb72009-02-03 19:21:40 +00002042
James Dennett41725122012-06-22 10:16:05 +00002043/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002044/// from name lookup.
2045///
James Dennett41725122012-06-22 10:16:05 +00002046/// \param Result The result of the ambiguous lookup to be diagnosed.
Serge Pavlov99292092013-08-29 07:23:24 +00002047void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002048 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
2049
John McCall27b18f82009-11-17 02:14:36 +00002050 DeclarationName Name = Result.getLookupName();
2051 SourceLocation NameLoc = Result.getNameLoc();
2052 SourceRange LookupRange = Result.getContextRange();
2053
John McCall6538c932009-10-10 05:48:19 +00002054 switch (Result.getAmbiguityKind()) {
2055 case LookupResult::AmbiguousBaseSubobjects: {
2056 CXXBasePaths *Paths = Result.getBasePaths();
2057 QualType SubobjectType = Paths->front().back().Base->getType();
2058 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
2059 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
2060 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002061
David Blaikieff7d47a2012-12-19 00:45:41 +00002062 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6538c932009-10-10 05:48:19 +00002063 while (isa<CXXMethodDecl>(*Found) &&
2064 cast<CXXMethodDecl>(*Found)->isStatic())
2065 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002066
John McCall6538c932009-10-10 05:48:19 +00002067 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
Serge Pavlov99292092013-08-29 07:23:24 +00002068 break;
John McCall6538c932009-10-10 05:48:19 +00002069 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00002070
John McCall6538c932009-10-10 05:48:19 +00002071 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00002072 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
2073 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002074
John McCall6538c932009-10-10 05:48:19 +00002075 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002076 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00002077 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
2078 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002079 Path != PathEnd; ++Path) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002080 Decl *D = Path->Decls.front();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002081 if (DeclsPrinted.insert(D).second)
2082 Diag(D->getLocation(), diag::note_ambiguous_member_found);
2083 }
Serge Pavlov99292092013-08-29 07:23:24 +00002084 break;
Douglas Gregor1c846b02009-01-16 00:38:09 +00002085 }
2086
John McCall6538c932009-10-10 05:48:19 +00002087 case LookupResult::AmbiguousTagHiding: {
2088 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00002089
John McCall6538c932009-10-10 05:48:19 +00002090 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
2091
Aaron Ballman1e606f42014-07-15 22:03:49 +00002092 for (auto *D : Result)
2093 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
John McCall6538c932009-10-10 05:48:19 +00002094 TagDecls.insert(TD);
2095 Diag(TD->getLocation(), diag::note_hidden_tag);
2096 }
2097
Aaron Ballman1e606f42014-07-15 22:03:49 +00002098 for (auto *D : Result)
2099 if (!isa<TagDecl>(D))
2100 Diag(D->getLocation(), diag::note_hiding_object);
John McCall6538c932009-10-10 05:48:19 +00002101
2102 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00002103 LookupResult::Filter F = Result.makeFilter();
2104 while (F.hasNext()) {
2105 if (TagDecls.count(F.next()))
2106 F.erase();
2107 }
2108 F.done();
Serge Pavlov99292092013-08-29 07:23:24 +00002109 break;
John McCall6538c932009-10-10 05:48:19 +00002110 }
2111
2112 case LookupResult::AmbiguousReference: {
2113 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002114
Aaron Ballman1e606f42014-07-15 22:03:49 +00002115 for (auto *D : Result)
2116 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
Serge Pavlov99292092013-08-29 07:23:24 +00002117 break;
John McCall6538c932009-10-10 05:48:19 +00002118 }
Serge Pavlov99292092013-08-29 07:23:24 +00002119 }
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002120}
Douglas Gregore254f902009-02-04 00:32:51 +00002121
John McCallf24d7bb2010-05-28 18:45:08 +00002122namespace {
2123 struct AssociatedLookup {
John McCall7d8b0412012-08-24 20:38:34 +00002124 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallf24d7bb2010-05-28 18:45:08 +00002125 Sema::AssociatedNamespaceSet &Namespaces,
2126 Sema::AssociatedClassSet &Classes)
John McCall7d8b0412012-08-24 20:38:34 +00002127 : S(S), Namespaces(Namespaces), Classes(Classes),
2128 InstantiationLoc(InstantiationLoc) {
John McCallf24d7bb2010-05-28 18:45:08 +00002129 }
2130
2131 Sema &S;
2132 Sema::AssociatedNamespaceSet &Namespaces;
2133 Sema::AssociatedClassSet &Classes;
John McCall7d8b0412012-08-24 20:38:34 +00002134 SourceLocation InstantiationLoc;
John McCallf24d7bb2010-05-28 18:45:08 +00002135 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002136}
John McCallf24d7bb2010-05-28 18:45:08 +00002137
Mike Stump11289f42009-09-09 15:08:12 +00002138static void
John McCallf24d7bb2010-05-28 18:45:08 +00002139addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00002140
Douglas Gregor8b895222010-04-30 07:08:38 +00002141static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
2142 DeclContext *Ctx) {
2143 // Add the associated namespace for this class.
2144
2145 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
2146 // be a locally scoped record.
2147
Sebastian Redlbd595762010-08-31 20:53:31 +00002148 // We skip out of inline namespaces. The innermost non-inline namespace
2149 // contains all names of all its nested inline namespaces anyway, so we can
2150 // replace the entire inline namespace tree with its root.
2151 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
2152 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00002153 Ctx = Ctx->getParent();
2154
John McCallc7e8e792009-08-07 22:18:02 +00002155 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00002156 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00002157}
Douglas Gregor197e5f72009-07-08 07:51:57 +00002158
Mike Stump11289f42009-09-09 15:08:12 +00002159// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00002160// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00002161static void
John McCallf24d7bb2010-05-28 18:45:08 +00002162addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2163 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002164 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00002165 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00002166 switch (Arg.getKind()) {
2167 case TemplateArgument::Null:
2168 break;
Mike Stump11289f42009-09-09 15:08:12 +00002169
Douglas Gregor197e5f72009-07-08 07:51:57 +00002170 case TemplateArgument::Type:
2171 // [...] the namespaces and classes associated with the types of the
2172 // template arguments provided for template type parameters (excluding
2173 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00002174 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00002175 break;
Mike Stump11289f42009-09-09 15:08:12 +00002176
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002177 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002178 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00002179 // [...] the namespaces in which any template template arguments are
2180 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00002181 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002182 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00002183 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002184 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002185 DeclContext *Ctx = ClassTemplate->getDeclContext();
2186 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002187 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002188 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002189 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002190 }
2191 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002192 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002193
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002194 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00002195 case TemplateArgument::Integral:
2196 case TemplateArgument::Expression:
Eli Friedmanb826a002012-09-26 02:36:12 +00002197 case TemplateArgument::NullPtr:
Mike Stump11289f42009-09-09 15:08:12 +00002198 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00002199 // associated namespaces. ]
2200 break;
Mike Stump11289f42009-09-09 15:08:12 +00002201
Douglas Gregor197e5f72009-07-08 07:51:57 +00002202 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00002203 for (const auto &P : Arg.pack_elements())
2204 addAssociatedClassesAndNamespaces(Result, P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002205 break;
2206 }
2207}
2208
Douglas Gregore254f902009-02-04 00:32:51 +00002209// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00002210// argument-dependent lookup with an argument of class type
2211// (C++ [basic.lookup.koenig]p2).
2212static void
John McCallf24d7bb2010-05-28 18:45:08 +00002213addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2214 CXXRecordDecl *Class) {
2215
2216 // Just silently ignore anything whose name is __va_list_tag.
2217 if (Class->getDeclName() == Result.S.VAListTagName)
2218 return;
2219
Douglas Gregore254f902009-02-04 00:32:51 +00002220 // C++ [basic.lookup.koenig]p2:
2221 // [...]
2222 // -- If T is a class type (including unions), its associated
2223 // classes are: the class itself; the class of which it is a
2224 // member, if any; and its direct and indirect base
2225 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00002226 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00002227
2228 // Add the class of which it is a member, if any.
2229 DeclContext *Ctx = Class->getDeclContext();
2230 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002231 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002232 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002233 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002234
Douglas Gregore254f902009-02-04 00:32:51 +00002235 // Add the class itself. If we've already seen this class, we don't
2236 // need to visit base classes.
Richard Smith594461f2014-03-14 22:07:27 +00002237 //
2238 // FIXME: That's not correct, we may have added this class only because it
2239 // was the enclosing class of another class, and in that case we won't have
2240 // added its base classes yet.
David Blaikie82e95a32014-11-19 07:49:47 +00002241 if (!Result.Classes.insert(Class).second)
Douglas Gregore254f902009-02-04 00:32:51 +00002242 return;
2243
Mike Stump11289f42009-09-09 15:08:12 +00002244 // -- If T is a template-id, its associated namespaces and classes are
2245 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002246 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00002247 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00002248 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00002249 // namespaces in which any template template arguments are defined; and
2250 // the classes in which any member templates used as template template
2251 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00002252 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00002253 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00002254 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2255 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2256 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002257 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002258 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002259 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002260
Douglas Gregor197e5f72009-07-08 07:51:57 +00002261 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2262 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00002263 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002264 }
Mike Stump11289f42009-09-09 15:08:12 +00002265
John McCall67da35c2010-02-04 22:26:26 +00002266 // Only recurse into base classes for complete types.
Richard Smith594461f2014-03-14 22:07:27 +00002267 if (!Class->hasDefinition())
2268 return;
John McCall67da35c2010-02-04 22:26:26 +00002269
Douglas Gregore254f902009-02-04 00:32:51 +00002270 // Add direct and indirect base classes along with their associated
2271 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002272 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00002273 Bases.push_back(Class);
2274 while (!Bases.empty()) {
2275 // Pop this class off the stack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002276 Class = Bases.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002277
2278 // Visit the base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +00002279 for (const auto &Base : Class->bases()) {
2280 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00002281 // In dependent contexts, we do ADL twice, and the first time around,
2282 // the base type might be a dependent TemplateSpecializationType, or a
2283 // TemplateTypeParmType. If that happens, simply ignore it.
2284 // FIXME: If we want to support export, we probably need to add the
2285 // namespace of the template in a TemplateSpecializationType, or even
2286 // the classes and namespaces of known non-dependent arguments.
2287 if (!BaseType)
2288 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002289 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
David Blaikie82e95a32014-11-19 07:49:47 +00002290 if (Result.Classes.insert(BaseDecl).second) {
Douglas Gregore254f902009-02-04 00:32:51 +00002291 // Find the associated namespace for this base class.
2292 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00002293 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00002294
2295 // Make sure we visit the bases of this base class.
2296 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2297 Bases.push_back(BaseDecl);
2298 }
2299 }
2300 }
2301}
2302
2303// \brief Add the associated classes and namespaces for
2304// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00002305// (C++ [basic.lookup.koenig]p2).
2306static void
John McCallf24d7bb2010-05-28 18:45:08 +00002307addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00002308 // C++ [basic.lookup.koenig]p2:
2309 //
2310 // For each argument type T in the function call, there is a set
2311 // of zero or more associated namespaces and a set of zero or more
2312 // associated classes to be considered. The sets of namespaces and
2313 // classes is determined entirely by the types of the function
2314 // arguments (and the namespace of any template template
2315 // argument). Typedef names and using-declarations used to specify
2316 // the types do not contribute to this set. The sets of namespaces
2317 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00002318
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002319 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00002320 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2321
Douglas Gregore254f902009-02-04 00:32:51 +00002322 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00002323 switch (T->getTypeClass()) {
2324
2325#define TYPE(Class, Base)
2326#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2327#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2328#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2329#define ABSTRACT_TYPE(Class, Base)
2330#include "clang/AST/TypeNodes.def"
2331 // T is canonical. We can also ignore dependent types because
2332 // we don't need to do ADL at the definition point, but if we
2333 // wanted to implement template export (or if we find some other
2334 // use for associated classes and namespaces...) this would be
2335 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00002336 break;
Douglas Gregore254f902009-02-04 00:32:51 +00002337
John McCall0af3d3b2010-05-28 06:08:54 +00002338 // -- If T is a pointer to U or an array of U, its associated
2339 // namespaces and classes are those associated with U.
2340 case Type::Pointer:
2341 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2342 continue;
2343 case Type::ConstantArray:
2344 case Type::IncompleteArray:
2345 case Type::VariableArray:
2346 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2347 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002348
John McCall0af3d3b2010-05-28 06:08:54 +00002349 // -- If T is a fundamental type, its associated sets of
2350 // namespaces and classes are both empty.
2351 case Type::Builtin:
2352 break;
2353
2354 // -- If T is a class type (including unions), its associated
2355 // classes are: the class itself; the class of which it is a
2356 // member, if any; and its direct and indirect base
2357 // classes. Its associated namespaces are the namespaces in
2358 // which its associated classes are defined.
2359 case Type::Record: {
Richard Smith594461f2014-03-14 22:07:27 +00002360 Result.S.RequireCompleteType(Result.InstantiationLoc, QualType(T, 0),
2361 /*no diagnostic*/ 0);
John McCall0af3d3b2010-05-28 06:08:54 +00002362 CXXRecordDecl *Class
2363 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002364 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00002365 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00002366 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00002367
John McCall0af3d3b2010-05-28 06:08:54 +00002368 // -- If T is an enumeration type, its associated namespace is
2369 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002370 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00002371 // it has no associated class.
2372 case Type::Enum: {
2373 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002374
John McCall0af3d3b2010-05-28 06:08:54 +00002375 DeclContext *Ctx = Enum->getDeclContext();
2376 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002377 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002378
John McCall0af3d3b2010-05-28 06:08:54 +00002379 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002380 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00002381
John McCall0af3d3b2010-05-28 06:08:54 +00002382 break;
2383 }
2384
2385 // -- If T is a function type, its associated namespaces and
2386 // classes are those associated with the function parameter
2387 // types and those associated with the return type.
2388 case Type::FunctionProto: {
2389 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002390 for (const auto &Arg : Proto->param_types())
2391 Queue.push_back(Arg.getTypePtr());
John McCall0af3d3b2010-05-28 06:08:54 +00002392 // fallthrough
2393 }
2394 case Type::FunctionNoProto: {
2395 const FunctionType *FnType = cast<FunctionType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00002396 T = FnType->getReturnType().getTypePtr();
John McCall0af3d3b2010-05-28 06:08:54 +00002397 continue;
2398 }
2399
2400 // -- If T is a pointer to a member function of a class X, its
2401 // associated namespaces and classes are those associated
2402 // with the function parameter types and return type,
2403 // together with those associated with X.
2404 //
2405 // -- If T is a pointer to a data member of class X, its
2406 // associated namespaces and classes are those associated
2407 // with the member type together with those associated with
2408 // X.
2409 case Type::MemberPointer: {
2410 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2411
2412 // Queue up the class type into which this points.
2413 Queue.push_back(MemberPtr->getClass());
2414
2415 // And directly continue with the pointee type.
2416 T = MemberPtr->getPointeeType().getTypePtr();
2417 continue;
2418 }
2419
2420 // As an extension, treat this like a normal pointer.
2421 case Type::BlockPointer:
2422 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2423 continue;
2424
2425 // References aren't covered by the standard, but that's such an
2426 // obvious defect that we cover them anyway.
2427 case Type::LValueReference:
2428 case Type::RValueReference:
2429 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2430 continue;
2431
2432 // These are fundamental types.
2433 case Type::Vector:
2434 case Type::ExtVector:
2435 case Type::Complex:
2436 break;
2437
Richard Smith27d807c2013-04-30 13:56:41 +00002438 // Non-deduced auto types only get here for error cases.
2439 case Type::Auto:
2440 break;
2441
Douglas Gregor8e936662011-04-12 01:02:45 +00002442 // If T is an Objective-C object or interface type, or a pointer to an
2443 // object or interface type, the associated namespace is the global
2444 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002445 case Type::ObjCObject:
2446 case Type::ObjCInterface:
2447 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002448 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002449 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002450
2451 // Atomic types are just wrappers; use the associations of the
2452 // contained type.
2453 case Type::Atomic:
2454 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2455 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002456 }
2457
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002458 if (Queue.empty())
2459 break;
2460 T = Queue.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002461 }
Douglas Gregore254f902009-02-04 00:32:51 +00002462}
2463
2464/// \brief Find the associated classes and namespaces for
2465/// argument-dependent lookup for a call with the given set of
2466/// arguments.
2467///
2468/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002469/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002470/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00002471void Sema::FindAssociatedClassesAndNamespaces(
2472 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2473 AssociatedNamespaceSet &AssociatedNamespaces,
2474 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002475 AssociatedNamespaces.clear();
2476 AssociatedClasses.clear();
2477
John McCall7d8b0412012-08-24 20:38:34 +00002478 AssociatedLookup Result(*this, InstantiationLoc,
2479 AssociatedNamespaces, AssociatedClasses);
John McCallf24d7bb2010-05-28 18:45:08 +00002480
Douglas Gregore254f902009-02-04 00:32:51 +00002481 // C++ [basic.lookup.koenig]p2:
2482 // For each argument type T in the function call, there is a set
2483 // of zero or more associated namespaces and a set of zero or more
2484 // associated classes to be considered. The sets of namespaces and
2485 // classes is determined entirely by the types of the function
2486 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002487 // argument).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002488 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregore254f902009-02-04 00:32:51 +00002489 Expr *Arg = Args[ArgIdx];
2490
2491 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002492 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002493 continue;
2494 }
2495
2496 // [...] In addition, if the argument is the name or address of a
2497 // set of overloaded functions and/or function templates, its
2498 // associated classes and namespaces are the union of those
2499 // associated with each of the members of the set: the namespace
2500 // in which the function or function template is defined and the
2501 // classes and namespaces associated with its (non-dependent)
2502 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002503 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002504 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002505 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002506 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002507
John McCallf24d7bb2010-05-28 18:45:08 +00002508 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2509 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002510
Aaron Ballman1e606f42014-07-15 22:03:49 +00002511 for (const auto *D : ULE->decls()) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002512 // Look through any using declarations to find the underlying function.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002513 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
Douglas Gregore254f902009-02-04 00:32:51 +00002514
2515 // Add the classes and namespaces associated with the parameter
2516 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002517 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002518 }
2519 }
2520}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002521
John McCall5cebab12009-11-18 07:57:50 +00002522NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002523 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002524 LookupNameKind NameKind,
2525 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002526 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002527 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002528 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002529}
2530
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002531/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002532ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002533 SourceLocation IdLoc,
2534 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002535 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002536 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002537 return cast_or_null<ObjCProtocolDecl>(D);
2538}
2539
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002540void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002541 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002542 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002543 // C++ [over.match.oper]p3:
2544 // -- The set of non-member candidates is the result of the
2545 // unqualified lookup of operator@ in the context of the
2546 // expression according to the usual rules for name lookup in
2547 // unqualified function calls (3.4.2) except that all member
Richard Smith100b24a2014-04-17 01:52:14 +00002548 // functions are ignored.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002549 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002550 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2551 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002552
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002553 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
Richard Smith100b24a2014-04-17 01:52:14 +00002554 Functions.append(Operators.begin(), Operators.end());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002555}
2556
Alexis Hunt1da39282011-06-24 02:11:39 +00002557Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002558 CXXSpecialMember SM,
2559 bool ConstArg,
2560 bool VolatileArg,
2561 bool RValueThis,
2562 bool ConstThis,
2563 bool VolatileThis) {
Richard Smith7d125a12012-11-27 21:20:31 +00002564 assert(CanDeclareSpecialMemberFunction(RD) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002565 "doing special member lookup into record that isn't fully complete");
Richard Smith7d125a12012-11-27 21:20:31 +00002566 RD = RD->getDefinition();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002567 if (RValueThis || ConstThis || VolatileThis)
2568 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2569 "constructors and destructors always have unqualified lvalue this");
2570 if (ConstArg || VolatileArg)
2571 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2572 "parameter-less special members can't have qualified arguments");
2573
2574 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002575 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002576 ID.AddInteger(SM);
2577 ID.AddInteger(ConstArg);
2578 ID.AddInteger(VolatileArg);
2579 ID.AddInteger(RValueThis);
2580 ID.AddInteger(ConstThis);
2581 ID.AddInteger(VolatileThis);
2582
2583 void *InsertPoint;
2584 SpecialMemberOverloadResult *Result =
2585 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2586
2587 // This was already cached
2588 if (Result)
2589 return Result;
2590
Alexis Huntba8e18d2011-06-07 00:11:58 +00002591 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2592 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002593 SpecialMemberCache.InsertNode(Result, InsertPoint);
2594
2595 if (SM == CXXDestructor) {
Richard Smith2be35f52012-12-01 02:35:44 +00002596 if (RD->needsImplicitDestructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002597 DeclareImplicitDestructor(RD);
2598 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002599 assert(DD && "record without a destructor");
2600 Result->setMethod(DD);
Richard Smith852265f2012-03-30 20:53:28 +00002601 Result->setKind(DD->isDeleted() ?
2602 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith83c478d2012-04-20 18:46:14 +00002603 SpecialMemberOverloadResult::Success);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002604 return Result;
2605 }
2606
Alexis Hunteef8ee02011-06-10 03:50:41 +00002607 // Prepare for overload resolution. Here we construct a synthetic argument
2608 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002609 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002610 DeclarationName Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002611 Expr *Arg = nullptr;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002612 unsigned NumArgs;
2613
Richard Smith83c478d2012-04-20 18:46:14 +00002614 QualType ArgType = CanTy;
2615 ExprValueKind VK = VK_LValue;
2616
Alexis Hunteef8ee02011-06-10 03:50:41 +00002617 if (SM == CXXDefaultConstructor) {
2618 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2619 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002620 if (RD->needsImplicitDefaultConstructor())
2621 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002622 } else {
2623 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2624 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smith2be35f52012-12-01 02:35:44 +00002625 if (RD->needsImplicitCopyConstructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002626 DeclareImplicitCopyConstructor(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002627 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002628 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002629 } else {
2630 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smith2be35f52012-12-01 02:35:44 +00002631 if (RD->needsImplicitCopyAssignment())
Alexis Hunt1da39282011-06-24 02:11:39 +00002632 DeclareImplicitCopyAssignment(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002633 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002634 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002635 }
2636
Alexis Hunteef8ee02011-06-10 03:50:41 +00002637 if (ConstArg)
2638 ArgType.addConst();
2639 if (VolatileArg)
2640 ArgType.addVolatile();
2641
2642 // This isn't /really/ specified by the standard, but it's implied
2643 // we should be working from an RValue in the case of move to ensure
2644 // that we prefer to bind to rvalue references, and an LValue in the
2645 // case of copy to ensure we don't bind to rvalue references.
2646 // Possibly an XValue is actually correct in the case of move, but
2647 // there is no semantic difference for class types in this restricted
2648 // case.
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002649 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002650 VK = VK_LValue;
2651 else
2652 VK = VK_RValue;
Richard Smith83c478d2012-04-20 18:46:14 +00002653 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00002654
Richard Smith83c478d2012-04-20 18:46:14 +00002655 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2656
2657 if (SM != CXXDefaultConstructor) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002658 NumArgs = 1;
Richard Smith83c478d2012-04-20 18:46:14 +00002659 Arg = &FakeArg;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002660 }
2661
2662 // Create the object argument
2663 QualType ThisTy = CanTy;
2664 if (ConstThis)
2665 ThisTy.addConst();
2666 if (VolatileThis)
2667 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002668 Expr::Classification Classification =
Richard Smith83c478d2012-04-20 18:46:14 +00002669 OpaqueValueExpr(SourceLocation(), ThisTy,
2670 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002671
2672 // Now we perform lookup on the name we computed earlier and do overload
2673 // resolution. Lookup is only performed directly into the class since there
2674 // will always be a (possibly implicit) declaration to shadow any others.
Richard Smith100b24a2014-04-17 01:52:14 +00002675 OverloadCandidateSet OCS(RD->getLocation(), OverloadCandidateSet::CSK_Normal);
David Blaikieff7d47a2012-12-19 00:45:41 +00002676 DeclContext::lookup_result R = RD->lookup(Name);
Richard Smith8c37ab52015-02-11 01:48:47 +00002677
2678 if (R.empty()) {
2679 // We might have no default constructor because we have a lambda's closure
2680 // type, rather than because there's some other declared constructor.
2681 // Every class has a copy/move constructor, copy/move assignment, and
2682 // destructor.
2683 assert(SM == CXXDefaultConstructor &&
2684 "lookup for a constructor or assignment operator was empty");
2685 Result->setMethod(nullptr);
2686 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
2687 return Result;
2688 }
Chandler Carruth7deaae72013-08-18 07:20:52 +00002689
2690 // Copy the candidates as our processing of them may load new declarations
2691 // from an external source and invalidate lookup_result.
2692 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2693
Aaron Ballman1e606f42014-07-15 22:03:49 +00002694 for (auto *Cand : Candidates) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002695 if (Cand->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002696 continue;
2697
Alexis Hunt1da39282011-06-24 02:11:39 +00002698 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2699 // FIXME: [namespace.udecl]p15 says that we should only consider a
2700 // using declaration here if it does not match a declaration in the
2701 // derived class. We do not implement this correctly in other cases
2702 // either.
2703 Cand = U->getTargetDecl();
2704
2705 if (Cand->isInvalidDecl())
2706 continue;
2707 }
2708
2709 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002710 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Alexis Hunt1da39282011-06-24 02:11:39 +00002711 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002712 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2713 OCS, true);
Alexis Hunt080709f2011-06-23 00:26:20 +00002714 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002715 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2716 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt2949f022011-06-22 02:58:46 +00002717 } else if (FunctionTemplateDecl *Tmpl =
Alexis Hunt1da39282011-06-24 02:11:39 +00002718 dyn_cast<FunctionTemplateDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002719 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2720 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Craig Topperc3ec1492014-05-26 06:22:03 +00002721 RD, nullptr, ThisTy, Classification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002722 llvm::makeArrayRef(&Arg, NumArgs),
Alexis Hunt080709f2011-06-23 00:26:20 +00002723 OCS, true);
2724 else
2725 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Craig Topperc3ec1492014-05-26 06:22:03 +00002726 nullptr, llvm::makeArrayRef(&Arg, NumArgs),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002727 OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002728 } else {
2729 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002730 }
2731 }
2732
2733 OverloadCandidateSet::iterator Best;
2734 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2735 case OR_Success:
2736 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith83c478d2012-04-20 18:46:14 +00002737 Result->setKind(SpecialMemberOverloadResult::Success);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002738 break;
2739
2740 case OR_Deleted:
2741 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith852265f2012-03-30 20:53:28 +00002742 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002743 break;
2744
2745 case OR_Ambiguous:
Craig Topperc3ec1492014-05-26 06:22:03 +00002746 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00002747 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2748 break;
2749
Alexis Hunteef8ee02011-06-10 03:50:41 +00002750 case OR_No_Viable_Function:
Craig Topperc3ec1492014-05-26 06:22:03 +00002751 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00002752 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002753 break;
2754 }
2755
2756 return Result;
2757}
2758
2759/// \brief Look up the default constructor for the given class.
2760CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002761 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002762 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2763 false, false);
2764
2765 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002766}
2767
Alexis Hunt491ec602011-06-21 23:42:56 +00002768/// \brief Look up the copying constructor for the given class.
2769CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith83c478d2012-04-20 18:46:14 +00002770 unsigned Quals) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002771 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2772 "non-const, non-volatile qualifiers for copy ctor arg");
2773 SpecialMemberOverloadResult *Result =
2774 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2775 Quals & Qualifiers::Volatile, false, false, false);
2776
Alexis Hunt899bd442011-06-10 04:44:37 +00002777 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2778}
2779
Sebastian Redl22653ba2011-08-30 19:58:05 +00002780/// \brief Look up the moving constructor for the given class.
Richard Smith1c6461e2012-07-18 03:36:00 +00002781CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2782 unsigned Quals) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002783 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002784 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2785 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002786
2787 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2788}
2789
Douglas Gregor52b72822010-07-02 23:12:18 +00002790/// \brief Look up the constructors for the given class.
2791DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002792 // If the implicit constructors have not yet been declared, do so now.
Richard Smith7d125a12012-11-27 21:20:31 +00002793 if (CanDeclareSpecialMemberFunction(Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00002794 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002795 DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +00002796 if (Class->needsImplicitCopyConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002797 DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002798 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002799 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00002800 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002801
Douglas Gregor52b72822010-07-02 23:12:18 +00002802 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2803 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2804 return Class->lookup(Name);
2805}
2806
Alexis Hunt491ec602011-06-21 23:42:56 +00002807/// \brief Look up the copying assignment operator for the given class.
2808CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2809 unsigned Quals, bool RValueThis,
Richard Smith83c478d2012-04-20 18:46:14 +00002810 unsigned ThisQuals) {
Alexis Hunt491ec602011-06-21 23:42:56 +00002811 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2812 "non-const, non-volatile qualifiers for copy assignment arg");
2813 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2814 "non-const, non-volatile qualifiers for copy assignment this");
2815 SpecialMemberOverloadResult *Result =
2816 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2817 Quals & Qualifiers::Volatile, RValueThis,
2818 ThisQuals & Qualifiers::Const,
2819 ThisQuals & Qualifiers::Volatile);
2820
Alexis Hunt491ec602011-06-21 23:42:56 +00002821 return Result->getMethod();
2822}
2823
Sebastian Redl22653ba2011-08-30 19:58:05 +00002824/// \brief Look up the moving assignment operator for the given class.
2825CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith1c6461e2012-07-18 03:36:00 +00002826 unsigned Quals,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002827 bool RValueThis,
2828 unsigned ThisQuals) {
2829 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2830 "non-const, non-volatile qualifiers for copy assignment this");
2831 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002832 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2833 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002834 ThisQuals & Qualifiers::Const,
2835 ThisQuals & Qualifiers::Volatile);
2836
2837 return Result->getMethod();
2838}
2839
Douglas Gregore71edda2010-07-01 22:47:18 +00002840/// \brief Look for the destructor of the given class.
2841///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00002842/// During semantic analysis, this routine should be used in lieu of
2843/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00002844///
2845/// \returns The destructor for this class.
2846CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002847 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2848 false, false, false,
2849 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00002850}
2851
Richard Smithbcc22fc2012-03-09 08:00:36 +00002852/// LookupLiteralOperator - Determine which literal operator should be used for
2853/// a user-defined literal, per C++11 [lex.ext].
2854///
2855/// Normal overload resolution is not used to select which literal operator to
2856/// call for a user-defined literal. Look up the provided literal operator name,
2857/// and filter the results to the appropriate set for the given argument types.
2858Sema::LiteralOperatorLookupResult
2859Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2860 ArrayRef<QualType> ArgTys,
Richard Smithb8b41d32013-10-07 19:57:58 +00002861 bool AllowRaw, bool AllowTemplate,
2862 bool AllowStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002863 LookupName(R, S);
2864 assert(R.getResultKind() != LookupResult::Ambiguous &&
2865 "literal operator lookup can't be ambiguous");
2866
2867 // Filter the lookup results appropriately.
2868 LookupResult::Filter F = R.makeFilter();
2869
Richard Smithbcc22fc2012-03-09 08:00:36 +00002870 bool FoundRaw = false;
Richard Smithb8b41d32013-10-07 19:57:58 +00002871 bool FoundTemplate = false;
2872 bool FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002873 bool FoundExactMatch = false;
2874
2875 while (F.hasNext()) {
2876 Decl *D = F.next();
2877 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2878 D = USD->getTargetDecl();
2879
Douglas Gregorc1970572013-04-10 05:18:00 +00002880 // If the declaration we found is invalid, skip it.
2881 if (D->isInvalidDecl()) {
2882 F.erase();
2883 continue;
2884 }
2885
Richard Smithb8b41d32013-10-07 19:57:58 +00002886 bool IsRaw = false;
2887 bool IsTemplate = false;
2888 bool IsStringTemplate = false;
2889 bool IsExactMatch = false;
2890
Richard Smithbcc22fc2012-03-09 08:00:36 +00002891 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2892 if (FD->getNumParams() == 1 &&
2893 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2894 IsRaw = true;
Richard Smith550de452013-01-15 07:12:59 +00002895 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002896 IsExactMatch = true;
2897 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2898 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2899 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2900 IsExactMatch = false;
2901 break;
2902 }
2903 }
2904 }
2905 }
Richard Smithb8b41d32013-10-07 19:57:58 +00002906 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
2907 TemplateParameterList *Params = FD->getTemplateParameters();
2908 if (Params->size() == 1)
2909 IsTemplate = true;
2910 else
2911 IsStringTemplate = true;
2912 }
Richard Smithbcc22fc2012-03-09 08:00:36 +00002913
2914 if (IsExactMatch) {
2915 FoundExactMatch = true;
Richard Smithb8b41d32013-10-07 19:57:58 +00002916 AllowRaw = false;
2917 AllowTemplate = false;
2918 AllowStringTemplate = false;
2919 if (FoundRaw || FoundTemplate || FoundStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002920 // Go through again and remove the raw and template decls we've
2921 // already found.
2922 F.restart();
Richard Smithb8b41d32013-10-07 19:57:58 +00002923 FoundRaw = FoundTemplate = FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002924 }
Richard Smithb8b41d32013-10-07 19:57:58 +00002925 } else if (AllowRaw && IsRaw) {
2926 FoundRaw = true;
2927 } else if (AllowTemplate && IsTemplate) {
2928 FoundTemplate = true;
2929 } else if (AllowStringTemplate && IsStringTemplate) {
2930 FoundStringTemplate = true;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002931 } else {
2932 F.erase();
2933 }
2934 }
2935
2936 F.done();
2937
2938 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2939 // parameter type, that is used in preference to a raw literal operator
2940 // or literal operator template.
2941 if (FoundExactMatch)
2942 return LOLR_Cooked;
2943
2944 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2945 // operator template, but not both.
2946 if (FoundRaw && FoundTemplate) {
2947 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
Alp Tokera2794f92014-01-22 07:29:52 +00002948 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2949 NoteOverloadCandidate((*I)->getUnderlyingDecl()->getAsFunction());
Richard Smithbcc22fc2012-03-09 08:00:36 +00002950 return LOLR_Error;
2951 }
2952
2953 if (FoundRaw)
2954 return LOLR_Raw;
2955
2956 if (FoundTemplate)
2957 return LOLR_Template;
2958
Richard Smithb8b41d32013-10-07 19:57:58 +00002959 if (FoundStringTemplate)
2960 return LOLR_StringTemplate;
2961
Richard Smithbcc22fc2012-03-09 08:00:36 +00002962 // Didn't find anything we could use.
2963 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2964 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
Richard Smithb8b41d32013-10-07 19:57:58 +00002965 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
2966 << (AllowTemplate || AllowStringTemplate);
Richard Smithbcc22fc2012-03-09 08:00:36 +00002967 return LOLR_Error;
2968}
2969
John McCall8fe68082010-01-26 07:16:45 +00002970void ADLResult::insert(NamedDecl *New) {
2971 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2972
2973 // If we haven't yet seen a decl for this key, or the last decl
2974 // was exactly this one, we're done.
Craig Topperc3ec1492014-05-26 06:22:03 +00002975 if (Old == nullptr || Old == New) {
John McCall8fe68082010-01-26 07:16:45 +00002976 Old = New;
2977 return;
2978 }
2979
2980 // Otherwise, decide which is a more recent redeclaration.
Alp Tokera2794f92014-01-22 07:29:52 +00002981 FunctionDecl *OldFD = Old->getAsFunction();
2982 FunctionDecl *NewFD = New->getAsFunction();
John McCall8fe68082010-01-26 07:16:45 +00002983
2984 FunctionDecl *Cursor = NewFD;
2985 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002986 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00002987
2988 // If we got to the end without finding OldFD, OldFD is the newer
2989 // declaration; leave things as they are.
2990 if (!Cursor) return;
2991
2992 // If we do find OldFD, then NewFD is newer.
2993 if (Cursor == OldFD) break;
2994
2995 // Otherwise, keep looking.
2996 }
2997
2998 Old = New;
2999}
3000
Richard Smith100b24a2014-04-17 01:52:14 +00003001void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3002 ArrayRef<Expr *> Args, ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003003 // Find all of the associated namespaces and classes based on the
3004 // arguments we have.
3005 AssociatedNamespaceSet AssociatedNamespaces;
3006 AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00003007 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCallc7e8e792009-08-07 22:18:02 +00003008 AssociatedNamespaces,
3009 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003010
3011 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003012 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3013 // and let Y be the lookup set produced by argument dependent
3014 // lookup (defined as follows). If X contains [...] then Y is
3015 // empty. Otherwise Y is the set of declarations found in the
3016 // namespaces associated with the argument types as described
3017 // below. The set of declarations found by the lookup of the name
3018 // is the union of X and Y.
3019 //
3020 // Here, we compute Y and add its members to the overloaded
3021 // candidate set.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003022 for (auto *NS : AssociatedNamespaces) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003023 // When considering an associated namespace, the lookup is the
3024 // same as the lookup performed when the associated namespace is
3025 // used as a qualifier (3.4.3.2) except that:
3026 //
3027 // -- Any using-directives in the associated namespace are
3028 // ignored.
3029 //
John McCallc7e8e792009-08-07 22:18:02 +00003030 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003031 // associated classes are visible within their respective
3032 // namespaces even if they are not visible during an ordinary
3033 // lookup (11.4).
Aaron Ballman1e606f42014-07-15 22:03:49 +00003034 DeclContext::lookup_result R = NS->lookup(Name);
3035 for (auto *D : R) {
John McCallaa74a0c2009-08-28 07:59:38 +00003036 // If the only declaration here is an ordinary friend, consider
3037 // it only if it was declared in an associated classes.
Richard Smith541b38b2013-09-20 01:15:31 +00003038 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) {
3039 // If it's neither ordinarily visible nor a friend, we can't find it.
3040 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0)
3041 continue;
3042
Richard Smith64017682013-07-17 23:53:16 +00003043 bool DeclaredInAssociatedClass = false;
3044 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
3045 DeclContext *LexDC = DI->getLexicalDeclContext();
3046 if (isa<CXXRecordDecl>(LexDC) &&
3047 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) {
3048 DeclaredInAssociatedClass = true;
3049 break;
3050 }
3051 }
3052 if (!DeclaredInAssociatedClass)
John McCalld1e9d832009-08-11 06:59:38 +00003053 continue;
3054 }
Mike Stump11289f42009-09-09 15:08:12 +00003055
John McCall91f61fc2010-01-26 06:04:06 +00003056 if (isa<UsingShadowDecl>(D))
3057 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00003058
Richard Smith100b24a2014-04-17 01:52:14 +00003059 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D))
John McCall8fe68082010-01-26 07:16:45 +00003060 continue;
3061
Richard Smitha1431072015-06-12 01:32:13 +00003062 if (!isVisible(D) && !(D = findAcceptableDecl(*this, D)))
3063 continue;
3064
John McCall8fe68082010-01-26 07:16:45 +00003065 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00003066 }
3067 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003068}
Douglas Gregor2d435302009-12-30 17:04:44 +00003069
3070//----------------------------------------------------------------------------
3071// Search for all visible declarations.
3072//----------------------------------------------------------------------------
3073VisibleDeclConsumer::~VisibleDeclConsumer() { }
3074
Richard Smithe156254d2013-08-20 20:35:18 +00003075bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
3076
Douglas Gregor2d435302009-12-30 17:04:44 +00003077namespace {
3078
3079class ShadowContextRAII;
3080
3081class VisibleDeclsRecord {
3082public:
3083 /// \brief An entry in the shadow map, which is optimized to store a
3084 /// single declaration (the common case) but can also store a list
3085 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00003086 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00003087
3088private:
3089 /// \brief A mapping from declaration names to the declarations that have
3090 /// this name within a particular scope.
3091 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
3092
3093 /// \brief A list of shadow maps, which is used to model name hiding.
3094 std::list<ShadowMap> ShadowMaps;
3095
3096 /// \brief The declaration contexts we have already visited.
3097 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
3098
3099 friend class ShadowContextRAII;
3100
3101public:
3102 /// \brief Determine whether we have already visited this context
3103 /// (and, if not, note that we are going to visit that context now).
3104 bool visitedContext(DeclContext *Ctx) {
David Blaikie82e95a32014-11-19 07:49:47 +00003105 return !VisitedContexts.insert(Ctx).second;
Douglas Gregor2d435302009-12-30 17:04:44 +00003106 }
3107
Douglas Gregor39982192010-08-15 06:18:01 +00003108 bool alreadyVisitedContext(DeclContext *Ctx) {
3109 return VisitedContexts.count(Ctx);
3110 }
3111
Douglas Gregor2d435302009-12-30 17:04:44 +00003112 /// \brief Determine whether the given declaration is hidden in the
3113 /// current scope.
3114 ///
3115 /// \returns the declaration that hides the given declaration, or
3116 /// NULL if no such declaration exists.
3117 NamedDecl *checkHidden(NamedDecl *ND);
3118
3119 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00003120 void add(NamedDecl *ND) {
3121 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
3122 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003123};
3124
3125/// \brief RAII object that records when we've entered a shadow context.
3126class ShadowContextRAII {
3127 VisibleDeclsRecord &Visible;
3128
3129 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
3130
3131public:
3132 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
Benjamin Kramer3204b152015-05-29 19:42:19 +00003133 Visible.ShadowMaps.emplace_back();
Douglas Gregor2d435302009-12-30 17:04:44 +00003134 }
3135
3136 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00003137 Visible.ShadowMaps.pop_back();
3138 }
3139};
3140
3141} // end anonymous namespace
3142
Douglas Gregor2d435302009-12-30 17:04:44 +00003143NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00003144 // Look through using declarations.
3145 ND = ND->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003146
Douglas Gregor2d435302009-12-30 17:04:44 +00003147 unsigned IDNS = ND->getIdentifierNamespace();
3148 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
3149 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3150 SM != SMEnd; ++SM) {
3151 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
3152 if (Pos == SM->end())
3153 continue;
3154
Aaron Ballman1e606f42014-07-15 22:03:49 +00003155 for (auto *D : Pos->second) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003156 // A tag declaration does not hide a non-tag declaration.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003157 if (D->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003158 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00003159 Decl::IDNS_ObjCProtocol)))
3160 continue;
3161
3162 // Protocols are in distinct namespaces from everything else.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003163 if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor2d435302009-12-30 17:04:44 +00003164 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Aaron Ballman1e606f42014-07-15 22:03:49 +00003165 D->getIdentifierNamespace() != IDNS)
Douglas Gregor2d435302009-12-30 17:04:44 +00003166 continue;
3167
Douglas Gregor09bbc652010-01-14 15:47:35 +00003168 // Functions and function templates in the same scope overload
3169 // rather than hide. FIXME: Look for hiding based on function
3170 // signatures!
Aaron Ballman1e606f42014-07-15 22:03:49 +00003171 if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Alp Tokera2794f92014-01-22 07:29:52 +00003172 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00003173 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00003174 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003175
Douglas Gregor2d435302009-12-30 17:04:44 +00003176 // We've found a declaration that hides this one.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003177 return D;
Douglas Gregor2d435302009-12-30 17:04:44 +00003178 }
3179 }
3180
Craig Topperc3ec1492014-05-26 06:22:03 +00003181 return nullptr;
Douglas Gregor2d435302009-12-30 17:04:44 +00003182}
3183
3184static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
3185 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003186 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00003187 VisibleDeclConsumer &Consumer,
3188 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00003189 if (!Ctx)
3190 return;
3191
Douglas Gregor2d435302009-12-30 17:04:44 +00003192 // Make sure we don't visit the same context twice.
3193 if (Visited.visitedContext(Ctx->getPrimaryContext()))
3194 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003195
Richard Smith9e2341d2015-03-23 03:25:59 +00003196 // Outside C++, lookup results for the TU live on identifiers.
3197 if (isa<TranslationUnitDecl>(Ctx) &&
3198 !Result.getSema().getLangOpts().CPlusPlus) {
3199 auto &S = Result.getSema();
3200 auto &Idents = S.Context.Idents;
3201
3202 // Ensure all external identifiers are in the identifier table.
3203 if (IdentifierInfoLookup *External = Idents.getExternalIdentifierLookup()) {
3204 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
3205 for (StringRef Name = Iter->Next(); !Name.empty(); Name = Iter->Next())
3206 Idents.get(Name);
3207 }
3208
3209 // Walk all lookup results in the TU for each identifier.
3210 for (const auto &Ident : Idents) {
3211 for (auto I = S.IdResolver.begin(Ident.getValue()),
3212 E = S.IdResolver.end();
3213 I != E; ++I) {
3214 if (S.IdResolver.isDeclInScope(*I, Ctx)) {
3215 if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
3216 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3217 Visited.add(ND);
3218 }
3219 }
3220 }
3221 }
3222
3223 return;
3224 }
3225
Douglas Gregor7454c562010-07-02 20:37:36 +00003226 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3227 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3228
Douglas Gregor2d435302009-12-30 17:04:44 +00003229 // Enumerate all of the results in this context.
Richard Trieu20abd6b2015-04-15 03:48:48 +00003230 for (DeclContextLookupResult R : Ctx->lookups()) {
Richard Smith9e2341d2015-03-23 03:25:59 +00003231 for (auto *D : R) {
3232 if (auto *ND = Result.getAcceptableDecl(D)) {
3233 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3234 Visited.add(ND);
Douglas Gregora3b23b02010-12-09 21:44:02 +00003235 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003236 }
3237 }
3238
3239 // Traverse using directives for qualified name lookup.
3240 if (QualifiedNameLookup) {
3241 ShadowContextRAII Shadow(Visited);
Aaron Ballman804a7fb2014-03-17 17:14:12 +00003242 for (auto I : Ctx->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00003243 LookupVisibleDecls(I->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003244 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003245 }
3246 }
3247
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003248 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00003249 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00003250 if (!Record->hasDefinition())
3251 return;
3252
Aaron Ballman574705e2014-03-13 15:41:46 +00003253 for (const auto &B : Record->bases()) {
3254 QualType BaseType = B.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003255
Douglas Gregor2d435302009-12-30 17:04:44 +00003256 // Don't look into dependent bases, because name lookup can't look
3257 // there anyway.
3258 if (BaseType->isDependentType())
3259 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003260
Douglas Gregor2d435302009-12-30 17:04:44 +00003261 const RecordType *Record = BaseType->getAs<RecordType>();
3262 if (!Record)
3263 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003264
Douglas Gregor2d435302009-12-30 17:04:44 +00003265 // FIXME: It would be nice to be able to determine whether referencing
3266 // a particular member would be ambiguous. For example, given
3267 //
3268 // struct A { int member; };
3269 // struct B { int member; };
3270 // struct C : A, B { };
3271 //
3272 // void f(C *c) { c->### }
3273 //
3274 // accessing 'member' would result in an ambiguity. However, we
3275 // could be smart enough to qualify the member with the base
3276 // class, e.g.,
3277 //
3278 // c->B::member
3279 //
3280 // or
3281 //
3282 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003283
Douglas Gregor2d435302009-12-30 17:04:44 +00003284 // Find results in this base class (and its bases).
3285 ShadowContextRAII Shadow(Visited);
3286 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003287 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003288 }
3289 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003290
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003291 // Traverse the contexts of Objective-C classes.
3292 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3293 // Traverse categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003294 for (auto *Cat : IFace->visible_categories()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003295 ShadowContextRAII Shadow(Visited);
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003296 LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003297 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003298 }
3299
3300 // Traverse protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003301 for (auto *I : IFace->all_referenced_protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003302 ShadowContextRAII Shadow(Visited);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003303 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003304 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003305 }
3306
3307 // Traverse the superclass.
3308 if (IFace->getSuperClass()) {
3309 ShadowContextRAII Shadow(Visited);
3310 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003311 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003312 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003313
Douglas Gregor0b59e802010-04-19 18:02:19 +00003314 // If there is an implementation, traverse it. We do this to find
3315 // synthesized ivars.
3316 if (IFace->getImplementation()) {
3317 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003318 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky13668f22012-04-03 20:26:45 +00003319 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor0b59e802010-04-19 18:02:19 +00003320 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003321 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003322 for (auto *I : Protocol->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003323 ShadowContextRAII Shadow(Visited);
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003324 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003325 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003326 }
3327 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003328 for (auto *I : Category->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003329 ShadowContextRAII Shadow(Visited);
Aaron Ballman19a41762014-03-14 12:55:57 +00003330 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003331 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003332 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003333
Douglas Gregor0b59e802010-04-19 18:02:19 +00003334 // If there is an implementation, traverse it.
3335 if (Category->getImplementation()) {
3336 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003337 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00003338 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003339 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003340 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003341}
3342
3343static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3344 UnqualUsingDirectiveSet &UDirs,
3345 VisibleDeclConsumer &Consumer,
3346 VisibleDeclsRecord &Visited) {
3347 if (!S)
3348 return;
3349
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003350 if (!S->getEntity() ||
3351 (!S->getParent() &&
Ted Kremenekc37877d2013-10-08 17:08:03 +00003352 !Visited.alreadyVisitedContext(S->getEntity())) ||
3353 (S->getEntity())->isFunctionOrMethod()) {
Richard Smith541b38b2013-09-20 01:15:31 +00003354 FindLocalExternScope FindLocals(Result);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003355 // Walk through the declarations in this Scope.
Aaron Ballman35c54952014-03-17 16:55:25 +00003356 for (auto *D : S->decls()) {
3357 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Douglas Gregor4a814562011-12-14 16:03:29 +00003358 if ((ND = Result.getAcceptableDecl(ND))) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003359 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003360 Visited.add(ND);
3361 }
3362 }
3363 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003364
Douglas Gregor66230062010-03-15 14:33:29 +00003365 // FIXME: C++ [temp.local]p8
Craig Topperc3ec1492014-05-26 06:22:03 +00003366 DeclContext *Entity = nullptr;
Douglas Gregor4f248632010-01-01 17:44:25 +00003367 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003368 // Look into this scope's declaration context, along with any of its
3369 // parent lookup contexts (e.g., enclosing classes), up to the point
3370 // where we hit the context stored in the next outer scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00003371 Entity = S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00003372 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003373
Douglas Gregorea166062010-03-15 15:26:48 +00003374 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00003375 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003376 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3377 if (Method->isInstanceMethod()) {
3378 // For instance methods, look for ivars in the method's interface.
3379 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3380 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003381 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003382 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Richard Smithe156254d2013-08-20 20:35:18 +00003383 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003384 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003385 }
3386
3387 // We've already performed all of the name lookup that we need
3388 // to for Objective-C methods; the next context will be the
3389 // outer scope.
3390 break;
3391 }
3392
Douglas Gregor2d435302009-12-30 17:04:44 +00003393 if (Ctx->isFunctionOrMethod())
3394 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003395
3396 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003397 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003398 }
3399 } else if (!S->getParent()) {
3400 // Look into the translation unit scope. We walk through the translation
3401 // unit's declaration context, because the Scope itself won't have all of
3402 // the declarations if we loaded a precompiled header.
3403 // FIXME: We would like the translation unit's Scope object to point to the
3404 // translation unit, so we don't need this special "if" branch. However,
3405 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003406 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00003407 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003408 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00003409 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003410 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003411 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003412 }
3413
Douglas Gregor2d435302009-12-30 17:04:44 +00003414 if (Entity) {
3415 // Lookup visible declarations in any namespaces found by using
3416 // directives.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003417 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
3418 LookupVisibleDecls(const_cast<DeclContext *>(UUE.getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003419 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003420 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003421 }
3422
3423 // Lookup names in the parent scope.
3424 ShadowContextRAII Shadow(Visited);
3425 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3426}
3427
3428void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003429 VisibleDeclConsumer &Consumer,
3430 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003431 // Determine the set of using directives available during
3432 // unqualified name lookup.
3433 Scope *Initial = S;
3434 UnqualUsingDirectiveSet UDirs;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003435 if (getLangOpts().CPlusPlus) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003436 // Find the first namespace or translation-unit scope.
3437 while (S && !isNamespaceOrTranslationUnitScope(S))
3438 S = S->getParent();
3439
3440 UDirs.visitScopeChain(Initial, S);
3441 }
3442 UDirs.done();
3443
3444 // Look for visible declarations.
3445 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003446 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003447 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003448 if (!IncludeGlobalScope)
3449 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003450 ShadowContextRAII Shadow(Visited);
3451 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3452}
3453
3454void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003455 VisibleDeclConsumer &Consumer,
3456 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003457 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003458 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003459 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003460 if (!IncludeGlobalScope)
3461 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003462 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003463 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003464 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003465}
3466
Chris Lattner43e7f312011-02-18 02:08:43 +00003467/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003468/// If GnuLabelLoc is a valid source location, then this is a definition
3469/// of an __label__ label name, otherwise it is a normal label definition
3470/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003471LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003472 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003473 // Do a lookup to see if we have a label with this name already.
Craig Topperc3ec1492014-05-26 06:22:03 +00003474 NamedDecl *Res = nullptr;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003475
3476 if (GnuLabelLoc.isValid()) {
3477 // Local label definitions always shadow existing labels.
3478 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3479 Scope *S = CurScope;
3480 PushOnScopeChains(Res, S, true);
3481 return cast<LabelDecl>(Res);
3482 }
3483
3484 // Not a GNU local label.
3485 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3486 // If we found a label, check to see if it is in the same context as us.
3487 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003488 if (Res && Res->getDeclContext() != CurContext)
Craig Topperc3ec1492014-05-26 06:22:03 +00003489 Res = nullptr;
3490 if (!Res) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003491 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003492 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3493 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003494 assert(S && "Not in a function?");
3495 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003496 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003497 return cast<LabelDecl>(Res);
3498}
3499
3500//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003501// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003502//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003503
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003504static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3505 TypoCorrection &Candidate) {
3506 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3507 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3508}
3509
3510static void LookupPotentialTypoResult(Sema &SemaRef,
3511 LookupResult &Res,
3512 IdentifierInfo *Name,
3513 Scope *S, CXXScopeSpec *SS,
3514 DeclContext *MemberContext,
3515 bool EnteringContext,
3516 bool isObjCIvarLookup,
3517 bool FindHidden);
3518
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003519/// \brief Check whether the declarations found for a typo correction are
3520/// visible, and if none of them are, convert the correction to an 'import
3521/// a module' correction.
3522static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
3523 if (TC.begin() == TC.end())
3524 return;
3525
3526 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3527
3528 for (/**/; DI != DE; ++DI)
3529 if (!LookupResult::isVisible(SemaRef, *DI))
3530 break;
3531 // Nothing to do if all decls are visible.
3532 if (DI == DE)
3533 return;
3534
3535 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3536 bool AnyVisibleDecls = !NewDecls.empty();
3537
3538 for (/**/; DI != DE; ++DI) {
3539 NamedDecl *VisibleDecl = *DI;
3540 if (!LookupResult::isVisible(SemaRef, *DI))
3541 VisibleDecl = findAcceptableDecl(SemaRef, *DI);
3542
3543 if (VisibleDecl) {
3544 if (!AnyVisibleDecls) {
3545 // Found a visible decl, discard all hidden ones.
3546 AnyVisibleDecls = true;
3547 NewDecls.clear();
3548 }
3549 NewDecls.push_back(VisibleDecl);
3550 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
3551 NewDecls.push_back(*DI);
3552 }
3553
3554 if (NewDecls.empty())
3555 TC = TypoCorrection();
3556 else {
3557 TC.setCorrectionDecls(NewDecls);
3558 TC.setRequiresImport(!AnyVisibleDecls);
3559 }
3560}
3561
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003562// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3563// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3564// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3565static void getNestedNameSpecifierIdentifiers(
3566 NestedNameSpecifier *NNS,
3567 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3568 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3569 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3570 else
3571 Identifiers.clear();
3572
3573 const IdentifierInfo *II = nullptr;
3574
3575 switch (NNS->getKind()) {
3576 case NestedNameSpecifier::Identifier:
3577 II = NNS->getAsIdentifier();
3578 break;
3579
3580 case NestedNameSpecifier::Namespace:
3581 if (NNS->getAsNamespace()->isAnonymousNamespace())
3582 return;
3583 II = NNS->getAsNamespace()->getIdentifier();
3584 break;
3585
3586 case NestedNameSpecifier::NamespaceAlias:
3587 II = NNS->getAsNamespaceAlias()->getIdentifier();
3588 break;
3589
3590 case NestedNameSpecifier::TypeSpecWithTemplate:
3591 case NestedNameSpecifier::TypeSpec:
3592 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3593 break;
3594
3595 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00003596 case NestedNameSpecifier::Super:
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003597 return;
3598 }
3599
3600 if (II)
3601 Identifiers.push_back(II);
3602}
3603
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003604void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003605 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003606 // Don't consider hidden names for typo correction.
3607 if (Hiding)
3608 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003609
Douglas Gregor2d435302009-12-30 17:04:44 +00003610 // Only consider entities with identifiers for names, ignoring
3611 // special names (constructors, overloaded operators, selectors,
3612 // etc.).
3613 IdentifierInfo *Name = ND->getIdentifier();
3614 if (!Name)
3615 return;
3616
Richard Smithe156254d2013-08-20 20:35:18 +00003617 // Only consider visible declarations and declarations from modules with
3618 // names that exactly match.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003619 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo &&
Richard Smithe156254d2013-08-20 20:35:18 +00003620 !findAcceptableDecl(SemaRef, ND))
3621 return;
3622
Douglas Gregor57756ea2010-10-14 22:11:03 +00003623 FoundName(Name->getName());
3624}
3625
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003626void TypoCorrectionConsumer::FoundName(StringRef Name) {
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003627 // Compute the edit distance between the typo and the name of this
3628 // entity, and add the identifier to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003629 addName(Name, nullptr);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003630}
3631
3632void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3633 // Compute the edit distance between the typo and this keyword,
3634 // and add the keyword to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003635 addName(Keyword, nullptr, nullptr, true);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003636}
3637
3638void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
3639 NestedNameSpecifier *NNS, bool isKeyword) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003640 // Use a simple length-based heuristic to determine the minimum possible
3641 // edit distance. If the minimum isn't good enough, bail out early.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003642 StringRef TypoStr = Typo->getName();
3643 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
3644 if (MinED && TypoStr.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00003645 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003646
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003647 // Compute an upper bound on the allowable edit distance, so that the
3648 // edit-distance algorithm can short-circuit.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003649 unsigned UpperBound = (TypoStr.size() + 2) / 3 + 1;
3650 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003651 if (ED >= UpperBound) return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003652
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003653 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003654 if (isKeyword) TC.makeKeyword();
Kaelyn Takata0a313022014-11-20 22:06:26 +00003655 TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003656 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003657}
3658
Kaelyn Takatad2287c32014-10-27 18:07:13 +00003659static const unsigned MaxTypoDistanceResultSets = 5;
3660
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003661void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003662 StringRef TypoStr = Typo->getName();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003663 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003664
3665 // For very short typos, ignore potential corrections that have a different
3666 // base identifier from the typo or which have a normalized edit distance
3667 // longer than the typo itself.
3668 if (TypoStr.size() < 3 &&
3669 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
3670 return;
3671
3672 // If the correction is resolved but is not viable, ignore it.
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003673 if (Correction.isResolved()) {
3674 checkCorrectionVisibility(SemaRef, Correction);
3675 if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
3676 return;
3677 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003678
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003679 TypoResultList &CList =
3680 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003681
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003682 if (!CList.empty() && !CList.back().isResolved())
3683 CList.pop_back();
3684 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3685 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3686 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3687 RI != RIEnd; ++RI) {
3688 // If the Correction refers to a decl already in the result list,
3689 // replace the existing result if the string representation of Correction
3690 // comes before the current result alphabetically, then stop as there is
3691 // nothing more to be done to add Correction to the candidate set.
3692 if (RI->getCorrectionDecl() == NewND) {
3693 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3694 *RI = Correction;
3695 return;
3696 }
3697 }
3698 }
3699 if (CList.empty() || Correction.isResolved())
3700 CList.push_back(Correction);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003701
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003702 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003703 CorrectionResults.erase(std::prev(CorrectionResults.end()));
3704}
3705
3706void TypoCorrectionConsumer::addNamespaces(
3707 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
3708 SearchNamespaces = true;
3709
3710 for (auto KNPair : KnownNamespaces)
3711 Namespaces.addNameSpecifier(KNPair.first);
3712
3713 bool SSIsTemplate = false;
3714 if (NestedNameSpecifier *NNS =
3715 (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
3716 if (const Type *T = NNS->getAsType())
3717 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
3718 }
3719 for (const auto *TI : SemaRef.getASTContext().types()) {
3720 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
3721 CD = CD->getCanonicalDecl();
3722 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
3723 !CD->isUnion() && CD->getIdentifier() &&
3724 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
3725 (CD->isBeingDefined() || CD->isCompleteDefinition()))
3726 Namespaces.addNameSpecifier(CD);
3727 }
3728 }
3729}
3730
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003731const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
3732 if (++CurrentTCIndex < ValidatedCorrections.size())
3733 return ValidatedCorrections[CurrentTCIndex];
3734
3735 CurrentTCIndex = ValidatedCorrections.size();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003736 while (!CorrectionResults.empty()) {
3737 auto DI = CorrectionResults.begin();
3738 if (DI->second.empty()) {
3739 CorrectionResults.erase(DI);
3740 continue;
3741 }
3742
3743 auto RI = DI->second.begin();
3744 if (RI->second.empty()) {
3745 DI->second.erase(RI);
3746 performQualifiedLookups();
3747 continue;
3748 }
3749
3750 TypoCorrection TC = RI->second.pop_back_val();
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003751 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003752 ValidatedCorrections.push_back(TC);
3753 return ValidatedCorrections[CurrentTCIndex];
3754 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003755 }
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003756 return ValidatedCorrections[0]; // The empty correction.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003757}
3758
3759bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
3760 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
3761 DeclContext *TempMemberContext = MemberContext;
Kaelyn Takata6c759512014-10-27 18:07:37 +00003762 CXXScopeSpec *TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003763retry_lookup:
3764 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
3765 EnteringContext,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00003766 CorrectionValidator->IsObjCIvarLookup,
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003767 Name == Typo && !Candidate.WillReplaceSpecifier());
3768 switch (Result.getResultKind()) {
3769 case LookupResult::NotFound:
3770 case LookupResult::NotFoundInCurrentInstantiation:
3771 case LookupResult::FoundUnresolvedValue:
3772 if (TempSS) {
3773 // Immediately retry the lookup without the given CXXScopeSpec
3774 TempSS = nullptr;
3775 Candidate.WillReplaceSpecifier(true);
3776 goto retry_lookup;
3777 }
3778 if (TempMemberContext) {
3779 if (SS && !TempSS)
Kaelyn Takata6c759512014-10-27 18:07:37 +00003780 TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003781 TempMemberContext = nullptr;
3782 goto retry_lookup;
3783 }
3784 if (SearchNamespaces)
3785 QualifiedResults.push_back(Candidate);
3786 break;
3787
3788 case LookupResult::Ambiguous:
3789 // We don't deal with ambiguities.
3790 break;
3791
3792 case LookupResult::Found:
3793 case LookupResult::FoundOverloaded:
3794 // Store all of the Decls for overloaded symbols
3795 for (auto *TRD : Result)
3796 Candidate.addCorrectionDecl(TRD);
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003797 checkCorrectionVisibility(SemaRef, Candidate);
Kaelyn Takata89c881b2014-10-27 18:07:29 +00003798 if (!isCandidateViable(*CorrectionValidator, Candidate)) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003799 if (SearchNamespaces)
3800 QualifiedResults.push_back(Candidate);
3801 break;
3802 }
Kaelyn Takata20deb1d2015-01-28 00:46:09 +00003803 Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003804 return true;
3805 }
3806 return false;
3807}
3808
3809void TypoCorrectionConsumer::performQualifiedLookups() {
3810 unsigned TypoLen = Typo->getName().size();
3811 for (auto QR : QualifiedResults) {
3812 for (auto NSI : Namespaces) {
3813 DeclContext *Ctx = NSI.DeclCtx;
3814 const Type *NSType = NSI.NameSpecifier->getAsType();
3815
3816 // If the current NestedNameSpecifier refers to a class and the
3817 // current correction candidate is the name of that class, then skip
3818 // it as it is unlikely a qualified version of the class' constructor
3819 // is an appropriate correction.
3820 if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() : 0) {
3821 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
3822 continue;
3823 }
3824
3825 TypoCorrection TC(QR);
3826 TC.ClearCorrectionDecls();
3827 TC.setCorrectionSpecifier(NSI.NameSpecifier);
3828 TC.setQualifierDistance(NSI.EditDistance);
3829 TC.setCallbackDistance(0); // Reset the callback distance
3830
3831 // If the current correction candidate and namespace combination are
3832 // too far away from the original typo based on the normalized edit
3833 // distance, then skip performing a qualified name lookup.
3834 unsigned TmpED = TC.getEditDistance(true);
3835 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
3836 TypoLen / TmpED < 3)
3837 continue;
3838
3839 Result.clear();
3840 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
3841 if (!SemaRef.LookupQualifiedName(Result, Ctx))
3842 continue;
3843
3844 // Any corrections added below will be validated in subsequent
3845 // iterations of the main while() loop over the Consumer's contents.
3846 switch (Result.getResultKind()) {
3847 case LookupResult::Found:
3848 case LookupResult::FoundOverloaded: {
3849 if (SS && SS->isValid()) {
3850 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
3851 std::string OldQualified;
3852 llvm::raw_string_ostream OldOStream(OldQualified);
3853 SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
3854 OldOStream << Typo->getName();
3855 // If correction candidate would be an identical written qualified
3856 // identifer, then the existing CXXScopeSpec probably included a
3857 // typedef that didn't get accounted for properly.
3858 if (OldOStream.str() == NewQualified)
3859 break;
3860 }
3861 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
3862 TRD != TRDEnd; ++TRD) {
3863 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
3864 NSType ? NSType->getAsCXXRecordDecl()
3865 : nullptr,
3866 TRD.getPair()) == Sema::AR_accessible)
3867 TC.addCorrectionDecl(*TRD);
3868 }
Kaelyn Takata0a313022014-11-20 22:06:26 +00003869 if (TC.isResolved()) {
3870 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003871 addCorrection(TC);
Kaelyn Takata0a313022014-11-20 22:06:26 +00003872 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003873 break;
3874 }
3875 case LookupResult::NotFound:
3876 case LookupResult::NotFoundInCurrentInstantiation:
3877 case LookupResult::Ambiguous:
3878 case LookupResult::FoundUnresolvedValue:
3879 break;
3880 }
3881 }
3882 }
3883 QualifiedResults.clear();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003884}
3885
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00003886TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
3887 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
Benjamin Kramer15537272015-03-13 16:10:42 +00003888 : Context(Context), CurContextChain(buildContextChain(CurContext)) {
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00003889 if (NestedNameSpecifier *NNS =
3890 CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
3891 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
3892 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3893
3894 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
3895 }
3896 // Build the list of identifiers that would be used for an absolute
3897 // (from the global context) NestedNameSpecifier referring to the current
3898 // context.
3899 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3900 CEnd = CurContextChain.rend();
3901 C != CEnd; ++C) {
3902 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3903 CurContextIdentifiers.push_back(ND->getIdentifier());
3904 }
3905
3906 // Add the global context as a NestedNameSpecifier
Hans Wennborg66010132014-06-11 21:24:13 +00003907 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
3908 NestedNameSpecifier::GlobalSpecifier(Context), 1};
3909 DistanceMap[1].push_back(SI);
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00003910}
3911
Kaelyn Takata7dcc0e62014-06-11 18:07:08 +00003912auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
3913 DeclContext *Start) -> DeclContextList {
Nick Lewycky0d9b3192013-04-08 21:55:21 +00003914 assert(Start && "Building a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003915 DeclContextList Chain;
Craig Topperc3ec1492014-05-26 06:22:03 +00003916 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003917 DC = DC->getLookupParent()) {
3918 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3919 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3920 !(ND && ND->isAnonymousNamespace()))
3921 Chain.push_back(DC->getPrimaryContext());
3922 }
3923 return Chain;
3924}
3925
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003926unsigned
3927TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
3928 DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003929 unsigned NumSpecifiers = 0;
3930 for (DeclContextList::reverse_iterator C = DeclChain.rbegin(),
3931 CEnd = DeclChain.rend();
3932 C != CEnd; ++C) {
3933 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) {
3934 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3935 ++NumSpecifiers;
3936 } else if (RecordDecl *RD = dyn_cast_or_null<RecordDecl>(*C)) {
3937 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
3938 RD->getTypeForDecl());
3939 ++NumSpecifiers;
3940 }
3941 }
3942 return NumSpecifiers;
3943}
3944
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003945void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
3946 DeclContext *Ctx) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003947 NestedNameSpecifier *NNS = nullptr;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003948 unsigned NumSpecifiers = 0;
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003949 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003950 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
3951
3952 // Eliminate common elements from the two DeclContext chains.
3953 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3954 CEnd = CurContextChain.rend();
3955 C != CEnd && !NamespaceDeclChain.empty() &&
3956 NamespaceDeclChain.back() == *C; ++C) {
3957 NamespaceDeclChain.pop_back();
3958 }
3959
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003960 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003961 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003962
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003963 // Add an explicit leading '::' specifier if needed.
3964 if (NamespaceDeclChain.empty()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003965 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003966 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003967 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003968 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003969 } else if (NamedDecl *ND =
3970 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003971 IdentifierInfo *Name = ND->getIdentifier();
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003972 bool SameNameSpecifier = false;
3973 if (std::find(CurNameSpecifierIdentifiers.begin(),
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003974 CurNameSpecifierIdentifiers.end(),
3975 Name) != CurNameSpecifierIdentifiers.end()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003976 std::string NewNameSpecifier;
3977 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
3978 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
3979 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3980 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3981 SpecifierOStream.flush();
3982 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003983 }
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003984 if (SameNameSpecifier ||
3985 std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3986 Name) != CurContextIdentifiers.end()) {
3987 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
3988 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3989 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003990 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003991 }
3992 }
3993
3994 // If the built NestedNameSpecifier would be replacing an existing
3995 // NestedNameSpecifier, use the number of component identifiers that
3996 // would need to be changed as the edit distance instead of the number
3997 // of components in the built NestedNameSpecifier.
3998 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3999 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
4000 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4001 NumSpecifiers = llvm::ComputeEditDistance(
Craig Topper8c2a2a02014-08-30 16:55:39 +00004002 llvm::makeArrayRef(CurNameSpecifierIdentifiers),
4003 llvm::makeArrayRef(NewNameSpecifierIdentifiers));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004004 }
4005
Hans Wennborg66010132014-06-11 21:24:13 +00004006 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
4007 DistanceMap[NumSpecifiers].push_back(SI);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004008}
4009
Douglas Gregord507d772010-10-20 03:06:34 +00004010/// \brief Perform name lookup for a possible result for typo correction.
4011static void LookupPotentialTypoResult(Sema &SemaRef,
4012 LookupResult &Res,
4013 IdentifierInfo *Name,
4014 Scope *S, CXXScopeSpec *SS,
4015 DeclContext *MemberContext,
4016 bool EnteringContext,
Richard Smithe156254d2013-08-20 20:35:18 +00004017 bool isObjCIvarLookup,
4018 bool FindHidden) {
Douglas Gregord507d772010-10-20 03:06:34 +00004019 Res.suppressDiagnostics();
4020 Res.clear();
4021 Res.setLookupName(Name);
Richard Smithe156254d2013-08-20 20:35:18 +00004022 Res.setAllowHidden(FindHidden);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004023 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00004024 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004025 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00004026 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
4027 Res.addDecl(Ivar);
4028 Res.resolveKind();
4029 return;
4030 }
4031 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004032
Douglas Gregord507d772010-10-20 03:06:34 +00004033 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
4034 Res.addDecl(Prop);
4035 Res.resolveKind();
4036 return;
4037 }
4038 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004039
Douglas Gregord507d772010-10-20 03:06:34 +00004040 SemaRef.LookupQualifiedName(Res, MemberContext);
4041 return;
4042 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004043
4044 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00004045 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004046
Douglas Gregord507d772010-10-20 03:06:34 +00004047 // Fake ivar lookup; this should really be part of
4048 // LookupParsedName.
4049 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
4050 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004051 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00004052 (Res.isSingleResult() &&
4053 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004054 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00004055 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
4056 Res.addDecl(IV);
4057 Res.resolveKind();
4058 }
4059 }
4060 }
4061}
4062
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004063/// \brief Add keywords to the consumer as possible typo corrections.
4064static void AddKeywordsToConsumer(Sema &SemaRef,
4065 TypoCorrectionConsumer &Consumer,
Richard Smithb3a1df02012-06-08 21:35:42 +00004066 Scope *S, CorrectionCandidateCallback &CCC,
4067 bool AfterNestedNameSpecifier) {
4068 if (AfterNestedNameSpecifier) {
4069 // For 'X::', we know exactly which keywords can appear next.
4070 Consumer.addKeywordResult("template");
4071 if (CCC.WantExpressionKeywords)
4072 Consumer.addKeywordResult("operator");
4073 return;
4074 }
4075
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004076 if (CCC.WantObjCSuper)
4077 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004078
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004079 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004080 // Add type-specifier keywords to the set of results.
Craig Topperd6d31ac2013-07-15 08:24:27 +00004081 static const char *const CTypeSpecs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004082 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00004083 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004084 "_Complex", "_Imaginary",
4085 // storage-specifiers as well
4086 "extern", "inline", "static", "typedef"
4087 };
4088
Craig Toppere5ce8312013-07-15 03:38:40 +00004089 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004090 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
4091 Consumer.addKeywordResult(CTypeSpecs[I]);
4092
David Blaikiebbafb8a2012-03-11 07:00:24 +00004093 if (SemaRef.getLangOpts().C99)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004094 Consumer.addKeywordResult("restrict");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004095 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004096 Consumer.addKeywordResult("bool");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004097 else if (SemaRef.getLangOpts().C99)
Douglas Gregor3b22a882011-07-01 21:27:45 +00004098 Consumer.addKeywordResult("_Bool");
4099
David Blaikiebbafb8a2012-03-11 07:00:24 +00004100 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004101 Consumer.addKeywordResult("class");
4102 Consumer.addKeywordResult("typename");
4103 Consumer.addKeywordResult("wchar_t");
4104
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004105 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004106 Consumer.addKeywordResult("char16_t");
4107 Consumer.addKeywordResult("char32_t");
4108 Consumer.addKeywordResult("constexpr");
4109 Consumer.addKeywordResult("decltype");
4110 Consumer.addKeywordResult("thread_local");
4111 }
4112 }
4113
David Blaikiebbafb8a2012-03-11 07:00:24 +00004114 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004115 Consumer.addKeywordResult("typeof");
Kaelyn Takatab04846b2014-07-28 18:14:02 +00004116 } else if (CCC.WantFunctionLikeCasts) {
4117 static const char *const CastableTypeSpecs[] = {
4118 "char", "double", "float", "int", "long", "short",
4119 "signed", "unsigned", "void"
4120 };
4121 for (auto *kw : CastableTypeSpecs)
4122 Consumer.addKeywordResult(kw);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004123 }
4124
David Blaikiebbafb8a2012-03-11 07:00:24 +00004125 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004126 Consumer.addKeywordResult("const_cast");
4127 Consumer.addKeywordResult("dynamic_cast");
4128 Consumer.addKeywordResult("reinterpret_cast");
4129 Consumer.addKeywordResult("static_cast");
4130 }
4131
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004132 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004133 Consumer.addKeywordResult("sizeof");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004134 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004135 Consumer.addKeywordResult("false");
4136 Consumer.addKeywordResult("true");
4137 }
4138
David Blaikiebbafb8a2012-03-11 07:00:24 +00004139 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topperd6d31ac2013-07-15 08:24:27 +00004140 static const char *const CXXExprs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004141 "delete", "new", "operator", "throw", "typeid"
4142 };
Craig Toppere5ce8312013-07-15 03:38:40 +00004143 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004144 for (unsigned I = 0; I != NumCXXExprs; ++I)
4145 Consumer.addKeywordResult(CXXExprs[I]);
4146
4147 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
4148 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
4149 Consumer.addKeywordResult("this");
4150
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004151 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004152 Consumer.addKeywordResult("alignof");
4153 Consumer.addKeywordResult("nullptr");
4154 }
4155 }
Jordan Rose58d54722012-06-30 21:33:57 +00004156
4157 if (SemaRef.getLangOpts().C11) {
4158 // FIXME: We should not suggest _Alignof if the alignof macro
4159 // is present.
4160 Consumer.addKeywordResult("_Alignof");
4161 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004162 }
4163
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004164 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004165 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
4166 // Statements.
Craig Topperd6d31ac2013-07-15 08:24:27 +00004167 static const char *const CStmts[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004168 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Toppere5ce8312013-07-15 03:38:40 +00004169 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004170 for (unsigned I = 0; I != NumCStmts; ++I)
4171 Consumer.addKeywordResult(CStmts[I]);
4172
David Blaikiebbafb8a2012-03-11 07:00:24 +00004173 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004174 Consumer.addKeywordResult("catch");
4175 Consumer.addKeywordResult("try");
4176 }
4177
4178 if (S && S->getBreakParent())
4179 Consumer.addKeywordResult("break");
4180
4181 if (S && S->getContinueParent())
4182 Consumer.addKeywordResult("continue");
4183
4184 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
4185 Consumer.addKeywordResult("case");
4186 Consumer.addKeywordResult("default");
4187 }
4188 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004189 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004190 Consumer.addKeywordResult("namespace");
4191 Consumer.addKeywordResult("template");
4192 }
4193
4194 if (S && S->isClassScope()) {
4195 Consumer.addKeywordResult("explicit");
4196 Consumer.addKeywordResult("friend");
4197 Consumer.addKeywordResult("mutable");
4198 Consumer.addKeywordResult("private");
4199 Consumer.addKeywordResult("protected");
4200 Consumer.addKeywordResult("public");
4201 Consumer.addKeywordResult("virtual");
4202 }
4203 }
4204
David Blaikiebbafb8a2012-03-11 07:00:24 +00004205 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004206 Consumer.addKeywordResult("using");
4207
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004208 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004209 Consumer.addKeywordResult("static_assert");
4210 }
4211 }
4212}
4213
Kaelyn Takata6c759512014-10-27 18:07:37 +00004214std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
4215 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4216 Scope *S, CXXScopeSpec *SS,
4217 std::unique_ptr<CorrectionCandidateCallback> CCC,
4218 DeclContext *MemberContext, bool EnteringContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004219 const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00004220
4221 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4222 DisableTypoCorrection)
4223 return nullptr;
4224
4225 // In Microsoft mode, don't perform typo correction in a template member
4226 // function dependent context because it interferes with the "lookup into
4227 // dependent bases of class templates" feature.
4228 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
4229 isa<CXXMethodDecl>(CurContext))
4230 return nullptr;
4231
4232 // We only attempt to correct typos for identifiers.
4233 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4234 if (!Typo)
4235 return nullptr;
4236
4237 // If the scope specifier itself was invalid, don't try to correct
4238 // typos.
4239 if (SS && SS->isInvalid())
4240 return nullptr;
4241
4242 // Never try to correct typos during template deduction or
4243 // instantiation.
4244 if (!ActiveTemplateInstantiations.empty())
4245 return nullptr;
4246
4247 // Don't try to correct 'super'.
4248 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4249 return nullptr;
4250
4251 // Abort if typo correction already failed for this specific typo.
4252 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4253 if (locs != TypoCorrectionFailures.end() &&
4254 locs->second.count(TypoName.getLoc()))
4255 return nullptr;
4256
4257 // Don't try to correct the identifier "vector" when in AltiVec mode.
4258 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4259 // remove this workaround.
4260 if (getLangOpts().AltiVec && Typo->isStr("vector"))
4261 return nullptr;
4262
Nick Lewycky24653262014-12-16 21:39:02 +00004263 // Provide a stop gap for files that are just seriously broken. Trying
4264 // to correct all typos can turn into a HUGE performance penalty, causing
4265 // some files to take minutes to get rejected by the parser.
4266 unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
4267 if (Limit && TyposCorrected >= Limit)
4268 return nullptr;
4269 ++TyposCorrected;
4270
Kaelyn Takata6c759512014-10-27 18:07:37 +00004271 // If we're handling a missing symbol error, using modules, and the
4272 // special search all modules option is used, look for a missing import.
4273 if (ErrorRecovery && getLangOpts().Modules &&
4274 getLangOpts().ModulesSearchAll) {
4275 // The following has the side effect of loading the missing module.
4276 getModuleLoader().lookupMissingImports(Typo->getName(),
4277 TypoName.getLocStart());
4278 }
4279
4280 CorrectionCandidateCallback &CCCRef = *CCC;
4281 auto Consumer = llvm::make_unique<TypoCorrectionConsumer>(
4282 *this, TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
4283 EnteringContext);
4284
Kaelyn Takata6c759512014-10-27 18:07:37 +00004285 // Perform name lookup to find visible, similarly-named entities.
Nick Lewycky24653262014-12-16 21:39:02 +00004286 bool IsUnqualifiedLookup = false;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004287 DeclContext *QualifiedDC = MemberContext;
4288 if (MemberContext) {
4289 LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
4290
4291 // Look in qualified interfaces.
4292 if (OPT) {
4293 for (auto *I : OPT->quals())
4294 LookupVisibleDecls(I, LookupKind, *Consumer);
4295 }
4296 } else if (SS && SS->isSet()) {
4297 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4298 if (!QualifiedDC)
4299 return nullptr;
4300
Kaelyn Takata6c759512014-10-27 18:07:37 +00004301 LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
4302 } else {
4303 IsUnqualifiedLookup = true;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004304 }
4305
4306 // Determine whether we are going to search in the various namespaces for
4307 // corrections.
4308 bool SearchNamespaces
4309 = getLangOpts().CPlusPlus &&
4310 (IsUnqualifiedLookup || (SS && SS->isSet()));
4311
4312 if (IsUnqualifiedLookup || SearchNamespaces) {
4313 // For unqualified lookup, look through all of the names that we have
4314 // seen in this translation unit.
4315 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4316 for (const auto &I : Context.Idents)
4317 Consumer->FoundName(I.getKey());
4318
4319 // Walk through identifiers in external identifier sources.
4320 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4321 if (IdentifierInfoLookup *External
4322 = Context.Idents.getExternalIdentifierLookup()) {
4323 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4324 do {
4325 StringRef Name = Iter->Next();
4326 if (Name.empty())
4327 break;
4328
4329 Consumer->FoundName(Name);
4330 } while (true);
4331 }
4332 }
4333
4334 AddKeywordsToConsumer(*this, *Consumer, S, CCCRef, SS && SS->isNotEmpty());
4335
4336 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4337 // to search those namespaces.
4338 if (SearchNamespaces) {
4339 // Load any externally-known namespaces.
4340 if (ExternalSource && !LoadedExternalKnownNamespaces) {
4341 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
4342 LoadedExternalKnownNamespaces = true;
4343 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4344 for (auto *N : ExternalKnownNamespaces)
4345 KnownNamespaces[N] = true;
4346 }
4347
4348 Consumer->addNamespaces(KnownNamespaces);
4349 }
4350
4351 return Consumer;
4352}
4353
Douglas Gregor2d435302009-12-30 17:04:44 +00004354/// \brief Try to "correct" a typo in the source code by finding
4355/// visible declarations whose names are similar to the name that was
4356/// present in the source code.
4357///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004358/// \param TypoName the \c DeclarationNameInfo structure that contains
4359/// the name that was present in the source code along with its location.
4360///
4361/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00004362///
4363/// \param S the scope in which name lookup occurs.
4364///
4365/// \param SS the nested-name-specifier that precedes the name we're
4366/// looking for, if present.
4367///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004368/// \param CCC A CorrectionCandidateCallback object that provides further
4369/// validation of typo correction candidates. It also provides flags for
4370/// determining the set of keywords permitted.
4371///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00004372/// \param MemberContext if non-NULL, the context in which to look for
4373/// a member access expression.
4374///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004375/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00004376/// the nested-name-specifier SS.
4377///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004378/// \param OPT when non-NULL, the search for visible declarations will
4379/// also walk the protocols in the qualified interfaces of \p OPT.
4380///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004381/// \returns a \c TypoCorrection containing the corrected name if the typo
4382/// along with information such as the \c NamedDecl where the corrected name
4383/// was declared, and any additional \c NestedNameSpecifier needed to access
4384/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
4385TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
4386 Sema::LookupNameKind LookupKind,
4387 Scope *S, CXXScopeSpec *SS,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004388 std::unique_ptr<CorrectionCandidateCallback> CCC,
John Thompson2255f2c2014-04-23 12:57:01 +00004389 CorrectTypoKind Mode,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004390 DeclContext *MemberContext,
4391 bool EnteringContext,
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004392 const ObjCObjectPointerType *OPT,
4393 bool RecordFailure) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004394 assert(CCC && "CorrectTypo requires a CorrectionCandidateCallback");
4395
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004396 // Always let the ExternalSource have the first chance at correction, even
4397 // if we would otherwise have given up.
4398 if (ExternalSource) {
4399 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004400 TypoName, LookupKind, S, SS, *CCC, MemberContext, EnteringContext, OPT))
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004401 return Correction;
4402 }
4403
Kaelyn Takata6c759512014-10-27 18:07:37 +00004404 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4405 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4406 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4407 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
4408 bool ObjCMessageReceiver = CCC->WantObjCSuper && !CCC->WantRemainingKeywords;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004409
Kaelyn Takata6c759512014-10-27 18:07:37 +00004410 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Kaelyn Takata6c759512014-10-27 18:07:37 +00004411 auto Consumer = makeTypoCorrectionConsumer(
4412 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004413 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004414
Kaelyn Takata6c759512014-10-27 18:07:37 +00004415 if (!Consumer)
4416 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004417
Douglas Gregor280e1ee2010-04-14 20:04:41 +00004418 // If we haven't found anything, we're done.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004419 if (Consumer->empty())
Nick Lewycky24653262014-12-16 21:39:02 +00004420 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregor2d435302009-12-30 17:04:44 +00004421
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004422 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4423 // is not more that about a third of the length of the typo's identifier.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004424 unsigned ED = Consumer->getBestEditDistance(true);
4425 unsigned TypoLen = Typo->getName().size();
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004426 if (ED > 0 && TypoLen / ED < 3)
Nick Lewycky24653262014-12-16 21:39:02 +00004427 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004428
Kaelyn Takata6c759512014-10-27 18:07:37 +00004429 TypoCorrection BestTC = Consumer->getNextCorrection();
4430 TypoCorrection SecondBestTC = Consumer->getNextCorrection();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004431 if (!BestTC)
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004432 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004433
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004434 ED = BestTC.getEditDistance();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004435
Kaelyn Takata6c759512014-10-27 18:07:37 +00004436 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004437 // If this was an unqualified lookup and we believe the callback
4438 // object wouldn't have filtered out possible corrections, note
4439 // that no correction was found.
Nick Lewycky24653262014-12-16 21:39:02 +00004440 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004441 }
4442
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004443 // If only a single name remains, return that result.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004444 if (!SecondBestTC ||
4445 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
4446 const TypoCorrection &Result = BestTC;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004447
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00004448 // Don't correct to a keyword that's the same as the typo; the keyword
4449 // wasn't actually in scope.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004450 if (ED == 0 && Result.isKeyword())
4451 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004452
David Blaikie04ea41c2012-10-12 20:00:44 +00004453 TypoCorrection TC = Result;
4454 TC.setCorrectionRange(SS, TypoName);
Kaelyn Takataa95ebc62014-06-17 23:47:29 +00004455 checkCorrectionVisibility(*this, TC);
David Blaikie04ea41c2012-10-12 20:00:44 +00004456 return TC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004457 } else if (SecondBestTC && ObjCMessageReceiver) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004458 // Prefer 'super' when we're completing in a message-receiver
4459 // context.
4460
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004461 if (BestTC.getCorrection().getAsString() != "super") {
4462 if (SecondBestTC.getCorrection().getAsString() == "super")
4463 BestTC = SecondBestTC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004464 else if ((*Consumer)["super"].front().isKeyword())
4465 BestTC = (*Consumer)["super"].front();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004466 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004467 // Don't correct to a keyword that's the same as the typo; the keyword
4468 // wasn't actually in scope.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004469 if (BestTC.getEditDistance() == 0 ||
4470 BestTC.getCorrection().getAsString() != "super")
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004471 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004472
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004473 BestTC.setCorrectionRange(SS, TypoName);
4474 return BestTC;
Douglas Gregoraf9eb592010-10-15 13:35:25 +00004475 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004476
Kaelyn Takata73429fd2014-06-10 21:03:49 +00004477 // Record the failure's location if needed and return an empty correction. If
4478 // this was an unqualified lookup and we believe the callback object did not
4479 // filter out possible corrections, also cache the failure for the typo.
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004480 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004481}
4482
Kaelyn Takata6c759512014-10-27 18:07:37 +00004483/// \brief Try to "correct" a typo in the source code by finding
4484/// visible declarations whose names are similar to the name that was
4485/// present in the source code.
4486///
4487/// \param TypoName the \c DeclarationNameInfo structure that contains
4488/// the name that was present in the source code along with its location.
4489///
4490/// \param LookupKind the name-lookup criteria used to search for the name.
4491///
4492/// \param S the scope in which name lookup occurs.
4493///
4494/// \param SS the nested-name-specifier that precedes the name we're
4495/// looking for, if present.
4496///
4497/// \param CCC A CorrectionCandidateCallback object that provides further
4498/// validation of typo correction candidates. It also provides flags for
4499/// determining the set of keywords permitted.
4500///
4501/// \param TDG A TypoDiagnosticGenerator functor that will be used to print
4502/// diagnostics when the actual typo correction is attempted.
4503///
Kaelyn Takata8363f042014-10-27 18:07:42 +00004504/// \param TRC A TypoRecoveryCallback functor that will be used to build an
4505/// Expr from a typo correction candidate.
4506///
Kaelyn Takata6c759512014-10-27 18:07:37 +00004507/// \param MemberContext if non-NULL, the context in which to look for
4508/// a member access expression.
4509///
4510/// \param EnteringContext whether we're entering the context described by
4511/// the nested-name-specifier SS.
4512///
4513/// \param OPT when non-NULL, the search for visible declarations will
4514/// also walk the protocols in the qualified interfaces of \p OPT.
4515///
4516/// \returns a new \c TypoExpr that will later be replaced in the AST with an
4517/// Expr representing the result of performing typo correction, or nullptr if
4518/// typo correction is not possible. If nullptr is returned, no diagnostics will
4519/// be emitted and it is the responsibility of the caller to emit any that are
4520/// needed.
4521TypoExpr *Sema::CorrectTypoDelayed(
4522 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4523 Scope *S, CXXScopeSpec *SS,
4524 std::unique_ptr<CorrectionCandidateCallback> CCC,
Kaelyn Takata8363f042014-10-27 18:07:42 +00004525 TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,
Kaelyn Takata6c759512014-10-27 18:07:37 +00004526 DeclContext *MemberContext, bool EnteringContext,
4527 const ObjCObjectPointerType *OPT) {
4528 assert(CCC && "CorrectTypoDelayed requires a CorrectionCandidateCallback");
4529
4530 TypoCorrection Empty;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004531 auto Consumer = makeTypoCorrectionConsumer(
4532 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004533 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Kaelyn Takata6c759512014-10-27 18:07:37 +00004534
4535 if (!Consumer || Consumer->empty())
4536 return nullptr;
4537
4538 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4539 // is not more that about a third of the length of the typo's identifier.
4540 unsigned ED = Consumer->getBestEditDistance(true);
4541 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4542 if (ED > 0 && Typo->getName().size() / ED < 3)
4543 return nullptr;
4544
4545 ExprEvalContexts.back().NumTypos++;
Kaelyn Takata8363f042014-10-27 18:07:42 +00004546 return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC));
Kaelyn Takata6c759512014-10-27 18:07:37 +00004547}
4548
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004549void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4550 if (!CDecl) return;
4551
4552 if (isKeyword())
4553 CorrectionDecls.clear();
4554
Kaelyn Uhrainf60b55a2012-11-19 18:49:53 +00004555 CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004556
4557 if (!CorrectionName)
4558 CorrectionName = CDecl->getDeclName();
4559}
4560
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004561std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4562 if (CorrectionNameSpec) {
4563 std::string tmpBuffer;
4564 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4565 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikied4da8722013-05-14 21:04:00 +00004566 PrefixOStream << CorrectionName;
Benjamin Kramer73faad62012-04-14 08:26:28 +00004567 return PrefixOStream.str();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004568 }
4569
4570 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00004571}
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004572
Nico Weberb58e51c2014-11-19 05:21:39 +00004573bool CorrectionCandidateCallback::ValidateCandidate(
4574 const TypoCorrection &candidate) {
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004575 if (!candidate.isResolved())
4576 return true;
4577
4578 if (candidate.isKeyword())
4579 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4580 WantRemainingKeywords || WantObjCSuper;
4581
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004582 bool HasNonType = false;
4583 bool HasStaticMethod = false;
4584 bool HasNonStaticMethod = false;
4585 for (Decl *D : candidate) {
4586 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
4587 D = FTD->getTemplatedDecl();
4588 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4589 if (Method->isStatic())
4590 HasStaticMethod = true;
4591 else
4592 HasNonStaticMethod = true;
4593 }
4594 if (!isa<TypeDecl>(D))
4595 HasNonType = true;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004596 }
4597
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004598 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
4599 !candidate.getCorrectionSpecifier())
4600 return false;
4601
4602 return WantTypeSpecifiers || HasNonType;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004603}
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004604
4605FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004606 bool HasExplicitTemplateArgs,
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004607 MemberExpr *ME)
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004608 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004609 CurContext(SemaRef.CurContext), MemberFn(ME) {
Kaelyn Takatab04846b2014-07-28 18:14:02 +00004610 WantTypeSpecifiers = false;
4611 WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus && NumArgs == 1;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004612 WantRemainingKeywords = false;
4613}
4614
4615bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4616 if (!candidate.getCorrectionDecl())
4617 return candidate.isKeyword();
4618
Aaron Ballman1e606f42014-07-15 22:03:49 +00004619 for (auto *C : candidate) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004620 FunctionDecl *FD = nullptr;
Aaron Ballman1e606f42014-07-15 22:03:49 +00004621 NamedDecl *ND = C->getUnderlyingDecl();
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004622 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4623 FD = FTD->getTemplatedDecl();
4624 if (!HasExplicitTemplateArgs && !FD) {
4625 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4626 // If the Decl is neither a function nor a template function,
4627 // determine if it is a pointer or reference to a function. If so,
4628 // check against the number of arguments expected for the pointee.
4629 QualType ValType = cast<ValueDecl>(ND)->getType();
4630 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4631 ValType = ValType->getPointeeType();
4632 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
Alp Toker9cacbab2014-01-20 20:26:09 +00004633 if (FPT->getNumParams() == NumArgs)
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004634 return true;
4635 }
4636 }
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004637
4638 // Skip the current candidate if it is not a FunctionDecl or does not accept
4639 // the current number of arguments.
4640 if (!FD || !(FD->getNumParams() >= NumArgs &&
4641 FD->getMinRequiredArguments() <= NumArgs))
4642 continue;
4643
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004644 // If the current candidate is a non-static C++ method, skip the candidate
4645 // unless the method being corrected--or the current DeclContext, if the
4646 // function being corrected is not a method--is a method in the same class
4647 // or a descendent class of the candidate's parent class.
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004648 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004649 if (MemberFn || !MD->isStatic()) {
4650 CXXMethodDecl *CurMD =
4651 MemberFn
4652 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
4653 : dyn_cast_or_null<CXXMethodDecl>(CurContext);
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004654 CXXRecordDecl *CurRD =
Craig Topperc3ec1492014-05-26 06:22:03 +00004655 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004656 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
4657 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
4658 continue;
4659 }
4660 }
4661 return true;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004662 }
4663 return false;
4664}
Richard Smithf9b15102013-08-17 00:46:16 +00004665
4666void Sema::diagnoseTypo(const TypoCorrection &Correction,
4667 const PartialDiagnostic &TypoDiag,
4668 bool ErrorRecovery) {
4669 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
4670 ErrorRecovery);
4671}
4672
Richard Smithe156254d2013-08-20 20:35:18 +00004673/// Find which declaration we should import to provide the definition of
4674/// the given declaration.
Richard Smith42413142015-05-15 20:05:43 +00004675static NamedDecl *getDefinitionToImport(NamedDecl *D) {
4676 if (VarDecl *VD = dyn_cast<VarDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004677 return VD->getDefinition();
4678 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Richard Smith42413142015-05-15 20:05:43 +00004679 return FD->isDefined(FD) ? const_cast<FunctionDecl*>(FD) : nullptr;
4680 if (TagDecl *TD = dyn_cast<TagDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004681 return TD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00004682 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004683 return ID->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00004684 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004685 return PD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00004686 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004687 return getDefinitionToImport(TD->getTemplatedDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004688 return nullptr;
Richard Smithe156254d2013-08-20 20:35:18 +00004689}
4690
Richard Smithf2b1eb92015-06-15 20:15:48 +00004691void Sema::diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
4692 bool NeedDefinition, bool Recover) {
4693 assert(!isVisible(Decl) && "missing import for non-hidden decl?");
4694
4695 // Suggest importing a module providing the definition of this entity, if
4696 // possible.
4697 NamedDecl *Def = getDefinitionToImport(Decl);
4698 if (!Def)
4699 Def = Decl;
4700
4701 // FIXME: Add a Fix-It that imports the corresponding module or includes
4702 // the header.
4703 Module *Owner = getOwningModule(Decl);
4704 assert(Owner && "definition of hidden declaration is not in a module");
4705
Richard Smith35c1df52015-06-17 20:16:32 +00004706 llvm::SmallVector<Module*, 8> OwningModules;
4707 OwningModules.push_back(Owner);
Richard Smithf2b1eb92015-06-15 20:15:48 +00004708 auto Merged = Context.getModulesWithMergedDefinition(Decl);
Richard Smith35c1df52015-06-17 20:16:32 +00004709 OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end());
4710
4711 diagnoseMissingImport(Loc, Decl, Decl->getLocation(), OwningModules,
4712 NeedDefinition ? MissingImportKind::Definition
4713 : MissingImportKind::Declaration,
4714 Recover);
4715}
4716
4717void Sema::diagnoseMissingImport(SourceLocation UseLoc, NamedDecl *Decl,
4718 SourceLocation DeclLoc,
4719 ArrayRef<Module *> Modules,
4720 MissingImportKind MIK, bool Recover) {
4721 assert(!Modules.empty());
4722
4723 if (Modules.size() > 1) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00004724 std::string ModuleList;
Richard Smithf2b1eb92015-06-15 20:15:48 +00004725 unsigned N = 0;
Richard Smith35c1df52015-06-17 20:16:32 +00004726 for (Module *M : Modules) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00004727 ModuleList += "\n ";
Richard Smith35c1df52015-06-17 20:16:32 +00004728 if (++N == 5 && N != Modules.size()) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00004729 ModuleList += "[...]";
4730 break;
4731 }
4732 ModuleList += M->getFullModuleName();
4733 }
4734
Richard Smith35c1df52015-06-17 20:16:32 +00004735 Diag(UseLoc, diag::err_module_unimported_use_multiple)
4736 << (int)MIK << Decl << ModuleList;
Richard Smithf2b1eb92015-06-15 20:15:48 +00004737 } else {
Richard Smith35c1df52015-06-17 20:16:32 +00004738 Diag(UseLoc, diag::err_module_unimported_use)
4739 << (int)MIK << Decl << Modules[0]->getFullModuleName();
Richard Smithf2b1eb92015-06-15 20:15:48 +00004740 }
Richard Smith35c1df52015-06-17 20:16:32 +00004741
4742 unsigned DiagID;
4743 switch (MIK) {
4744 case MissingImportKind::Declaration:
4745 DiagID = diag::note_previous_declaration;
4746 break;
4747 case MissingImportKind::Definition:
4748 DiagID = diag::note_previous_definition;
4749 break;
4750 case MissingImportKind::DefaultArgument:
4751 DiagID = diag::note_default_argument_declared_here;
4752 break;
4753 }
4754 Diag(DeclLoc, DiagID);
Richard Smithf2b1eb92015-06-15 20:15:48 +00004755
4756 // Try to recover by implicitly importing this module.
4757 if (Recover)
Richard Smith35c1df52015-06-17 20:16:32 +00004758 createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
Richard Smithf2b1eb92015-06-15 20:15:48 +00004759}
4760
Richard Smithf9b15102013-08-17 00:46:16 +00004761/// \brief Diagnose a successfully-corrected typo. Separated from the correction
4762/// itself to allow external validation of the result, etc.
4763///
4764/// \param Correction The result of performing typo correction.
4765/// \param TypoDiag The diagnostic to produce. This will have the corrected
4766/// string added to it (and usually also a fixit).
4767/// \param PrevNote A note to use when indicating the location of the entity to
4768/// which we are correcting. Will have the correction string added to it.
4769/// \param ErrorRecovery If \c true (the default), the caller is going to
4770/// recover from the typo as if the corrected string had been typed.
4771/// In this case, \c PDiag must be an error, and we will attach a fixit
4772/// to it.
4773void Sema::diagnoseTypo(const TypoCorrection &Correction,
4774 const PartialDiagnostic &TypoDiag,
4775 const PartialDiagnostic &PrevNote,
4776 bool ErrorRecovery) {
4777 std::string CorrectedStr = Correction.getAsString(getLangOpts());
4778 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
4779 FixItHint FixTypo = FixItHint::CreateReplacement(
4780 Correction.getCorrectionRange(), CorrectedStr);
4781
Richard Smithe156254d2013-08-20 20:35:18 +00004782 // Maybe we're just missing a module import.
4783 if (Correction.requiresImport()) {
4784 NamedDecl *Decl = Correction.getCorrectionDecl();
4785 assert(Decl && "import required but no declaration to import");
4786
Richard Smithf2b1eb92015-06-15 20:15:48 +00004787 diagnoseMissingImport(Correction.getCorrectionRange().getBegin(), Decl,
4788 /*NeedDefinition*/ false, ErrorRecovery);
Richard Smithe156254d2013-08-20 20:35:18 +00004789 return;
4790 }
4791
Richard Smithf9b15102013-08-17 00:46:16 +00004792 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
4793 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
4794
4795 NamedDecl *ChosenDecl =
Craig Topperc3ec1492014-05-26 06:22:03 +00004796 Correction.isKeyword() ? nullptr : Correction.getCorrectionDecl();
Richard Smithf9b15102013-08-17 00:46:16 +00004797 if (PrevNote.getDiagID() && ChosenDecl)
4798 Diag(ChosenDecl->getLocation(), PrevNote)
4799 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
4800}
Kaelyn Takata6c759512014-10-27 18:07:37 +00004801
Kaelyn Takata8363f042014-10-27 18:07:42 +00004802TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
4803 TypoDiagnosticGenerator TDG,
4804 TypoRecoveryCallback TRC) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00004805 assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
4806 auto TE = new (Context) TypoExpr(Context.DependentTy);
4807 auto &State = DelayedTypos[TE];
4808 State.Consumer = std::move(TCC);
4809 State.DiagHandler = std::move(TDG);
Kaelyn Takata8363f042014-10-27 18:07:42 +00004810 State.RecoveryHandler = std::move(TRC);
Kaelyn Takata6c759512014-10-27 18:07:37 +00004811 return TE;
4812}
4813
4814const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
4815 auto Entry = DelayedTypos.find(TE);
4816 assert(Entry != DelayedTypos.end() &&
4817 "Failed to get the state for a TypoExpr!");
4818 return Entry->second;
4819}
4820
4821void Sema::clearDelayedTypo(TypoExpr *TE) {
4822 DelayedTypos.erase(TE);
4823}