blob: bf67ae29c1d46b7cba18135ef0ca4430b0b857be [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
Richard Smith826711d2015-07-29 23:38:25 +0000357/// \brief Determine whether \p D is a better lookup result than \p Existing,
358/// given that they declare the same entity.
359static bool isPreferredLookupResult(Sema::LookupNameKind Kind,
360 NamedDecl *D, NamedDecl *Existing) {
361 // When looking up redeclarations of a using declaration, prefer a using
362 // shadow declaration over any other declaration of the same entity.
363 if (Kind == Sema::LookupUsingDeclName && isa<UsingShadowDecl>(D) &&
364 !isa<UsingShadowDecl>(Existing))
365 return true;
366
367 auto *DUnderlying = D->getUnderlyingDecl();
368 auto *EUnderlying = Existing->getUnderlyingDecl();
369
370 // If they have different underlying declarations, pick one arbitrarily
371 // (this happens when two type declarations denote the same type).
372 // FIXME: Should we prefer a struct declaration over a typedef or vice versa?
373 // If a name could be a typedef-name or a class-name, which is it?
374 if (DUnderlying->getCanonicalDecl() != EUnderlying->getCanonicalDecl()) {
375 assert(isa<TypeDecl>(DUnderlying) && isa<TypeDecl>(EUnderlying));
376 return false;
377 }
378
379 // If D is newer than Existing, prefer it.
380 for (Decl *Prev = DUnderlying->getPreviousDecl(); Prev;
381 Prev = Prev->getPreviousDecl())
382 if (Prev == EUnderlying)
383 return true;
384
385 return false;
386}
387
John McCall283b9012009-11-22 00:44:51 +0000388/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000389void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000390 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000391
John McCall9f3059a2009-10-09 21:13:30 +0000392 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000393 if (N == 0) {
Richard Smith826711d2015-07-29 23:38:25 +0000394 assert(ResultKind == NotFound ||
395 ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000396 return;
397 }
398
John McCall283b9012009-11-22 00:44:51 +0000399 // If there's a single decl, we need to examine it to decide what
400 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000401 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000402 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
403 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000404 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000405 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000406 ResultKind = FoundUnresolvedValue;
407 return;
408 }
John McCall9f3059a2009-10-09 21:13:30 +0000409
John McCall6538c932009-10-10 05:48:19 +0000410 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000411 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000412
Richard Smitha534a312015-07-21 23:54:07 +0000413 llvm::SmallDenseMap<NamedDecl*, unsigned, 16> Unique;
Richard Smith826711d2015-07-29 23:38:25 +0000414 llvm::SmallDenseMap<QualType, unsigned, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000415
John McCall9f3059a2009-10-09 21:13:30 +0000416 bool Ambiguous = false;
417 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000418 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000419
420 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000421
John McCall9f3059a2009-10-09 21:13:30 +0000422 unsigned I = 0;
423 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000424 NamedDecl *D = Decls[I]->getUnderlyingDecl();
425 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000426
Argyrios Kyrtzidis1fcd7fd2013-02-22 06:58:37 +0000427 // Ignore an invalid declaration unless it's the only one left.
428 if (D->isInvalidDecl() && I < N-1) {
429 Decls[I] = Decls[--N];
430 continue;
431 }
432
Richard Smith826711d2015-07-29 23:38:25 +0000433 llvm::Optional<unsigned> ExistingI;
434
Douglas Gregor13e65872010-08-11 14:45:53 +0000435 // Redeclarations of types via typedef can occur both within a scope
436 // and, through using declarations and directives, across scopes. There is
437 // no ambiguity if they all refer to the same type, so unique based on the
438 // canonical type.
439 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
Richard Smith826711d2015-07-29 23:38:25 +0000440 // FIXME: Why are nested type declarations treated differently?
Douglas Gregor13e65872010-08-11 14:45:53 +0000441 if (!TD->getDeclContext()->isRecord()) {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000442 QualType T = getSema().Context.getTypeDeclType(TD);
Richard Smith826711d2015-07-29 23:38:25 +0000443 auto UniqueResult = UniqueTypes.insert(
444 std::make_pair(getSema().Context.getCanonicalType(T), I));
445 if (!UniqueResult.second) {
446 // The type is not unique.
447 ExistingI = UniqueResult.first->second;
Douglas Gregor13e65872010-08-11 14:45:53 +0000448 }
449 }
450 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000451
Richard Smith826711d2015-07-29 23:38:25 +0000452 // For non-type declarations, check for a prior lookup result naming this
453 // canonical declaration.
454 if (!ExistingI) {
455 auto UniqueResult = Unique.insert(std::make_pair(D, I));
456 if (!UniqueResult.second) {
457 // We've seen this entity before.
458 ExistingI = UniqueResult.first->second;
Richard Smitha534a312015-07-21 23:54:07 +0000459 }
Richard Smith826711d2015-07-29 23:38:25 +0000460 }
461
462 if (ExistingI) {
463 // This is not a unique lookup result. Pick one of the results and
464 // discard the other.
465 if (isPreferredLookupResult(getLookupKind(), Decls[I],
466 Decls[*ExistingI]))
467 Decls[*ExistingI] = Decls[I];
468 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000469 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000470 }
471
Douglas Gregor13e65872010-08-11 14:45:53 +0000472 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000473
Douglas Gregor13e65872010-08-11 14:45:53 +0000474 if (isa<UnresolvedUsingValueDecl>(D)) {
475 HasUnresolved = true;
476 } else if (isa<TagDecl>(D)) {
477 if (HasTag)
478 Ambiguous = true;
479 UniqueTagIndex = I;
480 HasTag = true;
481 } else if (isa<FunctionTemplateDecl>(D)) {
482 HasFunction = true;
483 HasFunctionTemplate = true;
484 } else if (isa<FunctionDecl>(D)) {
485 HasFunction = true;
486 } else {
487 if (HasNonFunction)
488 Ambiguous = true;
489 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000490 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000491 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000492 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000493
John McCall9f3059a2009-10-09 21:13:30 +0000494 // C++ [basic.scope.hiding]p2:
495 // A class name or enumeration name can be hidden by the name of
496 // an object, function, or enumerator declared in the same
497 // scope. If a class or enumeration name and an object, function,
498 // or enumerator are declared in the same scope (in any order)
499 // with the same name, the class or enumeration name is hidden
500 // wherever the object, function, or enumerator name is visible.
501 // But it's still an error if there are distinct tag types found,
502 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000503 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000504 (HasFunction || HasNonFunction || HasUnresolved)) {
Richard Smith3876cc82013-10-30 01:02:04 +0000505 if (getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
506 getContextForScopeMatching(Decls[UniqueTagIndex ? 0 : N - 1])))
Douglas Gregore63d0872010-10-23 16:06:17 +0000507 Decls[UniqueTagIndex] = Decls[--N];
508 else
509 Ambiguous = true;
510 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000511
John McCall9f3059a2009-10-09 21:13:30 +0000512 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000513
John McCall80053822009-12-03 00:58:24 +0000514 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000515 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000516
John McCall9f3059a2009-10-09 21:13:30 +0000517 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000518 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000519 else if (HasUnresolved)
520 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000521 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000522 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000523 else
John McCall27b18f82009-11-17 02:14:36 +0000524 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000525}
526
John McCall5cebab12009-11-18 07:57:50 +0000527void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000528 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000529 for (I = P.begin(), E = P.end(); I != E; ++I)
David Blaikieff7d47a2012-12-19 00:45:41 +0000530 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
531 DE = I->Decls.end(); DI != DE; ++DI)
John McCall9f3059a2009-10-09 21:13:30 +0000532 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000533}
534
John McCall5cebab12009-11-18 07:57:50 +0000535void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000536 Paths = new CXXBasePaths;
537 Paths->swap(P);
538 addDeclsFromBasePaths(*Paths);
539 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000540 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000541}
542
John McCall5cebab12009-11-18 07:57:50 +0000543void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000544 Paths = new CXXBasePaths;
545 Paths->swap(P);
546 addDeclsFromBasePaths(*Paths);
547 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000548 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000549}
550
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000551void LookupResult::print(raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000552 Out << Decls.size() << " result(s)";
553 if (isAmbiguous()) Out << ", ambiguous";
554 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000555
John McCall9f3059a2009-10-09 21:13:30 +0000556 for (iterator I = begin(), E = end(); I != E; ++I) {
557 Out << "\n";
558 (*I)->print(Out, 2);
559 }
560}
561
Douglas Gregord3a59182010-02-12 05:48:04 +0000562/// \brief Lookup a builtin function, when name lookup would otherwise
563/// fail.
564static bool LookupBuiltin(Sema &S, LookupResult &R) {
565 Sema::LookupNameKind NameKind = R.getLookupKind();
566
567 // If we didn't find a use of this identifier, and if the identifier
568 // corresponds to a compiler builtin, create the decl object for the builtin
569 // now, injecting it into translation unit scope, and return it.
570 if (NameKind == Sema::LookupOrdinaryName ||
571 NameKind == Sema::LookupRedeclarationWithLinkage) {
572 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
573 if (II) {
Nico Webere1687c52013-06-20 21:44:55 +0000574 if (S.getLangOpts().CPlusPlus11 && S.getLangOpts().GNUMode &&
575 II == S.getFloat128Identifier()) {
576 // libstdc++4.7's type_traits expects type __float128 to exist, so
577 // insert a dummy type to make that header build in gnu++11 mode.
578 R.addDecl(S.getASTContext().getFloat128StubType());
579 return true;
580 }
581
Douglas Gregord3a59182010-02-12 05:48:04 +0000582 // If this is a builtin on this (or all) targets, create the decl.
583 if (unsigned BuiltinID = II->getBuiltinID()) {
584 // In C++, we don't have any predefined library functions like
585 // 'malloc'. Instead, we'll just error.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000586 if (S.getLangOpts().CPlusPlus &&
Douglas Gregord3a59182010-02-12 05:48:04 +0000587 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
588 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000589
590 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
591 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000592 R.isForRedeclaration(),
593 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000594 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000595 return true;
596 }
Douglas Gregord3a59182010-02-12 05:48:04 +0000597 }
598 }
599 }
600
601 return false;
602}
603
Douglas Gregor7454c562010-07-02 20:37:36 +0000604/// \brief Determine whether we can declare a special member function within
605/// the class at this point.
Richard Smith7d125a12012-11-27 21:20:31 +0000606static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +0000607 // We need to have a definition for the class.
608 if (!Class->getDefinition() || Class->isDependentContext())
609 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000610
Douglas Gregor7454c562010-07-02 20:37:36 +0000611 // We can't be in the middle of defining the class.
Richard Smith7d125a12012-11-27 21:20:31 +0000612 return !Class->isBeingDefined();
Douglas Gregor7454c562010-07-02 20:37:36 +0000613}
614
615void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smith7d125a12012-11-27 21:20:31 +0000616 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregora6d69502010-07-02 23:41:54 +0000617 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000618
619 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000620 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000621 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000622
Douglas Gregora6d69502010-07-02 23:41:54 +0000623 // If the copy constructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000624 if (Class->needsImplicitCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +0000625 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000626
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000627 // If the copy assignment operator has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000628 if (Class->needsImplicitCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000629 DeclareImplicitCopyAssignment(Class);
630
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000631 if (getLangOpts().CPlusPlus11) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000632 // If the move constructor has not yet been declared, do so now.
633 if (Class->needsImplicitMoveConstructor())
634 DeclareImplicitMoveConstructor(Class); // might not actually do it
635
636 // If the move assignment operator has not yet been declared, do so now.
637 if (Class->needsImplicitMoveAssignment())
638 DeclareImplicitMoveAssignment(Class); // might not actually do it
639 }
640
Douglas Gregor7454c562010-07-02 20:37:36 +0000641 // If the destructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000642 if (Class->needsImplicitDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000643 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000644}
645
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000646/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000647/// special member function.
648static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
649 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000650 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000651 case DeclarationName::CXXDestructorName:
652 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000653
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000654 case DeclarationName::CXXOperatorName:
655 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000656
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000657 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000658 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000659 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000660
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000661 return false;
662}
663
664/// \brief If there are any implicit member functions with the given name
665/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000666static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000667 DeclarationName Name,
668 const DeclContext *DC) {
669 if (!DC)
670 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000671
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000672 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000673 case DeclarationName::CXXConstructorName:
674 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith7d125a12012-11-27 21:20:31 +0000675 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000676 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000677 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000678 S.DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +0000679 if (Record->needsImplicitCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000680 S.DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000681 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000682 Record->needsImplicitMoveConstructor())
683 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000684 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000685 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000686
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000687 case DeclarationName::CXXDestructorName:
688 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith2be35f52012-12-01 02:35:44 +0000689 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smith7d125a12012-11-27 21:20:31 +0000690 CanDeclareSpecialMemberFunction(Record))
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000691 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000692 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000693
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000694 case DeclarationName::CXXOperatorName:
695 if (Name.getCXXOverloadedOperator() != OO_Equal)
696 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000697
Sebastian Redl22653ba2011-08-30 19:58:05 +0000698 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smith7d125a12012-11-27 21:20:31 +0000699 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000700 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smith2be35f52012-12-01 02:35:44 +0000701 if (Record->needsImplicitCopyAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000702 S.DeclareImplicitCopyAssignment(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000703 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000704 Record->needsImplicitMoveAssignment())
705 S.DeclareImplicitMoveAssignment(Class);
706 }
707 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000708 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000709
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000710 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000711 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000712 }
713}
Douglas Gregor7454c562010-07-02 20:37:36 +0000714
John McCall9f3059a2009-10-09 21:13:30 +0000715// Adds all qualifying matches for a name within a decl context to the
716// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000717static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000718 bool Found = false;
719
Douglas Gregor7454c562010-07-02 20:37:36 +0000720 // Lazily declare C++ special member functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000721 if (S.getLangOpts().CPlusPlus)
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000722 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000723
Douglas Gregor7454c562010-07-02 20:37:36 +0000724 // Perform lookup into this declaration context.
Richard Smithcf4bdde2015-02-21 02:45:19 +0000725 DeclContext::lookup_result DR = DC->lookup(R.getLookupName());
726 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E;
David Blaikieff7d47a2012-12-19 00:45:41 +0000727 ++I) {
John McCall401982f2010-01-20 21:53:11 +0000728 NamedDecl *D = *I;
Douglas Gregor4a814562011-12-14 16:03:29 +0000729 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000730 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000731 Found = true;
732 }
733 }
John McCall9f3059a2009-10-09 21:13:30 +0000734
Douglas Gregord3a59182010-02-12 05:48:04 +0000735 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
736 return true;
737
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000738 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000739 != DeclarationName::CXXConversionFunctionName ||
740 R.getLookupName().getCXXNameType()->isDependentType() ||
741 !isa<CXXRecordDecl>(DC))
742 return Found;
743
744 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000745 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000746 // name lookup. Instead, any conversion function templates visible in the
747 // context of the use are considered. [...]
748 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000749 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000750 return Found;
751
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +0000752 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
753 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruth3a693b72010-01-31 11:44:02 +0000754 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
755 if (!ConvTemplate)
756 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000757
Chandler Carruth3a693b72010-01-31 11:44:02 +0000758 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000759 // add the conversion function template. When we deduce template
760 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000761 // type of the new declaration with the type of the function template.
762 if (R.isForRedeclaration()) {
763 R.addDecl(ConvTemplate);
764 Found = true;
765 continue;
766 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000767
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000768 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000769 // [...] For each such operator, if argument deduction succeeds
770 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000771 // name lookup.
772 //
773 // When referencing a conversion function for any purpose other than
774 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000775 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000776 // specialization into the result set. We do this to avoid forcing all
777 // callers to perform special deduction for conversion functions.
Craig Toppere6706e42012-09-19 02:26:47 +0000778 TemplateDeductionInfo Info(R.getNameLoc());
Craig Topperc3ec1492014-05-26 06:22:03 +0000779 FunctionDecl *Specialization = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000780
781 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000782 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
783 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000784
Chandler Carruth3a693b72010-01-31 11:44:02 +0000785 // Compute the type of the function that we would expect the conversion
786 // function to have, if it were to match the name given.
787 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000788 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
Reid Kleckner78af0702013-08-27 23:08:25 +0000789 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
Richard Smith8acb4282014-07-31 21:57:55 +0000790 EPI.ExceptionSpec = EST_None;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000791 QualType ExpectedType
792 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000793 None, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000794
Chandler Carruth3a693b72010-01-31 11:44:02 +0000795 // Perform template argument deduction against the type that we would
796 // expect the function to have.
Craig Topperc3ec1492014-05-26 06:22:03 +0000797 if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
Chandler Carruth3a693b72010-01-31 11:44:02 +0000798 Specialization, Info)
799 == Sema::TDK_Success) {
800 R.addDecl(Specialization);
801 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000802 }
803 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000804
John McCall9f3059a2009-10-09 21:13:30 +0000805 return Found;
806}
807
John McCallf6c8a4e2009-11-10 07:01:13 +0000808// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000809static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000810CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000811 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000812
813 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
814
John McCallf6c8a4e2009-11-10 07:01:13 +0000815 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000816 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000817
John McCallf6c8a4e2009-11-10 07:01:13 +0000818 // Perform direct name lookup into the namespaces nominated by the
819 // using directives whose common ancestor is this namespace.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000820 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
821 if (LookupDirect(S, R, UUE.getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000822 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000823
824 R.resolveKind();
825
826 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000827}
828
829static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000830 if (DeclContext *Ctx = S->getEntity())
Douglas Gregor700792c2009-02-05 19:25:20 +0000831 return Ctx->isFileContext();
832 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000833}
Douglas Gregored8f2882009-01-30 01:04:22 +0000834
Douglas Gregor66230062010-03-15 14:33:29 +0000835// Find the next outer declaration context from this scope. This
836// routine actually returns the semantic outer context, which may
837// differ from the lexical context (encoded directly in the Scope
838// stack) when we are parsing a member of a class template. In this
839// case, the second element of the pair will be true, to indicate that
840// name lookup should continue searching in this semantic context when
841// it leaves the current template parameter scope.
842static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000843 DeclContext *DC = S->getEntity();
Craig Topperc3ec1492014-05-26 06:22:03 +0000844 DeclContext *Lexical = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000845 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000846 OuterS = OuterS->getParent()) {
847 if (OuterS->getEntity()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000848 Lexical = OuterS->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +0000849 break;
850 }
851 }
852
853 // C++ [temp.local]p8:
854 // In the definition of a member of a class template that appears
855 // outside of the namespace containing the class template
856 // definition, the name of a template-parameter hides the name of
857 // a member of this namespace.
858 //
859 // Example:
860 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000861 // namespace N {
862 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000863 //
864 // template<class T> class B {
865 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000866 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000867 // }
868 //
869 // template<class C> void N::B<C>::f(C) {
870 // C b; // C is the template parameter, not N::C
871 // }
872 //
873 // In this example, the lexical context we return is the
874 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000875 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000876 !S->getParent()->isTemplateParamScope())
877 return std::make_pair(Lexical, false);
878
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000879 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000880 // For the example, this is the scope for the template parameters of
881 // template<class C>.
882 Scope *OutermostTemplateScope = S->getParent();
883 while (OutermostTemplateScope->getParent() &&
884 OutermostTemplateScope->getParent()->isTemplateParamScope())
885 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000886
Douglas Gregor66230062010-03-15 14:33:29 +0000887 // Find the namespace context in which the original scope occurs. In
888 // the example, this is namespace N.
889 DeclContext *Semantic = DC;
890 while (!Semantic->isFileContext())
891 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000892
Douglas Gregor66230062010-03-15 14:33:29 +0000893 // Find the declaration context just outside of the template
894 // parameter scope. This is the context in which the template is
895 // being lexically declaration (a namespace context). In the
896 // example, this is the global scope.
897 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
898 Lexical->Encloses(Semantic))
899 return std::make_pair(Semantic, true);
900
901 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000902}
903
Richard Smith541b38b2013-09-20 01:15:31 +0000904namespace {
905/// An RAII object to specify that we want to find block scope extern
906/// declarations.
907struct FindLocalExternScope {
908 FindLocalExternScope(LookupResult &R)
909 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
910 Decl::IDNS_LocalExtern) {
911 R.setFindLocalExtern(R.getIdentifierNamespace() & Decl::IDNS_Ordinary);
912 }
913 void restore() {
914 R.setFindLocalExtern(OldFindLocalExtern);
915 }
916 ~FindLocalExternScope() {
917 restore();
918 }
919 LookupResult &R;
920 bool OldFindLocalExtern;
921};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000922}
Richard Smith541b38b2013-09-20 01:15:31 +0000923
John McCall27b18f82009-11-17 02:14:36 +0000924bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000925 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000926
927 DeclarationName Name = R.getLookupName();
Richard Smith1c34fb72013-08-13 18:18:50 +0000928 Sema::LookupNameKind NameKind = R.getLookupKind();
John McCall27b18f82009-11-17 02:14:36 +0000929
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000930 // If this is the name of an implicitly-declared special member function,
931 // go through the scope stack to implicitly declare
932 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
933 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +0000934 if (DeclContext *DC = PreS->getEntity())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000935 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
936 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000937
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000938 // Implicitly declare member functions with the name we're looking for, if in
939 // fact we are in a scope where it matters.
940
Douglas Gregor889ceb72009-02-03 19:21:40 +0000941 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000942 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000943 I = IdResolver.begin(Name),
944 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000945
Douglas Gregor889ceb72009-02-03 19:21:40 +0000946 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000947 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000948 // ...During unqualified name lookup (3.4.1), the names appear as if
949 // they were declared in the nearest enclosing namespace which contains
950 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000951 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000952 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000953 //
954 // For example:
955 // namespace A { int i; }
956 // void foo() {
957 // int i;
958 // {
959 // using namespace A;
960 // ++i; // finds local 'i', A::i appears at global scope
961 // }
962 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000963 //
Douglas Gregorcc9406c2013-04-08 23:11:25 +0000964 UnqualUsingDirectiveSet UDirs;
965 bool VisitedUsingDirectives = false;
Richard Smith1c34fb72013-08-13 18:18:50 +0000966 bool LeftStartingScope = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000967 DeclContext *OutsideOfTemplateParamDC = nullptr;
Richard Smith541b38b2013-09-20 01:15:31 +0000968
969 // When performing a scope lookup, we want to find local extern decls.
970 FindLocalExternScope FindLocals(R);
971
Douglas Gregor700792c2009-02-05 19:25:20 +0000972 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000973 DeclContext *Ctx = S->getEntity();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000974
Douglas Gregor889ceb72009-02-03 19:21:40 +0000975 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000976 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000977 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000978 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Richard Smith1c34fb72013-08-13 18:18:50 +0000979 if (NameKind == LookupRedeclarationWithLinkage) {
980 // Determine whether this (or a previous) declaration is
981 // out-of-scope.
982 if (!LeftStartingScope && !Initial->isDeclScope(*I))
983 LeftStartingScope = true;
984
985 // If we found something outside of our starting scope that
Richard Smith9a00bbf2013-10-16 21:12:00 +0000986 // does not have linkage, skip it. If it's a template parameter,
987 // we still find it, so we can diagnose the invalid redeclaration.
988 if (LeftStartingScope && !((*I)->hasLinkage()) &&
989 !(*I)->isTemplateParameter()) {
Richard Smith1c34fb72013-08-13 18:18:50 +0000990 R.setShadowed();
991 continue;
992 }
993 }
994
John McCall9f3059a2009-10-09 21:13:30 +0000995 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +0000996 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000997 }
998 }
John McCall9f3059a2009-10-09 21:13:30 +0000999 if (Found) {
1000 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +00001001 if (S->isClassScope())
1002 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
1003 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +00001004 return true;
1005 }
1006
Richard Smith1c34fb72013-08-13 18:18:50 +00001007 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
Richard Smith114394f2013-08-09 04:35:01 +00001008 // C++11 [class.friend]p11:
1009 // If a friend declaration appears in a local class and the name
1010 // specified is an unqualified name, a prior declaration is
1011 // looked up without considering scopes that are outside the
1012 // innermost enclosing non-class scope.
1013 return false;
1014 }
1015
Douglas Gregor66230062010-03-15 14:33:29 +00001016 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1017 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1018 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001019 // found nothing, so look into the contexts between the
Douglas Gregor66230062010-03-15 14:33:29 +00001020 // lexical and semantic declaration contexts returned by
1021 // findOuterContext(). This implements the name lookup behavior
1022 // of C++ [temp.local]p8.
1023 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +00001024 OutsideOfTemplateParamDC = nullptr;
Douglas Gregor66230062010-03-15 14:33:29 +00001025 }
1026
1027 if (Ctx) {
1028 DeclContext *OuterCtx;
1029 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001030 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregor66230062010-03-15 14:33:29 +00001031 if (SearchAfterTemplateScope)
1032 OutsideOfTemplateParamDC = OuterCtx;
1033
Douglas Gregorea166062010-03-15 15:26:48 +00001034 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +00001035 // We do not directly look into transparent contexts, since
1036 // those entities will be found in the nearest enclosing
1037 // non-transparent context.
1038 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +00001039 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +00001040
1041 // We do not look directly into function or method contexts,
1042 // since all of the local variables and parameters of the
1043 // function/method are present within the Scope.
1044 if (Ctx->isFunctionOrMethod()) {
1045 // If we have an Objective-C instance method, look for ivars
1046 // in the corresponding interface.
1047 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
1048 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1049 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1050 ObjCInterfaceDecl *ClassDeclared;
1051 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001052 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +00001053 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001054 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1055 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +00001056 R.resolveKind();
1057 return true;
1058 }
1059 }
1060 }
1061 }
1062
1063 continue;
1064 }
1065
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001066 // If this is a file context, we need to perform unqualified name
1067 // lookup considering using directives.
1068 if (Ctx->isFileContext()) {
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001069 // If we haven't handled using directives yet, do so now.
1070 if (!VisitedUsingDirectives) {
1071 // Add using directives from this context up to the top level.
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001072 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1073 if (UCtx->isTransparentContext())
1074 continue;
1075
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001076 UDirs.visit(UCtx, UCtx);
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001077 }
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001078
1079 // Find the innermost file scope, so we can add using directives
1080 // from local scopes.
1081 Scope *InnermostFileScope = S;
1082 while (InnermostFileScope &&
1083 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1084 InnermostFileScope = InnermostFileScope->getParent();
1085 UDirs.visitScopeChain(Initial, InnermostFileScope);
1086
1087 UDirs.done();
1088
1089 VisitedUsingDirectives = true;
1090 }
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001091
1092 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1093 R.resolveKind();
1094 return true;
1095 }
1096
1097 continue;
1098 }
1099
Douglas Gregor7f737c02009-09-10 16:57:35 +00001100 // Perform qualified name lookup into this context.
1101 // FIXME: In some cases, we know that every name that could be found by
1102 // this qualified name lookup will also be on the identifier chain. For
1103 // example, inside a class without any base classes, we never need to
1104 // perform qualified lookup because all of the members are on top of the
1105 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001106 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +00001107 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +00001108 }
Douglas Gregor700792c2009-02-05 19:25:20 +00001109 }
Douglas Gregored8f2882009-01-30 01:04:22 +00001110 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001111
John McCallf6c8a4e2009-11-10 07:01:13 +00001112 // Stop if we ran out of scopes.
1113 // FIXME: This really, really shouldn't be happening.
1114 if (!S) return false;
1115
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001116 // If we are looking for members, no need to look into global/namespace scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00001117 if (NameKind == LookupMemberName)
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001118 return false;
1119
Douglas Gregor700792c2009-02-05 19:25:20 +00001120 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +00001121 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +00001122 //
Mike Stump87c57ac2009-05-16 07:39:55 +00001123 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1124 // don't build it for each lookup!
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001125 if (!VisitedUsingDirectives) {
1126 UDirs.visitScopeChain(Initial, S);
1127 UDirs.done();
1128 }
Richard Smith541b38b2013-09-20 01:15:31 +00001129
1130 // If we're not performing redeclaration lookup, do not look for local
1131 // extern declarations outside of a function scope.
1132 if (!R.isForRedeclaration())
1133 FindLocals.restore();
1134
Douglas Gregor700792c2009-02-05 19:25:20 +00001135 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +00001136 // Unqualified name lookup in C++ requires looking into scopes
1137 // that aren't strictly lexical, and therefore we walk through the
1138 // context as well as walking through the scopes.
1139 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001140 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +00001141 bool Found = false;
John McCall48871652010-08-21 09:40:31 +00001142 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001143 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001144 // We found something. Look for anything else in our scope
1145 // with this same name and in an acceptable identifier
1146 // namespace, so that we can construct an overload set if we
1147 // need to.
John McCall9f3059a2009-10-09 21:13:30 +00001148 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +00001149 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001150 }
1151 }
1152
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001153 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +00001154 R.resolveKind();
1155 return true;
1156 }
1157
Ted Kremenekc37877d2013-10-08 17:08:03 +00001158 DeclContext *Ctx = S->getEntity();
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001159 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1160 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1161 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001162 // found nothing, so look into the contexts between the
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001163 // lexical and semantic declaration contexts returned by
1164 // findOuterContext(). This implements the name lookup behavior
1165 // of C++ [temp.local]p8.
1166 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +00001167 OutsideOfTemplateParamDC = nullptr;
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001168 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001169
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001170 if (Ctx) {
1171 DeclContext *OuterCtx;
1172 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001173 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001174 if (SearchAfterTemplateScope)
1175 OutsideOfTemplateParamDC = OuterCtx;
1176
1177 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1178 // We do not directly look into transparent contexts, since
1179 // those entities will be found in the nearest enclosing
1180 // non-transparent context.
1181 if (Ctx->isTransparentContext())
1182 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001183
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001184 // If we have a context, and it's not a context stashed in the
1185 // template parameter scope for an out-of-line definition, also
1186 // look into that context.
1187 if (!(Found && S && S->isTemplateParamScope())) {
1188 assert(Ctx->isFileContext() &&
1189 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001190
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001191 // Look into context considering using-directives.
1192 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1193 Found = true;
1194 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001195
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001196 if (Found) {
1197 R.resolveKind();
1198 return true;
1199 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001200
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001201 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1202 return false;
1203 }
1204 }
1205
Douglas Gregor3ce74932010-02-05 07:07:10 +00001206 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001207 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001208 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001209
John McCall9f3059a2009-10-09 21:13:30 +00001210 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001211}
1212
Richard Smith0e5d7b82013-07-25 23:08:39 +00001213/// \brief Find the declaration that a class temploid member specialization was
1214/// instantiated from, or the member itself if it is an explicit specialization.
1215static Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) {
1216 return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom();
1217}
1218
Richard Smith42413142015-05-15 20:05:43 +00001219Module *Sema::getOwningModule(Decl *Entity) {
1220 // If it's imported, grab its owning module.
1221 Module *M = Entity->getImportedOwningModule();
1222 if (M || !isa<NamedDecl>(Entity) || !cast<NamedDecl>(Entity)->isHidden())
1223 return M;
1224 assert(!Entity->isFromASTFile() &&
1225 "hidden entity from AST file has no owning module");
1226
Richard Smith87bb5692015-06-09 00:35:49 +00001227 if (!getLangOpts().ModulesLocalVisibility) {
1228 // If we're not tracking visibility locally, the only way a declaration
1229 // can be hidden and local is if it's hidden because it's parent is (for
1230 // instance, maybe this is a lazily-declared special member of an imported
1231 // class).
1232 auto *Parent = cast<NamedDecl>(Entity->getDeclContext());
1233 assert(Parent->isHidden() && "unexpectedly hidden decl");
1234 return getOwningModule(Parent);
1235 }
1236
Richard Smith42413142015-05-15 20:05:43 +00001237 // It's local and hidden; grab or compute its owning module.
1238 M = Entity->getLocalOwningModule();
1239 if (M)
1240 return M;
1241
1242 if (auto *Containing =
1243 PP.getModuleContainingLocation(Entity->getLocation())) {
1244 M = Containing;
1245 } else if (Entity->isInvalidDecl() || Entity->getLocation().isInvalid()) {
1246 // Don't bother tracking visibility for invalid declarations with broken
1247 // locations.
1248 cast<NamedDecl>(Entity)->setHidden(false);
1249 } else {
1250 // We need to assign a module to an entity that exists outside of any
1251 // module, so that we can hide it from modules that we textually enter.
1252 // Invent a fake module for all such entities.
1253 if (!CachedFakeTopLevelModule) {
1254 CachedFakeTopLevelModule =
1255 PP.getHeaderSearchInfo().getModuleMap().findOrCreateModule(
1256 "<top-level>", nullptr, false, false).first;
1257
1258 auto &SrcMgr = PP.getSourceManager();
1259 SourceLocation StartLoc =
1260 SrcMgr.getLocForStartOfFile(SrcMgr.getMainFileID());
1261 auto &TopLevel =
1262 VisibleModulesStack.empty() ? VisibleModules : VisibleModulesStack[0];
1263 TopLevel.setVisible(CachedFakeTopLevelModule, StartLoc);
1264 }
1265
1266 M = CachedFakeTopLevelModule;
1267 }
1268
1269 if (M)
1270 Entity->setLocalOwningModule(M);
1271 return M;
1272}
1273
Richard Smithd9ba2242015-05-07 03:54:19 +00001274void Sema::makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc) {
Richard Smith87bb5692015-06-09 00:35:49 +00001275 if (auto *M = PP.getModuleContainingLocation(Loc))
1276 Context.mergeDefinitionIntoModule(ND, M);
1277 else
1278 // We're not building a module; just make the definition visible.
1279 ND->setHidden(false);
Richard Smith63e09bf2015-06-17 20:39:41 +00001280
1281 // If ND is a template declaration, make the template parameters
1282 // visible too. They're not (necessarily) within a mergeable DeclContext.
1283 if (auto *TD = dyn_cast<TemplateDecl>(ND))
1284 for (auto *Param : *TD->getTemplateParameters())
1285 makeMergedDefinitionVisible(Param, Loc);
Richard Smithd9ba2242015-05-07 03:54:19 +00001286}
1287
Richard Smith0e5d7b82013-07-25 23:08:39 +00001288/// \brief Find the module in which the given declaration was defined.
Richard Smith42413142015-05-15 20:05:43 +00001289static Module *getDefiningModule(Sema &S, Decl *Entity) {
Richard Smith0e5d7b82013-07-25 23:08:39 +00001290 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1291 // If this function was instantiated from a template, the defining module is
1292 // the module containing the pattern.
1293 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1294 Entity = Pattern;
1295 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
Reid Klecknere7367d62014-10-14 20:28:40 +00001296 if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
1297 Entity = Pattern;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001298 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1299 if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo())
1300 Entity = getInstantiatedFrom(ED, MSInfo);
1301 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1302 // FIXME: Map from variable template specializations back to the template.
1303 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo())
1304 Entity = getInstantiatedFrom(VD, MSInfo);
1305 }
1306
1307 // Walk up to the containing context. That might also have been instantiated
1308 // from a template.
1309 DeclContext *Context = Entity->getDeclContext();
1310 if (Context->isFileContext())
Richard Smith42413142015-05-15 20:05:43 +00001311 return S.getOwningModule(Entity);
1312 return getDefiningModule(S, cast<Decl>(Context));
Richard Smith0e5d7b82013-07-25 23:08:39 +00001313}
1314
1315llvm::DenseSet<Module*> &Sema::getLookupModules() {
1316 unsigned N = ActiveTemplateInstantiations.size();
1317 for (unsigned I = ActiveTemplateInstantiationLookupModules.size();
1318 I != N; ++I) {
Richard Smith42413142015-05-15 20:05:43 +00001319 Module *M =
1320 getDefiningModule(*this, ActiveTemplateInstantiations[I].Entity);
Richard Smith0e5d7b82013-07-25 23:08:39 +00001321 if (M && !LookupModulesCache.insert(M).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00001322 M = nullptr;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001323 ActiveTemplateInstantiationLookupModules.push_back(M);
1324 }
1325 return LookupModulesCache;
1326}
1327
Richard Smith42413142015-05-15 20:05:43 +00001328bool Sema::hasVisibleMergedDefinition(NamedDecl *Def) {
1329 for (Module *Merged : Context.getModulesWithMergedDefinition(Def))
1330 if (isModuleVisible(Merged))
1331 return true;
1332 return false;
1333}
1334
Richard Smithe7bd6de2015-06-10 20:30:23 +00001335template<typename ParmDecl>
Richard Smith35c1df52015-06-17 20:16:32 +00001336static bool
1337hasVisibleDefaultArgument(Sema &S, const ParmDecl *D,
1338 llvm::SmallVectorImpl<Module *> *Modules) {
Richard Smithe7bd6de2015-06-10 20:30:23 +00001339 if (!D->hasDefaultArgument())
1340 return false;
1341
1342 while (D) {
1343 auto &DefaultArg = D->getDefaultArgStorage();
1344 if (!DefaultArg.isInherited() && S.isVisible(D))
1345 return true;
1346
Richard Smith63e09bf2015-06-17 20:39:41 +00001347 if (!DefaultArg.isInherited() && Modules) {
1348 auto *NonConstD = const_cast<ParmDecl*>(D);
1349 Modules->push_back(S.getOwningModule(NonConstD));
1350 const auto &Merged = S.Context.getModulesWithMergedDefinition(NonConstD);
1351 Modules->insert(Modules->end(), Merged.begin(), Merged.end());
1352 }
Richard Smith35c1df52015-06-17 20:16:32 +00001353
Richard Smithe7bd6de2015-06-10 20:30:23 +00001354 // If there was a previous default argument, maybe its parameter is visible.
1355 D = DefaultArg.getInheritedFrom();
1356 }
1357 return false;
1358}
1359
Richard Smith35c1df52015-06-17 20:16:32 +00001360bool Sema::hasVisibleDefaultArgument(const NamedDecl *D,
1361 llvm::SmallVectorImpl<Module *> *Modules) {
Richard Smithe7bd6de2015-06-10 20:30:23 +00001362 if (auto *P = dyn_cast<TemplateTypeParmDecl>(D))
Richard Smith35c1df52015-06-17 20:16:32 +00001363 return ::hasVisibleDefaultArgument(*this, P, Modules);
Richard Smithe7bd6de2015-06-10 20:30:23 +00001364 if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))
Richard Smith35c1df52015-06-17 20:16:32 +00001365 return ::hasVisibleDefaultArgument(*this, P, Modules);
1366 return ::hasVisibleDefaultArgument(*this, cast<TemplateTemplateParmDecl>(D),
1367 Modules);
Richard Smithe7bd6de2015-06-10 20:30:23 +00001368}
1369
Richard Smith0e5d7b82013-07-25 23:08:39 +00001370/// \brief Determine whether a declaration is visible to name lookup.
1371///
1372/// This routine determines whether the declaration D is visible in the current
1373/// lookup context, taking into account the current template instantiation
1374/// stack. During template instantiation, a declaration is visible if it is
1375/// visible from a module containing any entity on the template instantiation
1376/// path (by instantiating a template, you allow it to see the declarations that
1377/// your module can see, including those later on in your module).
1378bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001379 assert(D->isHidden() && "should not call this: not in slow case");
Richard Smith42413142015-05-15 20:05:43 +00001380 Module *DeclModule = SemaRef.getOwningModule(D);
1381 if (!DeclModule) {
1382 // getOwningModule() may have decided the declaration should not be hidden.
1383 assert(!D->isHidden() && "hidden decl not from a module");
1384 return true;
1385 }
1386
1387 // If the owning module is visible, and the decl is not module private,
1388 // then the decl is visible too. (Module private is ignored within the same
1389 // top-level module.)
1390 if (!D->isFromASTFile() || !D->isModulePrivate()) {
1391 if (SemaRef.isModuleVisible(DeclModule))
1392 return true;
1393 // Also check merged definitions.
1394 if (SemaRef.getLangOpts().ModulesLocalVisibility &&
1395 SemaRef.hasVisibleMergedDefinition(D))
1396 return true;
1397 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001398
Richard Smithbe3980b2015-03-27 00:41:57 +00001399 // If this declaration is not at namespace scope nor module-private,
1400 // then it is visible if its lexical parent has a visible definition.
1401 DeclContext *DC = D->getLexicalDeclContext();
1402 if (!D->isModulePrivate() &&
1403 DC && !DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) {
Richard Smithc7d48d12015-05-20 17:50:35 +00001404 // For a parameter, check whether our current template declaration's
1405 // lexical context is visible, not whether there's some other visible
1406 // definition of it, because parameters aren't "within" the definition.
1407 if ((D->isTemplateParameter() || isa<ParmVarDecl>(D))
1408 ? isVisible(SemaRef, cast<NamedDecl>(DC))
1409 : SemaRef.hasVisibleDefinition(cast<NamedDecl>(DC))) {
Richard Smith42413142015-05-15 20:05:43 +00001410 if (SemaRef.ActiveTemplateInstantiations.empty() &&
1411 // FIXME: Do something better in this case.
1412 !SemaRef.getLangOpts().ModulesLocalVisibility) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001413 // Cache the fact that this declaration is implicitly visible because
1414 // its parent has a visible definition.
1415 D->setHidden(false);
1416 }
1417 return true;
1418 }
1419 return false;
1420 }
1421
Richard Smith0e5d7b82013-07-25 23:08:39 +00001422 // Find the extra places where we need to look.
1423 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
1424 if (LookupModules.empty())
1425 return false;
1426
1427 // If our lookup set contains the decl's module, it's visible.
1428 if (LookupModules.count(DeclModule))
1429 return true;
1430
1431 // If the declaration isn't exported, it's not visible in any other module.
1432 if (D->isModulePrivate())
1433 return false;
1434
1435 // Check whether DeclModule is transitively exported to an import of
1436 // the lookup set.
1437 for (llvm::DenseSet<Module *>::iterator I = LookupModules.begin(),
1438 E = LookupModules.end();
1439 I != E; ++I)
1440 if ((*I)->isModuleVisible(DeclModule))
1441 return true;
1442 return false;
1443}
1444
Richard Smith42413142015-05-15 20:05:43 +00001445bool Sema::isVisibleSlow(const NamedDecl *D) {
1446 return LookupResult::isVisible(*this, const_cast<NamedDecl*>(D));
1447}
1448
Douglas Gregor4a814562011-12-14 16:03:29 +00001449/// \brief Retrieve the visible declaration corresponding to D, if any.
1450///
1451/// This routine determines whether the declaration D is visible in the current
1452/// module, with the current imports. If not, it checks whether any
1453/// redeclaration of D is visible, and if so, returns that declaration.
Richard Smith0e5d7b82013-07-25 23:08:39 +00001454///
Douglas Gregor4a814562011-12-14 16:03:29 +00001455/// \returns D, or a visible previous declaration of D, whichever is more recent
1456/// and visible. If no declaration of D is visible, returns null.
Richard Smithe156254d2013-08-20 20:35:18 +00001457static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
1458 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
Richard Smith0e5d7b82013-07-25 23:08:39 +00001459
Aaron Ballman86c93902014-03-06 23:45:36 +00001460 for (auto RD : D->redecls()) {
1461 if (auto ND = dyn_cast<NamedDecl>(RD)) {
Richard Smithe8292b12015-02-10 03:28:10 +00001462 // FIXME: This is wrong in the case where the previous declaration is not
1463 // visible in the same scope as D. This needs to be done much more
1464 // carefully.
Richard Smithe156254d2013-08-20 20:35:18 +00001465 if (LookupResult::isVisible(SemaRef, ND))
Douglas Gregor54079202012-01-06 22:05:37 +00001466 return ND;
1467 }
Douglas Gregor4a814562011-12-14 16:03:29 +00001468 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001469
Craig Topperc3ec1492014-05-26 06:22:03 +00001470 return nullptr;
Douglas Gregor4a814562011-12-14 16:03:29 +00001471}
1472
Richard Smithe156254d2013-08-20 20:35:18 +00001473NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +00001474 return findAcceptableDecl(getSema(), D);
Richard Smithe156254d2013-08-20 20:35:18 +00001475}
1476
Douglas Gregor34074322009-01-14 22:20:51 +00001477/// @brief Perform unqualified name lookup starting from a given
1478/// scope.
1479///
1480/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1481/// used to find names within the current scope. For example, 'x' in
1482/// @code
1483/// int x;
1484/// int f() {
1485/// return x; // unqualified name look finds 'x' in the global scope
1486/// }
1487/// @endcode
1488///
1489/// Different lookup criteria can find different names. For example, a
1490/// particular scope can have both a struct and a function of the same
1491/// name, and each can be found by certain lookup criteria. For more
1492/// information about lookup criteria, see the documentation for the
1493/// class LookupCriteria.
1494///
1495/// @param S The scope from which unqualified name lookup will
1496/// begin. If the lookup criteria permits, name lookup may also search
1497/// in the parent scopes.
1498///
James Dennett91738ff2012-06-22 10:32:46 +00001499/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1500/// look up and the lookup kind), and is updated with the results of lookup
1501/// including zero or more declarations and possibly additional information
1502/// used to diagnose ambiguities.
Douglas Gregor34074322009-01-14 22:20:51 +00001503///
James Dennett91738ff2012-06-22 10:32:46 +00001504/// @returns \c true if lookup succeeded and false otherwise.
John McCall27b18f82009-11-17 02:14:36 +00001505bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1506 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001507 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001508
John McCall27b18f82009-11-17 02:14:36 +00001509 LookupNameKind NameKind = R.getLookupKind();
1510
David Blaikiebbafb8a2012-03-11 07:00:24 +00001511 if (!getLangOpts().CPlusPlus) {
Douglas Gregor34074322009-01-14 22:20:51 +00001512 // Unqualified name lookup in C/Objective-C is purely lexical, so
1513 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001514 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001515 // Find the nearest non-transparent declaration scope.
1516 while (!(S->getFlags() & Scope::DeclScope) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001517 (S->getEntity() && S->getEntity()->isTransparentContext()))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001518 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001519 }
1520
Richard Smith541b38b2013-09-20 01:15:31 +00001521 // When performing a scope lookup, we want to find local extern decls.
1522 FindLocalExternScope FindLocals(R);
1523
Douglas Gregor34074322009-01-14 22:20:51 +00001524 // Scan up the scope chain looking for a decl that matches this
1525 // identifier that is in the appropriate namespace. This search
1526 // should not take long, as shadowing of names is uncommon, and
1527 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001528 bool LeftStartingScope = false;
1529
Douglas Gregored8f2882009-01-30 01:04:22 +00001530 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001531 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001532 I != IEnd; ++I)
Richard Smith0e5d7b82013-07-25 23:08:39 +00001533 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001534 if (NameKind == LookupRedeclarationWithLinkage) {
1535 // Determine whether this (or a previous) declaration is
1536 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001537 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001538 LeftStartingScope = true;
1539
1540 // If we found something outside of our starting scope that
1541 // does not have linkage, skip it.
Richard Smith1c34fb72013-08-13 18:18:50 +00001542 if (LeftStartingScope && !((*I)->hasLinkage())) {
1543 R.setShadowed();
Douglas Gregoreddf4332009-02-24 20:03:32 +00001544 continue;
Richard Smith1c34fb72013-08-13 18:18:50 +00001545 }
Douglas Gregoreddf4332009-02-24 20:03:32 +00001546 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001547 else if (NameKind == LookupObjCImplicitSelfParam &&
1548 !isa<ImplicitParamDecl>(*I))
1549 continue;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001550
Douglas Gregor4a814562011-12-14 16:03:29 +00001551 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001552
Douglas Gregorb59643b2012-01-03 23:26:26 +00001553 // Check whether there are any other declarations with the same name
1554 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001555 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001556 // Find the scope in which this declaration was declared (if it
1557 // actually exists in a Scope).
1558 while (S && !S->isDeclScope(D))
1559 S = S->getParent();
1560
1561 // If the scope containing the declaration is the translation unit,
1562 // then we'll need to perform our checks based on the matching
1563 // DeclContexts rather than matching scopes.
1564 if (S && isNamespaceOrTranslationUnitScope(S))
Craig Topperc3ec1492014-05-26 06:22:03 +00001565 S = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001566
1567 // Compute the DeclContext, if we need it.
Craig Topperc3ec1492014-05-26 06:22:03 +00001568 DeclContext *DC = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001569 if (!S)
1570 DC = (*I)->getDeclContext()->getRedeclContext();
1571
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001572 IdentifierResolver::iterator LastI = I;
1573 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001574 if (S) {
1575 // Match based on scope.
1576 if (!S->isDeclScope(*LastI))
1577 break;
1578 } else {
1579 // Match based on DeclContext.
1580 DeclContext *LastDC
1581 = (*LastI)->getDeclContext()->getRedeclContext();
1582 if (!LastDC->Equals(DC))
1583 break;
1584 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001585
1586 // If the declaration is in the right namespace and visible, add it.
1587 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1588 R.addDecl(LastD);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001589 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001590
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001591 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001592 }
Richard Smith541b38b2013-09-20 01:15:31 +00001593
John McCall9f3059a2009-10-09 21:13:30 +00001594 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001595 }
Douglas Gregor34074322009-01-14 22:20:51 +00001596 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001597 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001598 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001599 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001600 }
1601
1602 // If we didn't find a use of this identifier, and if the identifier
1603 // corresponds to a compiler builtin, create the decl object for the builtin
1604 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001605 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1606 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001607
Axel Naumann016538a2011-02-24 16:47:47 +00001608 // If we didn't find a use of this identifier, the ExternalSource
1609 // may be able to handle the situation.
1610 // Note: some lookup failures are expected!
1611 // See e.g. R.isForRedeclaration().
1612 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001613}
1614
John McCall6538c932009-10-10 05:48:19 +00001615/// @brief Perform qualified name lookup in the namespaces nominated by
1616/// using directives by the given context.
1617///
1618/// C++98 [namespace.qual]p2:
James Dennett51a8d8b2012-06-19 21:05:49 +00001619/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6538c932009-10-10 05:48:19 +00001620/// (where X is the global namespace), let S be the set of all
1621/// declarations of m in X and in the transitive closure of all
1622/// namespaces nominated by using-directives in X and its used
1623/// namespaces, except that using-directives are ignored in any
1624/// namespace, including X, directly containing one or more
1625/// declarations of m. No namespace is searched more than once in
1626/// the lookup of a name. If S is the empty set, the program is
1627/// ill-formed. Otherwise, if S has exactly one member, or if the
1628/// context of the reference is a using-declaration
1629/// (namespace.udecl), S is the required set of declarations of
1630/// m. Otherwise if the use of m is not one that allows a unique
1631/// declaration to be chosen from S, the program is ill-formed.
James Dennett51a8d8b2012-06-19 21:05:49 +00001632///
John McCall6538c932009-10-10 05:48:19 +00001633/// C++98 [namespace.qual]p5:
1634/// During the lookup of a qualified namespace member name, if the
1635/// lookup finds more than one declaration of the member, and if one
1636/// declaration introduces a class name or enumeration name and the
1637/// other declarations either introduce the same object, the same
1638/// enumerator or a set of functions, the non-type name hides the
1639/// class or enumeration name if and only if the declarations are
1640/// from the same namespace; otherwise (the declarations are from
1641/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001642static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001643 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001644 assert(StartDC->isFileContext() && "start context is not a file context");
1645
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001646 DeclContext::udir_range UsingDirectives = StartDC->using_directives();
1647 if (UsingDirectives.begin() == UsingDirectives.end()) return false;
John McCall6538c932009-10-10 05:48:19 +00001648
1649 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001650 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001651 Visited.insert(StartDC);
1652
1653 // We have not yet looked into these namespaces, much less added
1654 // their "using-children" to the queue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001655 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001656
1657 // We have already looked into the initial namespace; seed the queue
1658 // with its using-children.
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001659 for (auto *I : UsingDirectives) {
1660 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +00001661 if (Visited.insert(ND).second)
John McCall6538c932009-10-10 05:48:19 +00001662 Queue.push_back(ND);
1663 }
1664
1665 // The easiest way to implement the restriction in [namespace.qual]p5
1666 // is to check whether any of the individual results found a tag
1667 // and, if so, to declare an ambiguity if the final result is not
1668 // a tag.
1669 bool FoundTag = false;
1670 bool FoundNonTag = false;
1671
John McCall5cebab12009-11-18 07:57:50 +00001672 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001673
1674 bool Found = false;
1675 while (!Queue.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001676 NamespaceDecl *ND = Queue.pop_back_val();
John McCall6538c932009-10-10 05:48:19 +00001677
1678 // We go through some convolutions here to avoid copying results
1679 // between LookupResults.
1680 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001681 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001682 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001683
1684 if (FoundDirect) {
1685 // First do any local hiding.
1686 DirectR.resolveKind();
1687
1688 // If the local result is a tag, remember that.
1689 if (DirectR.isSingleTagDecl())
1690 FoundTag = true;
1691 else
1692 FoundNonTag = true;
1693
1694 // Append the local results to the total results if necessary.
1695 if (UseLocal) {
1696 R.addAllDecls(LocalR);
1697 LocalR.clear();
1698 }
1699 }
1700
1701 // If we find names in this namespace, ignore its using directives.
1702 if (FoundDirect) {
1703 Found = true;
1704 continue;
1705 }
1706
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001707 for (auto I : ND->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00001708 NamespaceDecl *Nom = I->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +00001709 if (Visited.insert(Nom).second)
John McCall6538c932009-10-10 05:48:19 +00001710 Queue.push_back(Nom);
1711 }
1712 }
1713
1714 if (Found) {
1715 if (FoundTag && FoundNonTag)
1716 R.setAmbiguousQualifiedTagHiding();
1717 else
1718 R.resolveKind();
1719 }
1720
1721 return Found;
1722}
1723
Douglas Gregor39982192010-08-15 06:18:01 +00001724/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001725static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00001726 CXXBasePath &Path, DeclarationName Name) {
Douglas Gregor39982192010-08-15 06:18:01 +00001727 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001728
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00001729 Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00001730 return !Path.Decls.empty();
Douglas Gregor39982192010-08-15 06:18:01 +00001731}
1732
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001733/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001734/// static members, nested types, and enumerators.
1735template<typename InputIterator>
1736static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1737 Decl *D = (*First)->getUnderlyingDecl();
1738 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1739 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001740
Douglas Gregorc0d24902010-10-22 22:08:47 +00001741 if (isa<CXXMethodDecl>(D)) {
1742 // Determine whether all of the methods are static.
1743 bool AllMethodsAreStatic = true;
1744 for(; First != Last; ++First) {
1745 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001746
Douglas Gregorc0d24902010-10-22 22:08:47 +00001747 if (!isa<CXXMethodDecl>(D)) {
1748 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1749 break;
1750 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001751
Douglas Gregorc0d24902010-10-22 22:08:47 +00001752 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1753 AllMethodsAreStatic = false;
1754 break;
1755 }
1756 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001757
Douglas Gregorc0d24902010-10-22 22:08:47 +00001758 if (AllMethodsAreStatic)
1759 return true;
1760 }
1761
1762 return false;
1763}
1764
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001765/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001766///
1767/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1768/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001769/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001770///
1771/// Different lookup criteria can find different names. For example, a
1772/// particular scope can have both a struct and a function of the same
1773/// name, and each can be found by certain lookup criteria. For more
1774/// information about lookup criteria, see the documentation for the
1775/// class LookupCriteria.
1776///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001777/// \param R captures both the lookup criteria and any lookup results found.
1778///
1779/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001780/// search. If the lookup criteria permits, name lookup may also search
1781/// in the parent contexts or (for C++ classes) base classes.
1782///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001783/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001784/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001785///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001786/// \returns true if lookup succeeded, false if it failed.
1787bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1788 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001789 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001790
John McCall27b18f82009-11-17 02:14:36 +00001791 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001792 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001793
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001794 // Make sure that the declaration context is complete.
1795 assert((!isa<TagDecl>(LookupCtx) ||
1796 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00001797 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith7d137e32012-03-23 03:33:32 +00001798 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001799 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001800
Douglas Gregor34074322009-01-14 22:20:51 +00001801 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001802 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001803 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001804 if (isa<CXXRecordDecl>(LookupCtx))
1805 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001806 return true;
1807 }
Douglas Gregor34074322009-01-14 22:20:51 +00001808
John McCall6538c932009-10-10 05:48:19 +00001809 // Don't descend into implied contexts for redeclarations.
1810 // C++98 [namespace.qual]p6:
1811 // In a declaration for a namespace member in which the
1812 // declarator-id is a qualified-id, given that the qualified-id
1813 // for the namespace member has the form
1814 // nested-name-specifier unqualified-id
1815 // the unqualified-id shall name a member of the namespace
1816 // designated by the nested-name-specifier.
1817 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001818 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001819 return false;
1820
John McCall27b18f82009-11-17 02:14:36 +00001821 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001822 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001823 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001824
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001825 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001826 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001827 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001828 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001829 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001830
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001831 // If we're performing qualified name lookup into a dependent class,
1832 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001833 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001834 // template instantiation time (at which point all bases will be available)
1835 // or we have to fail.
1836 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1837 LookupRec->hasAnyDependentBases()) {
1838 R.setNotFoundInCurrentInstantiation();
1839 return false;
1840 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001841
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001842 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001843 CXXBasePaths Paths;
1844 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001845
1846 // Look for this member in our base classes
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00001847 bool (*BaseCallback)(const CXXBaseSpecifier *Specifier, CXXBasePath &Path,
1848 DeclarationName Name) = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00001849 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001850 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001851 case LookupOrdinaryName:
1852 case LookupMemberName:
1853 case LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +00001854 case LookupLocalFriendName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001855 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1856 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001857
Douglas Gregor36d1b142009-10-06 17:59:45 +00001858 case LookupTagName:
1859 BaseCallback = &CXXRecordDecl::FindTagMember;
1860 break;
John McCall84d87672009-12-10 09:41:52 +00001861
Douglas Gregor39982192010-08-15 06:18:01 +00001862 case LookupAnyName:
1863 BaseCallback = &LookupAnyMember;
1864 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001865
John McCall84d87672009-12-10 09:41:52 +00001866 case LookupUsingDeclName:
1867 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001868
Douglas Gregor36d1b142009-10-06 17:59:45 +00001869 case LookupOperatorName:
1870 case LookupNamespaceName:
1871 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001872 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001873 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001874 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001875
Douglas Gregor36d1b142009-10-06 17:59:45 +00001876 case LookupNestedNameSpecifierName:
1877 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1878 break;
1879 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001880
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00001881 DeclarationName Name = R.getLookupName();
1882 if (!LookupRec->lookupInBases(
1883 [=](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
1884 return BaseCallback(Specifier, Path, Name);
1885 },
1886 Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001887 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001888
John McCall553c0792010-01-23 00:46:32 +00001889 R.setNamingClass(LookupRec);
1890
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001891 // C++ [class.member.lookup]p2:
1892 // [...] If the resulting set of declarations are not all from
1893 // sub-objects of the same type, or the set has a nonstatic member
1894 // and includes members from distinct sub-objects, there is an
1895 // ambiguity and the program is ill-formed. Otherwise that set is
1896 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001897 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001898 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001899 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001900
Douglas Gregor36d1b142009-10-06 17:59:45 +00001901 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001902 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001903 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001904
John McCall401982f2010-01-20 21:53:11 +00001905 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1906 // across all paths.
1907 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001908
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001909 // Determine whether we're looking at a distinct sub-object or not.
1910 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001911 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001912 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1913 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001914 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001915 }
1916
Douglas Gregorc0d24902010-10-22 22:08:47 +00001917 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001918 != Context.getCanonicalType(PathElement.Base->getType())) {
1919 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001920 // different types. If the declaration sets aren't the same, this
Nikola Smiljanic1c125682014-07-09 05:42:35 +00001921 // lookup is ambiguous.
David Blaikieff7d47a2012-12-19 00:45:41 +00001922 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00001923 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikieff7d47a2012-12-19 00:45:41 +00001924 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
1925 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001926
David Blaikieff7d47a2012-12-19 00:45:41 +00001927 while (FirstD != FirstPath->Decls.end() &&
1928 CurrentD != Path->Decls.end()) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00001929 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1930 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1931 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001932
Douglas Gregorc0d24902010-10-22 22:08:47 +00001933 ++FirstD;
1934 ++CurrentD;
1935 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001936
David Blaikieff7d47a2012-12-19 00:45:41 +00001937 if (FirstD == FirstPath->Decls.end() &&
1938 CurrentD == Path->Decls.end())
Douglas Gregorc0d24902010-10-22 22:08:47 +00001939 continue;
1940 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001941
John McCall9f3059a2009-10-09 21:13:30 +00001942 R.setAmbiguousBaseSubobjectTypes(Paths);
1943 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001944 }
1945
Douglas Gregorc0d24902010-10-22 22:08:47 +00001946 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001947 // We have a different subobject of the same type.
1948
1949 // C++ [class.member.lookup]p5:
1950 // A static member, a nested type or an enumerator defined in
1951 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001952 // has more than one base class subobject of type T.
David Blaikieff7d47a2012-12-19 00:45:41 +00001953 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001954 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001955
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001956 // We have found a nonstatic member name in multiple, distinct
1957 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001958 R.setAmbiguousBaseSubobjects(Paths);
1959 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001960 }
1961 }
1962
1963 // Lookup in a base class succeeded; return these results.
1964
Aaron Ballman1e606f42014-07-15 22:03:49 +00001965 for (auto *D : Paths.front().Decls) {
John McCall553c0792010-01-23 00:46:32 +00001966 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1967 D->getAccess());
1968 R.addDecl(D, AS);
1969 }
John McCall9f3059a2009-10-09 21:13:30 +00001970 R.resolveKind();
1971 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001972}
1973
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00001974/// \brief Performs qualified name lookup or special type of lookup for
1975/// "__super::" scope specifier.
1976///
1977/// This routine is a convenience overload meant to be called from contexts
1978/// that need to perform a qualified name lookup with an optional C++ scope
1979/// specifier that might require special kind of lookup.
1980///
1981/// \param R captures both the lookup criteria and any lookup results found.
1982///
1983/// \param LookupCtx The context in which qualified name lookup will
1984/// search.
1985///
1986/// \param SS An optional C++ scope-specifier.
1987///
1988/// \returns true if lookup succeeded, false if it failed.
1989bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1990 CXXScopeSpec &SS) {
1991 auto *NNS = SS.getScopeRep();
1992 if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
1993 return LookupInSuper(R, NNS->getAsRecordDecl());
1994 else
1995
1996 return LookupQualifiedName(R, LookupCtx);
1997}
1998
Douglas Gregor34074322009-01-14 22:20:51 +00001999/// @brief Performs name lookup for a name that was parsed in the
2000/// source code, and may contain a C++ scope specifier.
2001///
2002/// This routine is a convenience routine meant to be called from
2003/// contexts that receive a name and an optional C++ scope specifier
2004/// (e.g., "N::M::x"). It will then perform either qualified or
2005/// unqualified name lookup (with LookupQualifiedName or LookupName,
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002006/// respectively) on the given name and return those results. It will
2007/// perform a special type of lookup for "__super::" scope specifier.
Douglas Gregor34074322009-01-14 22:20:51 +00002008///
2009/// @param S The scope from which unqualified name lookup will
2010/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00002011///
Douglas Gregore861bac2009-08-25 22:51:20 +00002012/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00002013///
Douglas Gregore861bac2009-08-25 22:51:20 +00002014/// @param EnteringContext Indicates whether we are going to enter the
2015/// context of the scope-specifier SS (if present).
2016///
John McCall9f3059a2009-10-09 21:13:30 +00002017/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002018bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00002019 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00002020 if (SS && SS->isInvalid()) {
2021 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002022 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00002023 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00002024 }
Mike Stump11289f42009-09-09 15:08:12 +00002025
Douglas Gregore861bac2009-08-25 22:51:20 +00002026 if (SS && SS->isSet()) {
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002027 NestedNameSpecifier *NNS = SS->getScopeRep();
2028 if (NNS->getKind() == NestedNameSpecifier::Super)
2029 return LookupInSuper(R, NNS->getAsRecordDecl());
2030
Douglas Gregore861bac2009-08-25 22:51:20 +00002031 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00002032 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00002033 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00002034 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00002035 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002036
John McCall27b18f82009-11-17 02:14:36 +00002037 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00002038 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00002039 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002040
Douglas Gregore861bac2009-08-25 22:51:20 +00002041 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00002042 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00002043 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00002044 R.setNotFoundInCurrentInstantiation();
2045 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00002046 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00002047 }
2048
Mike Stump11289f42009-09-09 15:08:12 +00002049 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00002050 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00002051}
2052
Nikola Smiljanic67860242014-09-26 00:28:20 +00002053/// \brief Perform qualified name lookup into all base classes of the given
2054/// class.
2055///
2056/// \param R captures both the lookup criteria and any lookup results found.
2057///
2058/// \param Class The context in which qualified name lookup will
2059/// search. Name lookup will search in all base classes merging the results.
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002060///
2061/// @returns True if any decls were found (but possibly ambiguous)
2062bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
Nikola Smiljanic67860242014-09-26 00:28:20 +00002063 for (const auto &BaseSpec : Class->bases()) {
2064 CXXRecordDecl *RD = cast<CXXRecordDecl>(
2065 BaseSpec.getType()->castAs<RecordType>()->getDecl());
2066 LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
2067 Result.setBaseObjectType(Context.getRecordType(Class));
2068 LookupQualifiedName(Result, RD);
2069 for (auto *Decl : Result)
2070 R.addDecl(Decl);
2071 }
2072
2073 R.resolveKind();
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00002074
2075 return !R.empty();
Nikola Smiljanic67860242014-09-26 00:28:20 +00002076}
Douglas Gregor889ceb72009-02-03 19:21:40 +00002077
James Dennett41725122012-06-22 10:16:05 +00002078/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002079/// from name lookup.
2080///
James Dennett41725122012-06-22 10:16:05 +00002081/// \param Result The result of the ambiguous lookup to be diagnosed.
Serge Pavlov99292092013-08-29 07:23:24 +00002082void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002083 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
2084
John McCall27b18f82009-11-17 02:14:36 +00002085 DeclarationName Name = Result.getLookupName();
2086 SourceLocation NameLoc = Result.getNameLoc();
2087 SourceRange LookupRange = Result.getContextRange();
2088
John McCall6538c932009-10-10 05:48:19 +00002089 switch (Result.getAmbiguityKind()) {
2090 case LookupResult::AmbiguousBaseSubobjects: {
2091 CXXBasePaths *Paths = Result.getBasePaths();
2092 QualType SubobjectType = Paths->front().back().Base->getType();
2093 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
2094 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
2095 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002096
David Blaikieff7d47a2012-12-19 00:45:41 +00002097 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6538c932009-10-10 05:48:19 +00002098 while (isa<CXXMethodDecl>(*Found) &&
2099 cast<CXXMethodDecl>(*Found)->isStatic())
2100 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002101
John McCall6538c932009-10-10 05:48:19 +00002102 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
Serge Pavlov99292092013-08-29 07:23:24 +00002103 break;
John McCall6538c932009-10-10 05:48:19 +00002104 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00002105
John McCall6538c932009-10-10 05:48:19 +00002106 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00002107 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
2108 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002109
John McCall6538c932009-10-10 05:48:19 +00002110 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002111 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00002112 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
2113 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002114 Path != PathEnd; ++Path) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002115 Decl *D = Path->Decls.front();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002116 if (DeclsPrinted.insert(D).second)
2117 Diag(D->getLocation(), diag::note_ambiguous_member_found);
2118 }
Serge Pavlov99292092013-08-29 07:23:24 +00002119 break;
Douglas Gregor1c846b02009-01-16 00:38:09 +00002120 }
2121
John McCall6538c932009-10-10 05:48:19 +00002122 case LookupResult::AmbiguousTagHiding: {
2123 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00002124
John McCall6538c932009-10-10 05:48:19 +00002125 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
2126
Aaron Ballman1e606f42014-07-15 22:03:49 +00002127 for (auto *D : Result)
2128 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
John McCall6538c932009-10-10 05:48:19 +00002129 TagDecls.insert(TD);
2130 Diag(TD->getLocation(), diag::note_hidden_tag);
2131 }
2132
Aaron Ballman1e606f42014-07-15 22:03:49 +00002133 for (auto *D : Result)
2134 if (!isa<TagDecl>(D))
2135 Diag(D->getLocation(), diag::note_hiding_object);
John McCall6538c932009-10-10 05:48:19 +00002136
2137 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00002138 LookupResult::Filter F = Result.makeFilter();
2139 while (F.hasNext()) {
2140 if (TagDecls.count(F.next()))
2141 F.erase();
2142 }
2143 F.done();
Serge Pavlov99292092013-08-29 07:23:24 +00002144 break;
John McCall6538c932009-10-10 05:48:19 +00002145 }
2146
2147 case LookupResult::AmbiguousReference: {
2148 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002149
Aaron Ballman1e606f42014-07-15 22:03:49 +00002150 for (auto *D : Result)
2151 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
Serge Pavlov99292092013-08-29 07:23:24 +00002152 break;
John McCall6538c932009-10-10 05:48:19 +00002153 }
Serge Pavlov99292092013-08-29 07:23:24 +00002154 }
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002155}
Douglas Gregore254f902009-02-04 00:32:51 +00002156
John McCallf24d7bb2010-05-28 18:45:08 +00002157namespace {
2158 struct AssociatedLookup {
John McCall7d8b0412012-08-24 20:38:34 +00002159 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallf24d7bb2010-05-28 18:45:08 +00002160 Sema::AssociatedNamespaceSet &Namespaces,
2161 Sema::AssociatedClassSet &Classes)
John McCall7d8b0412012-08-24 20:38:34 +00002162 : S(S), Namespaces(Namespaces), Classes(Classes),
2163 InstantiationLoc(InstantiationLoc) {
John McCallf24d7bb2010-05-28 18:45:08 +00002164 }
2165
2166 Sema &S;
2167 Sema::AssociatedNamespaceSet &Namespaces;
2168 Sema::AssociatedClassSet &Classes;
John McCall7d8b0412012-08-24 20:38:34 +00002169 SourceLocation InstantiationLoc;
John McCallf24d7bb2010-05-28 18:45:08 +00002170 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002171}
John McCallf24d7bb2010-05-28 18:45:08 +00002172
Mike Stump11289f42009-09-09 15:08:12 +00002173static void
John McCallf24d7bb2010-05-28 18:45:08 +00002174addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00002175
Douglas Gregor8b895222010-04-30 07:08:38 +00002176static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
2177 DeclContext *Ctx) {
2178 // Add the associated namespace for this class.
2179
2180 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
2181 // be a locally scoped record.
2182
Sebastian Redlbd595762010-08-31 20:53:31 +00002183 // We skip out of inline namespaces. The innermost non-inline namespace
2184 // contains all names of all its nested inline namespaces anyway, so we can
2185 // replace the entire inline namespace tree with its root.
2186 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
2187 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00002188 Ctx = Ctx->getParent();
2189
John McCallc7e8e792009-08-07 22:18:02 +00002190 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00002191 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00002192}
Douglas Gregor197e5f72009-07-08 07:51:57 +00002193
Mike Stump11289f42009-09-09 15:08:12 +00002194// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00002195// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00002196static void
John McCallf24d7bb2010-05-28 18:45:08 +00002197addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2198 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002199 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00002200 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00002201 switch (Arg.getKind()) {
2202 case TemplateArgument::Null:
2203 break;
Mike Stump11289f42009-09-09 15:08:12 +00002204
Douglas Gregor197e5f72009-07-08 07:51:57 +00002205 case TemplateArgument::Type:
2206 // [...] the namespaces and classes associated with the types of the
2207 // template arguments provided for template type parameters (excluding
2208 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00002209 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00002210 break;
Mike Stump11289f42009-09-09 15:08:12 +00002211
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002212 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002213 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00002214 // [...] the namespaces in which any template template arguments are
2215 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00002216 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002217 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00002218 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002219 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002220 DeclContext *Ctx = ClassTemplate->getDeclContext();
2221 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002222 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002223 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002224 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002225 }
2226 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002227 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002228
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002229 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00002230 case TemplateArgument::Integral:
2231 case TemplateArgument::Expression:
Eli Friedmanb826a002012-09-26 02:36:12 +00002232 case TemplateArgument::NullPtr:
Mike Stump11289f42009-09-09 15:08:12 +00002233 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00002234 // associated namespaces. ]
2235 break;
Mike Stump11289f42009-09-09 15:08:12 +00002236
Douglas Gregor197e5f72009-07-08 07:51:57 +00002237 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00002238 for (const auto &P : Arg.pack_elements())
2239 addAssociatedClassesAndNamespaces(Result, P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002240 break;
2241 }
2242}
2243
Douglas Gregore254f902009-02-04 00:32:51 +00002244// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00002245// argument-dependent lookup with an argument of class type
2246// (C++ [basic.lookup.koenig]p2).
2247static void
John McCallf24d7bb2010-05-28 18:45:08 +00002248addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2249 CXXRecordDecl *Class) {
2250
2251 // Just silently ignore anything whose name is __va_list_tag.
2252 if (Class->getDeclName() == Result.S.VAListTagName)
2253 return;
2254
Douglas Gregore254f902009-02-04 00:32:51 +00002255 // C++ [basic.lookup.koenig]p2:
2256 // [...]
2257 // -- If T is a class type (including unions), its associated
2258 // classes are: the class itself; the class of which it is a
2259 // member, if any; and its direct and indirect base
2260 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00002261 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00002262
2263 // Add the class of which it is a member, if any.
2264 DeclContext *Ctx = Class->getDeclContext();
2265 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002266 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002267 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002268 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002269
Douglas Gregore254f902009-02-04 00:32:51 +00002270 // Add the class itself. If we've already seen this class, we don't
2271 // need to visit base classes.
Richard Smith594461f2014-03-14 22:07:27 +00002272 //
2273 // FIXME: That's not correct, we may have added this class only because it
2274 // was the enclosing class of another class, and in that case we won't have
2275 // added its base classes yet.
David Blaikie82e95a32014-11-19 07:49:47 +00002276 if (!Result.Classes.insert(Class).second)
Douglas Gregore254f902009-02-04 00:32:51 +00002277 return;
2278
Mike Stump11289f42009-09-09 15:08:12 +00002279 // -- If T is a template-id, its associated namespaces and classes are
2280 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002281 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00002282 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00002283 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00002284 // namespaces in which any template template arguments are defined; and
2285 // the classes in which any member templates used as template template
2286 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00002287 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00002288 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00002289 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2290 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2291 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002292 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002293 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002294 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002295
Douglas Gregor197e5f72009-07-08 07:51:57 +00002296 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2297 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00002298 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002299 }
Mike Stump11289f42009-09-09 15:08:12 +00002300
John McCall67da35c2010-02-04 22:26:26 +00002301 // Only recurse into base classes for complete types.
Richard Smith594461f2014-03-14 22:07:27 +00002302 if (!Class->hasDefinition())
2303 return;
John McCall67da35c2010-02-04 22:26:26 +00002304
Douglas Gregore254f902009-02-04 00:32:51 +00002305 // Add direct and indirect base classes along with their associated
2306 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002307 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00002308 Bases.push_back(Class);
2309 while (!Bases.empty()) {
2310 // Pop this class off the stack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002311 Class = Bases.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002312
2313 // Visit the base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +00002314 for (const auto &Base : Class->bases()) {
2315 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00002316 // In dependent contexts, we do ADL twice, and the first time around,
2317 // the base type might be a dependent TemplateSpecializationType, or a
2318 // TemplateTypeParmType. If that happens, simply ignore it.
2319 // FIXME: If we want to support export, we probably need to add the
2320 // namespace of the template in a TemplateSpecializationType, or even
2321 // the classes and namespaces of known non-dependent arguments.
2322 if (!BaseType)
2323 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002324 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
David Blaikie82e95a32014-11-19 07:49:47 +00002325 if (Result.Classes.insert(BaseDecl).second) {
Douglas Gregore254f902009-02-04 00:32:51 +00002326 // Find the associated namespace for this base class.
2327 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00002328 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00002329
2330 // Make sure we visit the bases of this base class.
2331 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2332 Bases.push_back(BaseDecl);
2333 }
2334 }
2335 }
2336}
2337
2338// \brief Add the associated classes and namespaces for
2339// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00002340// (C++ [basic.lookup.koenig]p2).
2341static void
John McCallf24d7bb2010-05-28 18:45:08 +00002342addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00002343 // C++ [basic.lookup.koenig]p2:
2344 //
2345 // For each argument type T in the function call, there is a set
2346 // of zero or more associated namespaces and a set of zero or more
2347 // associated classes to be considered. The sets of namespaces and
2348 // classes is determined entirely by the types of the function
2349 // arguments (and the namespace of any template template
2350 // argument). Typedef names and using-declarations used to specify
2351 // the types do not contribute to this set. The sets of namespaces
2352 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00002353
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002354 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00002355 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2356
Douglas Gregore254f902009-02-04 00:32:51 +00002357 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00002358 switch (T->getTypeClass()) {
2359
2360#define TYPE(Class, Base)
2361#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2362#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2363#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2364#define ABSTRACT_TYPE(Class, Base)
2365#include "clang/AST/TypeNodes.def"
2366 // T is canonical. We can also ignore dependent types because
2367 // we don't need to do ADL at the definition point, but if we
2368 // wanted to implement template export (or if we find some other
2369 // use for associated classes and namespaces...) this would be
2370 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00002371 break;
Douglas Gregore254f902009-02-04 00:32:51 +00002372
John McCall0af3d3b2010-05-28 06:08:54 +00002373 // -- If T is a pointer to U or an array of U, its associated
2374 // namespaces and classes are those associated with U.
2375 case Type::Pointer:
2376 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2377 continue;
2378 case Type::ConstantArray:
2379 case Type::IncompleteArray:
2380 case Type::VariableArray:
2381 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2382 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002383
John McCall0af3d3b2010-05-28 06:08:54 +00002384 // -- If T is a fundamental type, its associated sets of
2385 // namespaces and classes are both empty.
2386 case Type::Builtin:
2387 break;
2388
2389 // -- If T is a class type (including unions), its associated
2390 // classes are: the class itself; the class of which it is a
2391 // member, if any; and its direct and indirect base
2392 // classes. Its associated namespaces are the namespaces in
2393 // which its associated classes are defined.
2394 case Type::Record: {
Richard Smith594461f2014-03-14 22:07:27 +00002395 Result.S.RequireCompleteType(Result.InstantiationLoc, QualType(T, 0),
2396 /*no diagnostic*/ 0);
John McCall0af3d3b2010-05-28 06:08:54 +00002397 CXXRecordDecl *Class
2398 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002399 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00002400 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00002401 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00002402
John McCall0af3d3b2010-05-28 06:08:54 +00002403 // -- If T is an enumeration type, its associated namespace is
2404 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002405 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00002406 // it has no associated class.
2407 case Type::Enum: {
2408 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002409
John McCall0af3d3b2010-05-28 06:08:54 +00002410 DeclContext *Ctx = Enum->getDeclContext();
2411 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002412 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002413
John McCall0af3d3b2010-05-28 06:08:54 +00002414 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002415 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00002416
John McCall0af3d3b2010-05-28 06:08:54 +00002417 break;
2418 }
2419
2420 // -- If T is a function type, its associated namespaces and
2421 // classes are those associated with the function parameter
2422 // types and those associated with the return type.
2423 case Type::FunctionProto: {
2424 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002425 for (const auto &Arg : Proto->param_types())
2426 Queue.push_back(Arg.getTypePtr());
John McCall0af3d3b2010-05-28 06:08:54 +00002427 // fallthrough
2428 }
2429 case Type::FunctionNoProto: {
2430 const FunctionType *FnType = cast<FunctionType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00002431 T = FnType->getReturnType().getTypePtr();
John McCall0af3d3b2010-05-28 06:08:54 +00002432 continue;
2433 }
2434
2435 // -- If T is a pointer to a member function of a class X, its
2436 // associated namespaces and classes are those associated
2437 // with the function parameter types and return type,
2438 // together with those associated with X.
2439 //
2440 // -- If T is a pointer to a data member of class X, its
2441 // associated namespaces and classes are those associated
2442 // with the member type together with those associated with
2443 // X.
2444 case Type::MemberPointer: {
2445 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2446
2447 // Queue up the class type into which this points.
2448 Queue.push_back(MemberPtr->getClass());
2449
2450 // And directly continue with the pointee type.
2451 T = MemberPtr->getPointeeType().getTypePtr();
2452 continue;
2453 }
2454
2455 // As an extension, treat this like a normal pointer.
2456 case Type::BlockPointer:
2457 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2458 continue;
2459
2460 // References aren't covered by the standard, but that's such an
2461 // obvious defect that we cover them anyway.
2462 case Type::LValueReference:
2463 case Type::RValueReference:
2464 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2465 continue;
2466
2467 // These are fundamental types.
2468 case Type::Vector:
2469 case Type::ExtVector:
2470 case Type::Complex:
2471 break;
2472
Richard Smith27d807c2013-04-30 13:56:41 +00002473 // Non-deduced auto types only get here for error cases.
2474 case Type::Auto:
2475 break;
2476
Douglas Gregor8e936662011-04-12 01:02:45 +00002477 // If T is an Objective-C object or interface type, or a pointer to an
2478 // object or interface type, the associated namespace is the global
2479 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002480 case Type::ObjCObject:
2481 case Type::ObjCInterface:
2482 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002483 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002484 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002485
2486 // Atomic types are just wrappers; use the associations of the
2487 // contained type.
2488 case Type::Atomic:
2489 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2490 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002491 }
2492
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002493 if (Queue.empty())
2494 break;
2495 T = Queue.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002496 }
Douglas Gregore254f902009-02-04 00:32:51 +00002497}
2498
2499/// \brief Find the associated classes and namespaces for
2500/// argument-dependent lookup for a call with the given set of
2501/// arguments.
2502///
2503/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002504/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002505/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00002506void Sema::FindAssociatedClassesAndNamespaces(
2507 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2508 AssociatedNamespaceSet &AssociatedNamespaces,
2509 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002510 AssociatedNamespaces.clear();
2511 AssociatedClasses.clear();
2512
John McCall7d8b0412012-08-24 20:38:34 +00002513 AssociatedLookup Result(*this, InstantiationLoc,
2514 AssociatedNamespaces, AssociatedClasses);
John McCallf24d7bb2010-05-28 18:45:08 +00002515
Douglas Gregore254f902009-02-04 00:32:51 +00002516 // C++ [basic.lookup.koenig]p2:
2517 // For each argument type T in the function call, there is a set
2518 // of zero or more associated namespaces and a set of zero or more
2519 // associated classes to be considered. The sets of namespaces and
2520 // classes is determined entirely by the types of the function
2521 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002522 // argument).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002523 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregore254f902009-02-04 00:32:51 +00002524 Expr *Arg = Args[ArgIdx];
2525
2526 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002527 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002528 continue;
2529 }
2530
2531 // [...] In addition, if the argument is the name or address of a
2532 // set of overloaded functions and/or function templates, its
2533 // associated classes and namespaces are the union of those
2534 // associated with each of the members of the set: the namespace
2535 // in which the function or function template is defined and the
2536 // classes and namespaces associated with its (non-dependent)
2537 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002538 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002539 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002540 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002541 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002542
John McCallf24d7bb2010-05-28 18:45:08 +00002543 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2544 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002545
Aaron Ballman1e606f42014-07-15 22:03:49 +00002546 for (const auto *D : ULE->decls()) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002547 // Look through any using declarations to find the underlying function.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002548 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
Douglas Gregore254f902009-02-04 00:32:51 +00002549
2550 // Add the classes and namespaces associated with the parameter
2551 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002552 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002553 }
2554 }
2555}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002556
John McCall5cebab12009-11-18 07:57:50 +00002557NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002558 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002559 LookupNameKind NameKind,
2560 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002561 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002562 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002563 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002564}
2565
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002566/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002567ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002568 SourceLocation IdLoc,
2569 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002570 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002571 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002572 return cast_or_null<ObjCProtocolDecl>(D);
2573}
2574
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002575void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002576 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002577 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002578 // C++ [over.match.oper]p3:
2579 // -- The set of non-member candidates is the result of the
2580 // unqualified lookup of operator@ in the context of the
2581 // expression according to the usual rules for name lookup in
2582 // unqualified function calls (3.4.2) except that all member
Richard Smith100b24a2014-04-17 01:52:14 +00002583 // functions are ignored.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002584 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002585 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2586 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002587
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002588 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
Richard Smith100b24a2014-04-17 01:52:14 +00002589 Functions.append(Operators.begin(), Operators.end());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002590}
2591
Alexis Hunt1da39282011-06-24 02:11:39 +00002592Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002593 CXXSpecialMember SM,
2594 bool ConstArg,
2595 bool VolatileArg,
2596 bool RValueThis,
2597 bool ConstThis,
2598 bool VolatileThis) {
Richard Smith7d125a12012-11-27 21:20:31 +00002599 assert(CanDeclareSpecialMemberFunction(RD) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002600 "doing special member lookup into record that isn't fully complete");
Richard Smith7d125a12012-11-27 21:20:31 +00002601 RD = RD->getDefinition();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002602 if (RValueThis || ConstThis || VolatileThis)
2603 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2604 "constructors and destructors always have unqualified lvalue this");
2605 if (ConstArg || VolatileArg)
2606 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2607 "parameter-less special members can't have qualified arguments");
2608
2609 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002610 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002611 ID.AddInteger(SM);
2612 ID.AddInteger(ConstArg);
2613 ID.AddInteger(VolatileArg);
2614 ID.AddInteger(RValueThis);
2615 ID.AddInteger(ConstThis);
2616 ID.AddInteger(VolatileThis);
2617
2618 void *InsertPoint;
2619 SpecialMemberOverloadResult *Result =
2620 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2621
2622 // This was already cached
2623 if (Result)
2624 return Result;
2625
Alexis Huntba8e18d2011-06-07 00:11:58 +00002626 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2627 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002628 SpecialMemberCache.InsertNode(Result, InsertPoint);
2629
2630 if (SM == CXXDestructor) {
Richard Smith2be35f52012-12-01 02:35:44 +00002631 if (RD->needsImplicitDestructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002632 DeclareImplicitDestructor(RD);
2633 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002634 assert(DD && "record without a destructor");
2635 Result->setMethod(DD);
Richard Smith852265f2012-03-30 20:53:28 +00002636 Result->setKind(DD->isDeleted() ?
2637 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith83c478d2012-04-20 18:46:14 +00002638 SpecialMemberOverloadResult::Success);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002639 return Result;
2640 }
2641
Alexis Hunteef8ee02011-06-10 03:50:41 +00002642 // Prepare for overload resolution. Here we construct a synthetic argument
2643 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002644 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002645 DeclarationName Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002646 Expr *Arg = nullptr;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002647 unsigned NumArgs;
2648
Richard Smith83c478d2012-04-20 18:46:14 +00002649 QualType ArgType = CanTy;
2650 ExprValueKind VK = VK_LValue;
2651
Alexis Hunteef8ee02011-06-10 03:50:41 +00002652 if (SM == CXXDefaultConstructor) {
2653 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2654 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002655 if (RD->needsImplicitDefaultConstructor())
2656 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002657 } else {
2658 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2659 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smith2be35f52012-12-01 02:35:44 +00002660 if (RD->needsImplicitCopyConstructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002661 DeclareImplicitCopyConstructor(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002662 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002663 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002664 } else {
2665 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smith2be35f52012-12-01 02:35:44 +00002666 if (RD->needsImplicitCopyAssignment())
Alexis Hunt1da39282011-06-24 02:11:39 +00002667 DeclareImplicitCopyAssignment(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002668 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002669 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002670 }
2671
Alexis Hunteef8ee02011-06-10 03:50:41 +00002672 if (ConstArg)
2673 ArgType.addConst();
2674 if (VolatileArg)
2675 ArgType.addVolatile();
2676
2677 // This isn't /really/ specified by the standard, but it's implied
2678 // we should be working from an RValue in the case of move to ensure
2679 // that we prefer to bind to rvalue references, and an LValue in the
2680 // case of copy to ensure we don't bind to rvalue references.
2681 // Possibly an XValue is actually correct in the case of move, but
2682 // there is no semantic difference for class types in this restricted
2683 // case.
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002684 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002685 VK = VK_LValue;
2686 else
2687 VK = VK_RValue;
Richard Smith83c478d2012-04-20 18:46:14 +00002688 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00002689
Richard Smith83c478d2012-04-20 18:46:14 +00002690 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2691
2692 if (SM != CXXDefaultConstructor) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002693 NumArgs = 1;
Richard Smith83c478d2012-04-20 18:46:14 +00002694 Arg = &FakeArg;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002695 }
2696
2697 // Create the object argument
2698 QualType ThisTy = CanTy;
2699 if (ConstThis)
2700 ThisTy.addConst();
2701 if (VolatileThis)
2702 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002703 Expr::Classification Classification =
Richard Smith83c478d2012-04-20 18:46:14 +00002704 OpaqueValueExpr(SourceLocation(), ThisTy,
2705 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002706
2707 // Now we perform lookup on the name we computed earlier and do overload
2708 // resolution. Lookup is only performed directly into the class since there
2709 // will always be a (possibly implicit) declaration to shadow any others.
Richard Smith100b24a2014-04-17 01:52:14 +00002710 OverloadCandidateSet OCS(RD->getLocation(), OverloadCandidateSet::CSK_Normal);
David Blaikieff7d47a2012-12-19 00:45:41 +00002711 DeclContext::lookup_result R = RD->lookup(Name);
Richard Smith8c37ab52015-02-11 01:48:47 +00002712
2713 if (R.empty()) {
2714 // We might have no default constructor because we have a lambda's closure
2715 // type, rather than because there's some other declared constructor.
2716 // Every class has a copy/move constructor, copy/move assignment, and
2717 // destructor.
2718 assert(SM == CXXDefaultConstructor &&
2719 "lookup for a constructor or assignment operator was empty");
2720 Result->setMethod(nullptr);
2721 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
2722 return Result;
2723 }
Chandler Carruth7deaae72013-08-18 07:20:52 +00002724
2725 // Copy the candidates as our processing of them may load new declarations
2726 // from an external source and invalidate lookup_result.
2727 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2728
Aaron Ballman1e606f42014-07-15 22:03:49 +00002729 for (auto *Cand : Candidates) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002730 if (Cand->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002731 continue;
2732
Alexis Hunt1da39282011-06-24 02:11:39 +00002733 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2734 // FIXME: [namespace.udecl]p15 says that we should only consider a
2735 // using declaration here if it does not match a declaration in the
2736 // derived class. We do not implement this correctly in other cases
2737 // either.
2738 Cand = U->getTargetDecl();
2739
2740 if (Cand->isInvalidDecl())
2741 continue;
2742 }
2743
2744 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002745 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Alexis Hunt1da39282011-06-24 02:11:39 +00002746 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002747 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2748 OCS, true);
Alexis Hunt080709f2011-06-23 00:26:20 +00002749 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002750 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2751 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt2949f022011-06-22 02:58:46 +00002752 } else if (FunctionTemplateDecl *Tmpl =
Alexis Hunt1da39282011-06-24 02:11:39 +00002753 dyn_cast<FunctionTemplateDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002754 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2755 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Craig Topperc3ec1492014-05-26 06:22:03 +00002756 RD, nullptr, ThisTy, Classification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002757 llvm::makeArrayRef(&Arg, NumArgs),
Alexis Hunt080709f2011-06-23 00:26:20 +00002758 OCS, true);
2759 else
2760 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Craig Topperc3ec1492014-05-26 06:22:03 +00002761 nullptr, llvm::makeArrayRef(&Arg, NumArgs),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002762 OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002763 } else {
2764 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002765 }
2766 }
2767
2768 OverloadCandidateSet::iterator Best;
2769 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2770 case OR_Success:
2771 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith83c478d2012-04-20 18:46:14 +00002772 Result->setKind(SpecialMemberOverloadResult::Success);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002773 break;
2774
2775 case OR_Deleted:
2776 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith852265f2012-03-30 20:53:28 +00002777 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002778 break;
2779
2780 case OR_Ambiguous:
Craig Topperc3ec1492014-05-26 06:22:03 +00002781 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00002782 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2783 break;
2784
Alexis Hunteef8ee02011-06-10 03:50:41 +00002785 case OR_No_Viable_Function:
Craig Topperc3ec1492014-05-26 06:22:03 +00002786 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00002787 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002788 break;
2789 }
2790
2791 return Result;
2792}
2793
2794/// \brief Look up the default constructor for the given class.
2795CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002796 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002797 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2798 false, false);
2799
2800 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002801}
2802
Alexis Hunt491ec602011-06-21 23:42:56 +00002803/// \brief Look up the copying constructor for the given class.
2804CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith83c478d2012-04-20 18:46:14 +00002805 unsigned Quals) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002806 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2807 "non-const, non-volatile qualifiers for copy ctor arg");
2808 SpecialMemberOverloadResult *Result =
2809 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2810 Quals & Qualifiers::Volatile, false, false, false);
2811
Alexis Hunt899bd442011-06-10 04:44:37 +00002812 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2813}
2814
Sebastian Redl22653ba2011-08-30 19:58:05 +00002815/// \brief Look up the moving constructor for the given class.
Richard Smith1c6461e2012-07-18 03:36:00 +00002816CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2817 unsigned Quals) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002818 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002819 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2820 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002821
2822 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2823}
2824
Douglas Gregor52b72822010-07-02 23:12:18 +00002825/// \brief Look up the constructors for the given class.
2826DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002827 // If the implicit constructors have not yet been declared, do so now.
Richard Smith7d125a12012-11-27 21:20:31 +00002828 if (CanDeclareSpecialMemberFunction(Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00002829 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002830 DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +00002831 if (Class->needsImplicitCopyConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002832 DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002833 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002834 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00002835 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002836
Douglas Gregor52b72822010-07-02 23:12:18 +00002837 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2838 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2839 return Class->lookup(Name);
2840}
2841
Alexis Hunt491ec602011-06-21 23:42:56 +00002842/// \brief Look up the copying assignment operator for the given class.
2843CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2844 unsigned Quals, bool RValueThis,
Richard Smith83c478d2012-04-20 18:46:14 +00002845 unsigned ThisQuals) {
Alexis Hunt491ec602011-06-21 23:42:56 +00002846 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2847 "non-const, non-volatile qualifiers for copy assignment arg");
2848 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2849 "non-const, non-volatile qualifiers for copy assignment this");
2850 SpecialMemberOverloadResult *Result =
2851 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2852 Quals & Qualifiers::Volatile, RValueThis,
2853 ThisQuals & Qualifiers::Const,
2854 ThisQuals & Qualifiers::Volatile);
2855
Alexis Hunt491ec602011-06-21 23:42:56 +00002856 return Result->getMethod();
2857}
2858
Sebastian Redl22653ba2011-08-30 19:58:05 +00002859/// \brief Look up the moving assignment operator for the given class.
2860CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith1c6461e2012-07-18 03:36:00 +00002861 unsigned Quals,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002862 bool RValueThis,
2863 unsigned ThisQuals) {
2864 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2865 "non-const, non-volatile qualifiers for copy assignment this");
2866 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002867 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2868 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002869 ThisQuals & Qualifiers::Const,
2870 ThisQuals & Qualifiers::Volatile);
2871
2872 return Result->getMethod();
2873}
2874
Douglas Gregore71edda2010-07-01 22:47:18 +00002875/// \brief Look for the destructor of the given class.
2876///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00002877/// During semantic analysis, this routine should be used in lieu of
2878/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00002879///
2880/// \returns The destructor for this class.
2881CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002882 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2883 false, false, false,
2884 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00002885}
2886
Richard Smithbcc22fc2012-03-09 08:00:36 +00002887/// LookupLiteralOperator - Determine which literal operator should be used for
2888/// a user-defined literal, per C++11 [lex.ext].
2889///
2890/// Normal overload resolution is not used to select which literal operator to
2891/// call for a user-defined literal. Look up the provided literal operator name,
2892/// and filter the results to the appropriate set for the given argument types.
2893Sema::LiteralOperatorLookupResult
2894Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2895 ArrayRef<QualType> ArgTys,
Richard Smithb8b41d32013-10-07 19:57:58 +00002896 bool AllowRaw, bool AllowTemplate,
2897 bool AllowStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002898 LookupName(R, S);
2899 assert(R.getResultKind() != LookupResult::Ambiguous &&
2900 "literal operator lookup can't be ambiguous");
2901
2902 // Filter the lookup results appropriately.
2903 LookupResult::Filter F = R.makeFilter();
2904
Richard Smithbcc22fc2012-03-09 08:00:36 +00002905 bool FoundRaw = false;
Richard Smithb8b41d32013-10-07 19:57:58 +00002906 bool FoundTemplate = false;
2907 bool FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002908 bool FoundExactMatch = false;
2909
2910 while (F.hasNext()) {
2911 Decl *D = F.next();
2912 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2913 D = USD->getTargetDecl();
2914
Douglas Gregorc1970572013-04-10 05:18:00 +00002915 // If the declaration we found is invalid, skip it.
2916 if (D->isInvalidDecl()) {
2917 F.erase();
2918 continue;
2919 }
2920
Richard Smithb8b41d32013-10-07 19:57:58 +00002921 bool IsRaw = false;
2922 bool IsTemplate = false;
2923 bool IsStringTemplate = false;
2924 bool IsExactMatch = false;
2925
Richard Smithbcc22fc2012-03-09 08:00:36 +00002926 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2927 if (FD->getNumParams() == 1 &&
2928 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2929 IsRaw = true;
Richard Smith550de452013-01-15 07:12:59 +00002930 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002931 IsExactMatch = true;
2932 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2933 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2934 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2935 IsExactMatch = false;
2936 break;
2937 }
2938 }
2939 }
2940 }
Richard Smithb8b41d32013-10-07 19:57:58 +00002941 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
2942 TemplateParameterList *Params = FD->getTemplateParameters();
2943 if (Params->size() == 1)
2944 IsTemplate = true;
2945 else
2946 IsStringTemplate = true;
2947 }
Richard Smithbcc22fc2012-03-09 08:00:36 +00002948
2949 if (IsExactMatch) {
2950 FoundExactMatch = true;
Richard Smithb8b41d32013-10-07 19:57:58 +00002951 AllowRaw = false;
2952 AllowTemplate = false;
2953 AllowStringTemplate = false;
2954 if (FoundRaw || FoundTemplate || FoundStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002955 // Go through again and remove the raw and template decls we've
2956 // already found.
2957 F.restart();
Richard Smithb8b41d32013-10-07 19:57:58 +00002958 FoundRaw = FoundTemplate = FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002959 }
Richard Smithb8b41d32013-10-07 19:57:58 +00002960 } else if (AllowRaw && IsRaw) {
2961 FoundRaw = true;
2962 } else if (AllowTemplate && IsTemplate) {
2963 FoundTemplate = true;
2964 } else if (AllowStringTemplate && IsStringTemplate) {
2965 FoundStringTemplate = true;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002966 } else {
2967 F.erase();
2968 }
2969 }
2970
2971 F.done();
2972
2973 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2974 // parameter type, that is used in preference to a raw literal operator
2975 // or literal operator template.
2976 if (FoundExactMatch)
2977 return LOLR_Cooked;
2978
2979 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2980 // operator template, but not both.
2981 if (FoundRaw && FoundTemplate) {
2982 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
Alp Tokera2794f92014-01-22 07:29:52 +00002983 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2984 NoteOverloadCandidate((*I)->getUnderlyingDecl()->getAsFunction());
Richard Smithbcc22fc2012-03-09 08:00:36 +00002985 return LOLR_Error;
2986 }
2987
2988 if (FoundRaw)
2989 return LOLR_Raw;
2990
2991 if (FoundTemplate)
2992 return LOLR_Template;
2993
Richard Smithb8b41d32013-10-07 19:57:58 +00002994 if (FoundStringTemplate)
2995 return LOLR_StringTemplate;
2996
Richard Smithbcc22fc2012-03-09 08:00:36 +00002997 // Didn't find anything we could use.
2998 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2999 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
Richard Smithb8b41d32013-10-07 19:57:58 +00003000 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
3001 << (AllowTemplate || AllowStringTemplate);
Richard Smithbcc22fc2012-03-09 08:00:36 +00003002 return LOLR_Error;
3003}
3004
John McCall8fe68082010-01-26 07:16:45 +00003005void ADLResult::insert(NamedDecl *New) {
3006 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
3007
3008 // If we haven't yet seen a decl for this key, or the last decl
3009 // was exactly this one, we're done.
Craig Topperc3ec1492014-05-26 06:22:03 +00003010 if (Old == nullptr || Old == New) {
John McCall8fe68082010-01-26 07:16:45 +00003011 Old = New;
3012 return;
3013 }
3014
3015 // Otherwise, decide which is a more recent redeclaration.
Alp Tokera2794f92014-01-22 07:29:52 +00003016 FunctionDecl *OldFD = Old->getAsFunction();
3017 FunctionDecl *NewFD = New->getAsFunction();
John McCall8fe68082010-01-26 07:16:45 +00003018
3019 FunctionDecl *Cursor = NewFD;
3020 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00003021 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00003022
3023 // If we got to the end without finding OldFD, OldFD is the newer
3024 // declaration; leave things as they are.
3025 if (!Cursor) return;
3026
3027 // If we do find OldFD, then NewFD is newer.
3028 if (Cursor == OldFD) break;
3029
3030 // Otherwise, keep looking.
3031 }
3032
3033 Old = New;
3034}
3035
Richard Smith100b24a2014-04-17 01:52:14 +00003036void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3037 ArrayRef<Expr *> Args, ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003038 // Find all of the associated namespaces and classes based on the
3039 // arguments we have.
3040 AssociatedNamespaceSet AssociatedNamespaces;
3041 AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00003042 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCallc7e8e792009-08-07 22:18:02 +00003043 AssociatedNamespaces,
3044 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003045
3046 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003047 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3048 // and let Y be the lookup set produced by argument dependent
3049 // lookup (defined as follows). If X contains [...] then Y is
3050 // empty. Otherwise Y is the set of declarations found in the
3051 // namespaces associated with the argument types as described
3052 // below. The set of declarations found by the lookup of the name
3053 // is the union of X and Y.
3054 //
3055 // Here, we compute Y and add its members to the overloaded
3056 // candidate set.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003057 for (auto *NS : AssociatedNamespaces) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003058 // When considering an associated namespace, the lookup is the
3059 // same as the lookup performed when the associated namespace is
3060 // used as a qualifier (3.4.3.2) except that:
3061 //
3062 // -- Any using-directives in the associated namespace are
3063 // ignored.
3064 //
John McCallc7e8e792009-08-07 22:18:02 +00003065 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003066 // associated classes are visible within their respective
3067 // namespaces even if they are not visible during an ordinary
3068 // lookup (11.4).
Aaron Ballman1e606f42014-07-15 22:03:49 +00003069 DeclContext::lookup_result R = NS->lookup(Name);
3070 for (auto *D : R) {
John McCallaa74a0c2009-08-28 07:59:38 +00003071 // If the only declaration here is an ordinary friend, consider
3072 // it only if it was declared in an associated classes.
Richard Smith541b38b2013-09-20 01:15:31 +00003073 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) {
3074 // If it's neither ordinarily visible nor a friend, we can't find it.
3075 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0)
3076 continue;
3077
Richard Smith64017682013-07-17 23:53:16 +00003078 bool DeclaredInAssociatedClass = false;
3079 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
3080 DeclContext *LexDC = DI->getLexicalDeclContext();
3081 if (isa<CXXRecordDecl>(LexDC) &&
3082 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) {
3083 DeclaredInAssociatedClass = true;
3084 break;
3085 }
3086 }
3087 if (!DeclaredInAssociatedClass)
John McCalld1e9d832009-08-11 06:59:38 +00003088 continue;
3089 }
Mike Stump11289f42009-09-09 15:08:12 +00003090
John McCall91f61fc2010-01-26 06:04:06 +00003091 if (isa<UsingShadowDecl>(D))
3092 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00003093
Richard Smith100b24a2014-04-17 01:52:14 +00003094 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D))
John McCall8fe68082010-01-26 07:16:45 +00003095 continue;
3096
Richard Smitha1431072015-06-12 01:32:13 +00003097 if (!isVisible(D) && !(D = findAcceptableDecl(*this, D)))
3098 continue;
3099
John McCall8fe68082010-01-26 07:16:45 +00003100 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00003101 }
3102 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003103}
Douglas Gregor2d435302009-12-30 17:04:44 +00003104
3105//----------------------------------------------------------------------------
3106// Search for all visible declarations.
3107//----------------------------------------------------------------------------
3108VisibleDeclConsumer::~VisibleDeclConsumer() { }
3109
Richard Smithe156254d2013-08-20 20:35:18 +00003110bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
3111
Douglas Gregor2d435302009-12-30 17:04:44 +00003112namespace {
3113
3114class ShadowContextRAII;
3115
3116class VisibleDeclsRecord {
3117public:
3118 /// \brief An entry in the shadow map, which is optimized to store a
3119 /// single declaration (the common case) but can also store a list
3120 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00003121 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00003122
3123private:
3124 /// \brief A mapping from declaration names to the declarations that have
3125 /// this name within a particular scope.
3126 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
3127
3128 /// \brief A list of shadow maps, which is used to model name hiding.
3129 std::list<ShadowMap> ShadowMaps;
3130
3131 /// \brief The declaration contexts we have already visited.
3132 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
3133
3134 friend class ShadowContextRAII;
3135
3136public:
3137 /// \brief Determine whether we have already visited this context
3138 /// (and, if not, note that we are going to visit that context now).
3139 bool visitedContext(DeclContext *Ctx) {
David Blaikie82e95a32014-11-19 07:49:47 +00003140 return !VisitedContexts.insert(Ctx).second;
Douglas Gregor2d435302009-12-30 17:04:44 +00003141 }
3142
Douglas Gregor39982192010-08-15 06:18:01 +00003143 bool alreadyVisitedContext(DeclContext *Ctx) {
3144 return VisitedContexts.count(Ctx);
3145 }
3146
Douglas Gregor2d435302009-12-30 17:04:44 +00003147 /// \brief Determine whether the given declaration is hidden in the
3148 /// current scope.
3149 ///
3150 /// \returns the declaration that hides the given declaration, or
3151 /// NULL if no such declaration exists.
3152 NamedDecl *checkHidden(NamedDecl *ND);
3153
3154 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00003155 void add(NamedDecl *ND) {
3156 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
3157 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003158};
3159
3160/// \brief RAII object that records when we've entered a shadow context.
3161class ShadowContextRAII {
3162 VisibleDeclsRecord &Visible;
3163
3164 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
3165
3166public:
3167 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
Benjamin Kramer3204b152015-05-29 19:42:19 +00003168 Visible.ShadowMaps.emplace_back();
Douglas Gregor2d435302009-12-30 17:04:44 +00003169 }
3170
3171 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00003172 Visible.ShadowMaps.pop_back();
3173 }
3174};
3175
3176} // end anonymous namespace
3177
Douglas Gregor2d435302009-12-30 17:04:44 +00003178NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00003179 // Look through using declarations.
3180 ND = ND->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003181
Douglas Gregor2d435302009-12-30 17:04:44 +00003182 unsigned IDNS = ND->getIdentifierNamespace();
3183 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
3184 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3185 SM != SMEnd; ++SM) {
3186 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
3187 if (Pos == SM->end())
3188 continue;
3189
Aaron Ballman1e606f42014-07-15 22:03:49 +00003190 for (auto *D : Pos->second) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003191 // A tag declaration does not hide a non-tag declaration.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003192 if (D->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003193 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00003194 Decl::IDNS_ObjCProtocol)))
3195 continue;
3196
3197 // Protocols are in distinct namespaces from everything else.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003198 if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor2d435302009-12-30 17:04:44 +00003199 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Aaron Ballman1e606f42014-07-15 22:03:49 +00003200 D->getIdentifierNamespace() != IDNS)
Douglas Gregor2d435302009-12-30 17:04:44 +00003201 continue;
3202
Douglas Gregor09bbc652010-01-14 15:47:35 +00003203 // Functions and function templates in the same scope overload
3204 // rather than hide. FIXME: Look for hiding based on function
3205 // signatures!
Aaron Ballman1e606f42014-07-15 22:03:49 +00003206 if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Alp Tokera2794f92014-01-22 07:29:52 +00003207 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00003208 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00003209 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003210
Douglas Gregor2d435302009-12-30 17:04:44 +00003211 // We've found a declaration that hides this one.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003212 return D;
Douglas Gregor2d435302009-12-30 17:04:44 +00003213 }
3214 }
3215
Craig Topperc3ec1492014-05-26 06:22:03 +00003216 return nullptr;
Douglas Gregor2d435302009-12-30 17:04:44 +00003217}
3218
3219static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
3220 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003221 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00003222 VisibleDeclConsumer &Consumer,
3223 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00003224 if (!Ctx)
3225 return;
3226
Douglas Gregor2d435302009-12-30 17:04:44 +00003227 // Make sure we don't visit the same context twice.
3228 if (Visited.visitedContext(Ctx->getPrimaryContext()))
3229 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003230
Richard Smith9e2341d2015-03-23 03:25:59 +00003231 // Outside C++, lookup results for the TU live on identifiers.
3232 if (isa<TranslationUnitDecl>(Ctx) &&
3233 !Result.getSema().getLangOpts().CPlusPlus) {
3234 auto &S = Result.getSema();
3235 auto &Idents = S.Context.Idents;
3236
3237 // Ensure all external identifiers are in the identifier table.
3238 if (IdentifierInfoLookup *External = Idents.getExternalIdentifierLookup()) {
3239 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
3240 for (StringRef Name = Iter->Next(); !Name.empty(); Name = Iter->Next())
3241 Idents.get(Name);
3242 }
3243
3244 // Walk all lookup results in the TU for each identifier.
3245 for (const auto &Ident : Idents) {
3246 for (auto I = S.IdResolver.begin(Ident.getValue()),
3247 E = S.IdResolver.end();
3248 I != E; ++I) {
3249 if (S.IdResolver.isDeclInScope(*I, Ctx)) {
3250 if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
3251 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3252 Visited.add(ND);
3253 }
3254 }
3255 }
3256 }
3257
3258 return;
3259 }
3260
Douglas Gregor7454c562010-07-02 20:37:36 +00003261 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3262 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3263
Douglas Gregor2d435302009-12-30 17:04:44 +00003264 // Enumerate all of the results in this context.
Richard Trieu20abd6b2015-04-15 03:48:48 +00003265 for (DeclContextLookupResult R : Ctx->lookups()) {
Richard Smith9e2341d2015-03-23 03:25:59 +00003266 for (auto *D : R) {
3267 if (auto *ND = Result.getAcceptableDecl(D)) {
3268 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3269 Visited.add(ND);
Douglas Gregora3b23b02010-12-09 21:44:02 +00003270 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003271 }
3272 }
3273
3274 // Traverse using directives for qualified name lookup.
3275 if (QualifiedNameLookup) {
3276 ShadowContextRAII Shadow(Visited);
Aaron Ballman804a7fb2014-03-17 17:14:12 +00003277 for (auto I : Ctx->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00003278 LookupVisibleDecls(I->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003279 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003280 }
3281 }
3282
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003283 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00003284 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00003285 if (!Record->hasDefinition())
3286 return;
3287
Aaron Ballman574705e2014-03-13 15:41:46 +00003288 for (const auto &B : Record->bases()) {
3289 QualType BaseType = B.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003290
Douglas Gregor2d435302009-12-30 17:04:44 +00003291 // Don't look into dependent bases, because name lookup can't look
3292 // there anyway.
3293 if (BaseType->isDependentType())
3294 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003295
Douglas Gregor2d435302009-12-30 17:04:44 +00003296 const RecordType *Record = BaseType->getAs<RecordType>();
3297 if (!Record)
3298 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003299
Douglas Gregor2d435302009-12-30 17:04:44 +00003300 // FIXME: It would be nice to be able to determine whether referencing
3301 // a particular member would be ambiguous. For example, given
3302 //
3303 // struct A { int member; };
3304 // struct B { int member; };
3305 // struct C : A, B { };
3306 //
3307 // void f(C *c) { c->### }
3308 //
3309 // accessing 'member' would result in an ambiguity. However, we
3310 // could be smart enough to qualify the member with the base
3311 // class, e.g.,
3312 //
3313 // c->B::member
3314 //
3315 // or
3316 //
3317 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003318
Douglas Gregor2d435302009-12-30 17:04:44 +00003319 // Find results in this base class (and its bases).
3320 ShadowContextRAII Shadow(Visited);
3321 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003322 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003323 }
3324 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003325
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003326 // Traverse the contexts of Objective-C classes.
3327 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3328 // Traverse categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003329 for (auto *Cat : IFace->visible_categories()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003330 ShadowContextRAII Shadow(Visited);
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003331 LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003332 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003333 }
3334
3335 // Traverse protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003336 for (auto *I : IFace->all_referenced_protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003337 ShadowContextRAII Shadow(Visited);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003338 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003339 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003340 }
3341
3342 // Traverse the superclass.
3343 if (IFace->getSuperClass()) {
3344 ShadowContextRAII Shadow(Visited);
3345 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003346 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003347 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003348
Douglas Gregor0b59e802010-04-19 18:02:19 +00003349 // If there is an implementation, traverse it. We do this to find
3350 // synthesized ivars.
3351 if (IFace->getImplementation()) {
3352 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003353 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky13668f22012-04-03 20:26:45 +00003354 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor0b59e802010-04-19 18:02:19 +00003355 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003356 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003357 for (auto *I : Protocol->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003358 ShadowContextRAII Shadow(Visited);
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003359 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003360 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003361 }
3362 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003363 for (auto *I : Category->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003364 ShadowContextRAII Shadow(Visited);
Aaron Ballman19a41762014-03-14 12:55:57 +00003365 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003366 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003367 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003368
Douglas Gregor0b59e802010-04-19 18:02:19 +00003369 // If there is an implementation, traverse it.
3370 if (Category->getImplementation()) {
3371 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003372 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00003373 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003374 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003375 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003376}
3377
3378static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3379 UnqualUsingDirectiveSet &UDirs,
3380 VisibleDeclConsumer &Consumer,
3381 VisibleDeclsRecord &Visited) {
3382 if (!S)
3383 return;
3384
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003385 if (!S->getEntity() ||
3386 (!S->getParent() &&
Ted Kremenekc37877d2013-10-08 17:08:03 +00003387 !Visited.alreadyVisitedContext(S->getEntity())) ||
3388 (S->getEntity())->isFunctionOrMethod()) {
Richard Smith541b38b2013-09-20 01:15:31 +00003389 FindLocalExternScope FindLocals(Result);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003390 // Walk through the declarations in this Scope.
Aaron Ballman35c54952014-03-17 16:55:25 +00003391 for (auto *D : S->decls()) {
3392 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Douglas Gregor4a814562011-12-14 16:03:29 +00003393 if ((ND = Result.getAcceptableDecl(ND))) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003394 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003395 Visited.add(ND);
3396 }
3397 }
3398 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003399
Douglas Gregor66230062010-03-15 14:33:29 +00003400 // FIXME: C++ [temp.local]p8
Craig Topperc3ec1492014-05-26 06:22:03 +00003401 DeclContext *Entity = nullptr;
Douglas Gregor4f248632010-01-01 17:44:25 +00003402 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003403 // Look into this scope's declaration context, along with any of its
3404 // parent lookup contexts (e.g., enclosing classes), up to the point
3405 // where we hit the context stored in the next outer scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00003406 Entity = S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00003407 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003408
Douglas Gregorea166062010-03-15 15:26:48 +00003409 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00003410 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003411 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3412 if (Method->isInstanceMethod()) {
3413 // For instance methods, look for ivars in the method's interface.
3414 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3415 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003416 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003417 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Richard Smithe156254d2013-08-20 20:35:18 +00003418 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003419 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003420 }
3421
3422 // We've already performed all of the name lookup that we need
3423 // to for Objective-C methods; the next context will be the
3424 // outer scope.
3425 break;
3426 }
3427
Douglas Gregor2d435302009-12-30 17:04:44 +00003428 if (Ctx->isFunctionOrMethod())
3429 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003430
3431 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003432 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003433 }
3434 } else if (!S->getParent()) {
3435 // Look into the translation unit scope. We walk through the translation
3436 // unit's declaration context, because the Scope itself won't have all of
3437 // the declarations if we loaded a precompiled header.
3438 // FIXME: We would like the translation unit's Scope object to point to the
3439 // translation unit, so we don't need this special "if" branch. However,
3440 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003441 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00003442 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003443 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00003444 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003445 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003446 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003447 }
3448
Douglas Gregor2d435302009-12-30 17:04:44 +00003449 if (Entity) {
3450 // Lookup visible declarations in any namespaces found by using
3451 // directives.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003452 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
3453 LookupVisibleDecls(const_cast<DeclContext *>(UUE.getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003454 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003455 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003456 }
3457
3458 // Lookup names in the parent scope.
3459 ShadowContextRAII Shadow(Visited);
3460 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3461}
3462
3463void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003464 VisibleDeclConsumer &Consumer,
3465 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003466 // Determine the set of using directives available during
3467 // unqualified name lookup.
3468 Scope *Initial = S;
3469 UnqualUsingDirectiveSet UDirs;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003470 if (getLangOpts().CPlusPlus) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003471 // Find the first namespace or translation-unit scope.
3472 while (S && !isNamespaceOrTranslationUnitScope(S))
3473 S = S->getParent();
3474
3475 UDirs.visitScopeChain(Initial, S);
3476 }
3477 UDirs.done();
3478
3479 // Look for visible declarations.
3480 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003481 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003482 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003483 if (!IncludeGlobalScope)
3484 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003485 ShadowContextRAII Shadow(Visited);
3486 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3487}
3488
3489void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003490 VisibleDeclConsumer &Consumer,
3491 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003492 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003493 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003494 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003495 if (!IncludeGlobalScope)
3496 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003497 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003498 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003499 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003500}
3501
Chris Lattner43e7f312011-02-18 02:08:43 +00003502/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003503/// If GnuLabelLoc is a valid source location, then this is a definition
3504/// of an __label__ label name, otherwise it is a normal label definition
3505/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003506LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003507 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003508 // Do a lookup to see if we have a label with this name already.
Craig Topperc3ec1492014-05-26 06:22:03 +00003509 NamedDecl *Res = nullptr;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003510
3511 if (GnuLabelLoc.isValid()) {
3512 // Local label definitions always shadow existing labels.
3513 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3514 Scope *S = CurScope;
3515 PushOnScopeChains(Res, S, true);
3516 return cast<LabelDecl>(Res);
3517 }
3518
3519 // Not a GNU local label.
3520 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3521 // If we found a label, check to see if it is in the same context as us.
3522 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003523 if (Res && Res->getDeclContext() != CurContext)
Craig Topperc3ec1492014-05-26 06:22:03 +00003524 Res = nullptr;
3525 if (!Res) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003526 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003527 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3528 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003529 assert(S && "Not in a function?");
3530 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003531 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003532 return cast<LabelDecl>(Res);
3533}
3534
3535//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003536// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003537//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003538
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003539static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3540 TypoCorrection &Candidate) {
3541 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3542 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3543}
3544
3545static void LookupPotentialTypoResult(Sema &SemaRef,
3546 LookupResult &Res,
3547 IdentifierInfo *Name,
3548 Scope *S, CXXScopeSpec *SS,
3549 DeclContext *MemberContext,
3550 bool EnteringContext,
3551 bool isObjCIvarLookup,
3552 bool FindHidden);
3553
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003554/// \brief Check whether the declarations found for a typo correction are
3555/// visible, and if none of them are, convert the correction to an 'import
3556/// a module' correction.
3557static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
3558 if (TC.begin() == TC.end())
3559 return;
3560
3561 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3562
3563 for (/**/; DI != DE; ++DI)
3564 if (!LookupResult::isVisible(SemaRef, *DI))
3565 break;
3566 // Nothing to do if all decls are visible.
3567 if (DI == DE)
3568 return;
3569
3570 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3571 bool AnyVisibleDecls = !NewDecls.empty();
3572
3573 for (/**/; DI != DE; ++DI) {
3574 NamedDecl *VisibleDecl = *DI;
3575 if (!LookupResult::isVisible(SemaRef, *DI))
3576 VisibleDecl = findAcceptableDecl(SemaRef, *DI);
3577
3578 if (VisibleDecl) {
3579 if (!AnyVisibleDecls) {
3580 // Found a visible decl, discard all hidden ones.
3581 AnyVisibleDecls = true;
3582 NewDecls.clear();
3583 }
3584 NewDecls.push_back(VisibleDecl);
3585 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
3586 NewDecls.push_back(*DI);
3587 }
3588
3589 if (NewDecls.empty())
3590 TC = TypoCorrection();
3591 else {
3592 TC.setCorrectionDecls(NewDecls);
3593 TC.setRequiresImport(!AnyVisibleDecls);
3594 }
3595}
3596
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003597// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3598// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3599// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3600static void getNestedNameSpecifierIdentifiers(
3601 NestedNameSpecifier *NNS,
3602 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3603 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3604 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3605 else
3606 Identifiers.clear();
3607
3608 const IdentifierInfo *II = nullptr;
3609
3610 switch (NNS->getKind()) {
3611 case NestedNameSpecifier::Identifier:
3612 II = NNS->getAsIdentifier();
3613 break;
3614
3615 case NestedNameSpecifier::Namespace:
3616 if (NNS->getAsNamespace()->isAnonymousNamespace())
3617 return;
3618 II = NNS->getAsNamespace()->getIdentifier();
3619 break;
3620
3621 case NestedNameSpecifier::NamespaceAlias:
3622 II = NNS->getAsNamespaceAlias()->getIdentifier();
3623 break;
3624
3625 case NestedNameSpecifier::TypeSpecWithTemplate:
3626 case NestedNameSpecifier::TypeSpec:
3627 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3628 break;
3629
3630 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00003631 case NestedNameSpecifier::Super:
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003632 return;
3633 }
3634
3635 if (II)
3636 Identifiers.push_back(II);
3637}
3638
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003639void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003640 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003641 // Don't consider hidden names for typo correction.
3642 if (Hiding)
3643 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003644
Douglas Gregor2d435302009-12-30 17:04:44 +00003645 // Only consider entities with identifiers for names, ignoring
3646 // special names (constructors, overloaded operators, selectors,
3647 // etc.).
3648 IdentifierInfo *Name = ND->getIdentifier();
3649 if (!Name)
3650 return;
3651
Richard Smithe156254d2013-08-20 20:35:18 +00003652 // Only consider visible declarations and declarations from modules with
3653 // names that exactly match.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003654 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo &&
Richard Smithe156254d2013-08-20 20:35:18 +00003655 !findAcceptableDecl(SemaRef, ND))
3656 return;
3657
Douglas Gregor57756ea2010-10-14 22:11:03 +00003658 FoundName(Name->getName());
3659}
3660
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003661void TypoCorrectionConsumer::FoundName(StringRef Name) {
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003662 // Compute the edit distance between the typo and the name of this
3663 // entity, and add the identifier to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003664 addName(Name, nullptr);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003665}
3666
3667void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3668 // Compute the edit distance between the typo and this keyword,
3669 // and add the keyword to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003670 addName(Keyword, nullptr, nullptr, true);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003671}
3672
3673void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
3674 NestedNameSpecifier *NNS, bool isKeyword) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003675 // Use a simple length-based heuristic to determine the minimum possible
3676 // edit distance. If the minimum isn't good enough, bail out early.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003677 StringRef TypoStr = Typo->getName();
3678 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
3679 if (MinED && TypoStr.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00003680 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003681
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003682 // Compute an upper bound on the allowable edit distance, so that the
3683 // edit-distance algorithm can short-circuit.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003684 unsigned UpperBound = (TypoStr.size() + 2) / 3 + 1;
3685 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003686 if (ED >= UpperBound) return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003687
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003688 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003689 if (isKeyword) TC.makeKeyword();
Kaelyn Takata0a313022014-11-20 22:06:26 +00003690 TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003691 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003692}
3693
Kaelyn Takatad2287c32014-10-27 18:07:13 +00003694static const unsigned MaxTypoDistanceResultSets = 5;
3695
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003696void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003697 StringRef TypoStr = Typo->getName();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003698 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003699
3700 // For very short typos, ignore potential corrections that have a different
3701 // base identifier from the typo or which have a normalized edit distance
3702 // longer than the typo itself.
3703 if (TypoStr.size() < 3 &&
3704 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
3705 return;
3706
3707 // If the correction is resolved but is not viable, ignore it.
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003708 if (Correction.isResolved()) {
3709 checkCorrectionVisibility(SemaRef, Correction);
3710 if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
3711 return;
3712 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003713
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003714 TypoResultList &CList =
3715 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003716
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003717 if (!CList.empty() && !CList.back().isResolved())
3718 CList.pop_back();
3719 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3720 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3721 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3722 RI != RIEnd; ++RI) {
3723 // If the Correction refers to a decl already in the result list,
3724 // replace the existing result if the string representation of Correction
3725 // comes before the current result alphabetically, then stop as there is
3726 // nothing more to be done to add Correction to the candidate set.
3727 if (RI->getCorrectionDecl() == NewND) {
3728 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3729 *RI = Correction;
3730 return;
3731 }
3732 }
3733 }
3734 if (CList.empty() || Correction.isResolved())
3735 CList.push_back(Correction);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003736
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003737 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003738 CorrectionResults.erase(std::prev(CorrectionResults.end()));
3739}
3740
3741void TypoCorrectionConsumer::addNamespaces(
3742 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
3743 SearchNamespaces = true;
3744
3745 for (auto KNPair : KnownNamespaces)
3746 Namespaces.addNameSpecifier(KNPair.first);
3747
3748 bool SSIsTemplate = false;
3749 if (NestedNameSpecifier *NNS =
3750 (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
3751 if (const Type *T = NNS->getAsType())
3752 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
3753 }
3754 for (const auto *TI : SemaRef.getASTContext().types()) {
3755 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
3756 CD = CD->getCanonicalDecl();
3757 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
3758 !CD->isUnion() && CD->getIdentifier() &&
3759 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
3760 (CD->isBeingDefined() || CD->isCompleteDefinition()))
3761 Namespaces.addNameSpecifier(CD);
3762 }
3763 }
3764}
3765
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003766const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
3767 if (++CurrentTCIndex < ValidatedCorrections.size())
3768 return ValidatedCorrections[CurrentTCIndex];
3769
3770 CurrentTCIndex = ValidatedCorrections.size();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003771 while (!CorrectionResults.empty()) {
3772 auto DI = CorrectionResults.begin();
3773 if (DI->second.empty()) {
3774 CorrectionResults.erase(DI);
3775 continue;
3776 }
3777
3778 auto RI = DI->second.begin();
3779 if (RI->second.empty()) {
3780 DI->second.erase(RI);
3781 performQualifiedLookups();
3782 continue;
3783 }
3784
3785 TypoCorrection TC = RI->second.pop_back_val();
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003786 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003787 ValidatedCorrections.push_back(TC);
3788 return ValidatedCorrections[CurrentTCIndex];
3789 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003790 }
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003791 return ValidatedCorrections[0]; // The empty correction.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003792}
3793
3794bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
3795 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
3796 DeclContext *TempMemberContext = MemberContext;
Kaelyn Takata6c759512014-10-27 18:07:37 +00003797 CXXScopeSpec *TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003798retry_lookup:
3799 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
3800 EnteringContext,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00003801 CorrectionValidator->IsObjCIvarLookup,
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003802 Name == Typo && !Candidate.WillReplaceSpecifier());
3803 switch (Result.getResultKind()) {
3804 case LookupResult::NotFound:
3805 case LookupResult::NotFoundInCurrentInstantiation:
3806 case LookupResult::FoundUnresolvedValue:
3807 if (TempSS) {
3808 // Immediately retry the lookup without the given CXXScopeSpec
3809 TempSS = nullptr;
3810 Candidate.WillReplaceSpecifier(true);
3811 goto retry_lookup;
3812 }
3813 if (TempMemberContext) {
3814 if (SS && !TempSS)
Kaelyn Takata6c759512014-10-27 18:07:37 +00003815 TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003816 TempMemberContext = nullptr;
3817 goto retry_lookup;
3818 }
3819 if (SearchNamespaces)
3820 QualifiedResults.push_back(Candidate);
3821 break;
3822
3823 case LookupResult::Ambiguous:
3824 // We don't deal with ambiguities.
3825 break;
3826
3827 case LookupResult::Found:
3828 case LookupResult::FoundOverloaded:
3829 // Store all of the Decls for overloaded symbols
3830 for (auto *TRD : Result)
3831 Candidate.addCorrectionDecl(TRD);
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003832 checkCorrectionVisibility(SemaRef, Candidate);
Kaelyn Takata89c881b2014-10-27 18:07:29 +00003833 if (!isCandidateViable(*CorrectionValidator, Candidate)) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003834 if (SearchNamespaces)
3835 QualifiedResults.push_back(Candidate);
3836 break;
3837 }
Kaelyn Takata20deb1d2015-01-28 00:46:09 +00003838 Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003839 return true;
3840 }
3841 return false;
3842}
3843
3844void TypoCorrectionConsumer::performQualifiedLookups() {
3845 unsigned TypoLen = Typo->getName().size();
3846 for (auto QR : QualifiedResults) {
3847 for (auto NSI : Namespaces) {
3848 DeclContext *Ctx = NSI.DeclCtx;
3849 const Type *NSType = NSI.NameSpecifier->getAsType();
3850
3851 // If the current NestedNameSpecifier refers to a class and the
3852 // current correction candidate is the name of that class, then skip
3853 // it as it is unlikely a qualified version of the class' constructor
3854 // is an appropriate correction.
3855 if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() : 0) {
3856 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
3857 continue;
3858 }
3859
3860 TypoCorrection TC(QR);
3861 TC.ClearCorrectionDecls();
3862 TC.setCorrectionSpecifier(NSI.NameSpecifier);
3863 TC.setQualifierDistance(NSI.EditDistance);
3864 TC.setCallbackDistance(0); // Reset the callback distance
3865
3866 // If the current correction candidate and namespace combination are
3867 // too far away from the original typo based on the normalized edit
3868 // distance, then skip performing a qualified name lookup.
3869 unsigned TmpED = TC.getEditDistance(true);
3870 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
3871 TypoLen / TmpED < 3)
3872 continue;
3873
3874 Result.clear();
3875 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
3876 if (!SemaRef.LookupQualifiedName(Result, Ctx))
3877 continue;
3878
3879 // Any corrections added below will be validated in subsequent
3880 // iterations of the main while() loop over the Consumer's contents.
3881 switch (Result.getResultKind()) {
3882 case LookupResult::Found:
3883 case LookupResult::FoundOverloaded: {
3884 if (SS && SS->isValid()) {
3885 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
3886 std::string OldQualified;
3887 llvm::raw_string_ostream OldOStream(OldQualified);
3888 SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
3889 OldOStream << Typo->getName();
3890 // If correction candidate would be an identical written qualified
3891 // identifer, then the existing CXXScopeSpec probably included a
3892 // typedef that didn't get accounted for properly.
3893 if (OldOStream.str() == NewQualified)
3894 break;
3895 }
3896 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
3897 TRD != TRDEnd; ++TRD) {
3898 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
3899 NSType ? NSType->getAsCXXRecordDecl()
3900 : nullptr,
3901 TRD.getPair()) == Sema::AR_accessible)
3902 TC.addCorrectionDecl(*TRD);
3903 }
Kaelyn Takata0a313022014-11-20 22:06:26 +00003904 if (TC.isResolved()) {
3905 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003906 addCorrection(TC);
Kaelyn Takata0a313022014-11-20 22:06:26 +00003907 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003908 break;
3909 }
3910 case LookupResult::NotFound:
3911 case LookupResult::NotFoundInCurrentInstantiation:
3912 case LookupResult::Ambiguous:
3913 case LookupResult::FoundUnresolvedValue:
3914 break;
3915 }
3916 }
3917 }
3918 QualifiedResults.clear();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003919}
3920
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00003921TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
3922 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
Benjamin Kramer15537272015-03-13 16:10:42 +00003923 : Context(Context), CurContextChain(buildContextChain(CurContext)) {
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00003924 if (NestedNameSpecifier *NNS =
3925 CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
3926 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
3927 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3928
3929 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
3930 }
3931 // Build the list of identifiers that would be used for an absolute
3932 // (from the global context) NestedNameSpecifier referring to the current
3933 // context.
3934 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3935 CEnd = CurContextChain.rend();
3936 C != CEnd; ++C) {
3937 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3938 CurContextIdentifiers.push_back(ND->getIdentifier());
3939 }
3940
3941 // Add the global context as a NestedNameSpecifier
Hans Wennborg66010132014-06-11 21:24:13 +00003942 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
3943 NestedNameSpecifier::GlobalSpecifier(Context), 1};
3944 DistanceMap[1].push_back(SI);
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00003945}
3946
Kaelyn Takata7dcc0e62014-06-11 18:07:08 +00003947auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
3948 DeclContext *Start) -> DeclContextList {
Nick Lewycky0d9b3192013-04-08 21:55:21 +00003949 assert(Start && "Building a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003950 DeclContextList Chain;
Craig Topperc3ec1492014-05-26 06:22:03 +00003951 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003952 DC = DC->getLookupParent()) {
3953 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3954 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3955 !(ND && ND->isAnonymousNamespace()))
3956 Chain.push_back(DC->getPrimaryContext());
3957 }
3958 return Chain;
3959}
3960
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003961unsigned
3962TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
3963 DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003964 unsigned NumSpecifiers = 0;
3965 for (DeclContextList::reverse_iterator C = DeclChain.rbegin(),
3966 CEnd = DeclChain.rend();
3967 C != CEnd; ++C) {
3968 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) {
3969 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3970 ++NumSpecifiers;
3971 } else if (RecordDecl *RD = dyn_cast_or_null<RecordDecl>(*C)) {
3972 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
3973 RD->getTypeForDecl());
3974 ++NumSpecifiers;
3975 }
3976 }
3977 return NumSpecifiers;
3978}
3979
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003980void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
3981 DeclContext *Ctx) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003982 NestedNameSpecifier *NNS = nullptr;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003983 unsigned NumSpecifiers = 0;
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003984 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003985 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
3986
3987 // Eliminate common elements from the two DeclContext chains.
3988 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3989 CEnd = CurContextChain.rend();
3990 C != CEnd && !NamespaceDeclChain.empty() &&
3991 NamespaceDeclChain.back() == *C; ++C) {
3992 NamespaceDeclChain.pop_back();
3993 }
3994
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003995 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003996 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003997
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003998 // Add an explicit leading '::' specifier if needed.
3999 if (NamespaceDeclChain.empty()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004000 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004001 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004002 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004003 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004004 } else if (NamedDecl *ND =
4005 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004006 IdentifierInfo *Name = ND->getIdentifier();
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004007 bool SameNameSpecifier = false;
4008 if (std::find(CurNameSpecifierIdentifiers.begin(),
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004009 CurNameSpecifierIdentifiers.end(),
4010 Name) != CurNameSpecifierIdentifiers.end()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004011 std::string NewNameSpecifier;
4012 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
4013 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
4014 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4015 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4016 SpecifierOStream.flush();
4017 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004018 }
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00004019 if (SameNameSpecifier ||
4020 std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
4021 Name) != CurContextIdentifiers.end()) {
4022 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4023 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4024 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00004025 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004026 }
4027 }
4028
4029 // If the built NestedNameSpecifier would be replacing an existing
4030 // NestedNameSpecifier, use the number of component identifiers that
4031 // would need to be changed as the edit distance instead of the number
4032 // of components in the built NestedNameSpecifier.
4033 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
4034 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
4035 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4036 NumSpecifiers = llvm::ComputeEditDistance(
Craig Topper8c2a2a02014-08-30 16:55:39 +00004037 llvm::makeArrayRef(CurNameSpecifierIdentifiers),
4038 llvm::makeArrayRef(NewNameSpecifierIdentifiers));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004039 }
4040
Hans Wennborg66010132014-06-11 21:24:13 +00004041 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
4042 DistanceMap[NumSpecifiers].push_back(SI);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004043}
4044
Douglas Gregord507d772010-10-20 03:06:34 +00004045/// \brief Perform name lookup for a possible result for typo correction.
4046static void LookupPotentialTypoResult(Sema &SemaRef,
4047 LookupResult &Res,
4048 IdentifierInfo *Name,
4049 Scope *S, CXXScopeSpec *SS,
4050 DeclContext *MemberContext,
4051 bool EnteringContext,
Richard Smithe156254d2013-08-20 20:35:18 +00004052 bool isObjCIvarLookup,
4053 bool FindHidden) {
Douglas Gregord507d772010-10-20 03:06:34 +00004054 Res.suppressDiagnostics();
4055 Res.clear();
4056 Res.setLookupName(Name);
Richard Smithe156254d2013-08-20 20:35:18 +00004057 Res.setAllowHidden(FindHidden);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004058 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00004059 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004060 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00004061 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
4062 Res.addDecl(Ivar);
4063 Res.resolveKind();
4064 return;
4065 }
4066 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004067
Douglas Gregord507d772010-10-20 03:06:34 +00004068 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
4069 Res.addDecl(Prop);
4070 Res.resolveKind();
4071 return;
4072 }
4073 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004074
Douglas Gregord507d772010-10-20 03:06:34 +00004075 SemaRef.LookupQualifiedName(Res, MemberContext);
4076 return;
4077 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004078
4079 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00004080 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004081
Douglas Gregord507d772010-10-20 03:06:34 +00004082 // Fake ivar lookup; this should really be part of
4083 // LookupParsedName.
4084 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
4085 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004086 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00004087 (Res.isSingleResult() &&
4088 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004089 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00004090 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
4091 Res.addDecl(IV);
4092 Res.resolveKind();
4093 }
4094 }
4095 }
4096}
4097
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004098/// \brief Add keywords to the consumer as possible typo corrections.
4099static void AddKeywordsToConsumer(Sema &SemaRef,
4100 TypoCorrectionConsumer &Consumer,
Richard Smithb3a1df02012-06-08 21:35:42 +00004101 Scope *S, CorrectionCandidateCallback &CCC,
4102 bool AfterNestedNameSpecifier) {
4103 if (AfterNestedNameSpecifier) {
4104 // For 'X::', we know exactly which keywords can appear next.
4105 Consumer.addKeywordResult("template");
4106 if (CCC.WantExpressionKeywords)
4107 Consumer.addKeywordResult("operator");
4108 return;
4109 }
4110
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004111 if (CCC.WantObjCSuper)
4112 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004113
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004114 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004115 // Add type-specifier keywords to the set of results.
Craig Topperd6d31ac2013-07-15 08:24:27 +00004116 static const char *const CTypeSpecs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004117 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00004118 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004119 "_Complex", "_Imaginary",
4120 // storage-specifiers as well
4121 "extern", "inline", "static", "typedef"
4122 };
4123
Craig Toppere5ce8312013-07-15 03:38:40 +00004124 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004125 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
4126 Consumer.addKeywordResult(CTypeSpecs[I]);
4127
David Blaikiebbafb8a2012-03-11 07:00:24 +00004128 if (SemaRef.getLangOpts().C99)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004129 Consumer.addKeywordResult("restrict");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004130 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004131 Consumer.addKeywordResult("bool");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004132 else if (SemaRef.getLangOpts().C99)
Douglas Gregor3b22a882011-07-01 21:27:45 +00004133 Consumer.addKeywordResult("_Bool");
4134
David Blaikiebbafb8a2012-03-11 07:00:24 +00004135 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004136 Consumer.addKeywordResult("class");
4137 Consumer.addKeywordResult("typename");
4138 Consumer.addKeywordResult("wchar_t");
4139
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004140 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004141 Consumer.addKeywordResult("char16_t");
4142 Consumer.addKeywordResult("char32_t");
4143 Consumer.addKeywordResult("constexpr");
4144 Consumer.addKeywordResult("decltype");
4145 Consumer.addKeywordResult("thread_local");
4146 }
4147 }
4148
David Blaikiebbafb8a2012-03-11 07:00:24 +00004149 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004150 Consumer.addKeywordResult("typeof");
Kaelyn Takatab04846b2014-07-28 18:14:02 +00004151 } else if (CCC.WantFunctionLikeCasts) {
4152 static const char *const CastableTypeSpecs[] = {
4153 "char", "double", "float", "int", "long", "short",
4154 "signed", "unsigned", "void"
4155 };
4156 for (auto *kw : CastableTypeSpecs)
4157 Consumer.addKeywordResult(kw);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004158 }
4159
David Blaikiebbafb8a2012-03-11 07:00:24 +00004160 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004161 Consumer.addKeywordResult("const_cast");
4162 Consumer.addKeywordResult("dynamic_cast");
4163 Consumer.addKeywordResult("reinterpret_cast");
4164 Consumer.addKeywordResult("static_cast");
4165 }
4166
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004167 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004168 Consumer.addKeywordResult("sizeof");
David Blaikiebbafb8a2012-03-11 07:00:24 +00004169 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004170 Consumer.addKeywordResult("false");
4171 Consumer.addKeywordResult("true");
4172 }
4173
David Blaikiebbafb8a2012-03-11 07:00:24 +00004174 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topperd6d31ac2013-07-15 08:24:27 +00004175 static const char *const CXXExprs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004176 "delete", "new", "operator", "throw", "typeid"
4177 };
Craig Toppere5ce8312013-07-15 03:38:40 +00004178 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004179 for (unsigned I = 0; I != NumCXXExprs; ++I)
4180 Consumer.addKeywordResult(CXXExprs[I]);
4181
4182 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
4183 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
4184 Consumer.addKeywordResult("this");
4185
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004186 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004187 Consumer.addKeywordResult("alignof");
4188 Consumer.addKeywordResult("nullptr");
4189 }
4190 }
Jordan Rose58d54722012-06-30 21:33:57 +00004191
4192 if (SemaRef.getLangOpts().C11) {
4193 // FIXME: We should not suggest _Alignof if the alignof macro
4194 // is present.
4195 Consumer.addKeywordResult("_Alignof");
4196 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004197 }
4198
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004199 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004200 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
4201 // Statements.
Craig Topperd6d31ac2013-07-15 08:24:27 +00004202 static const char *const CStmts[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004203 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Toppere5ce8312013-07-15 03:38:40 +00004204 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004205 for (unsigned I = 0; I != NumCStmts; ++I)
4206 Consumer.addKeywordResult(CStmts[I]);
4207
David Blaikiebbafb8a2012-03-11 07:00:24 +00004208 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004209 Consumer.addKeywordResult("catch");
4210 Consumer.addKeywordResult("try");
4211 }
4212
4213 if (S && S->getBreakParent())
4214 Consumer.addKeywordResult("break");
4215
4216 if (S && S->getContinueParent())
4217 Consumer.addKeywordResult("continue");
4218
4219 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
4220 Consumer.addKeywordResult("case");
4221 Consumer.addKeywordResult("default");
4222 }
4223 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004224 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004225 Consumer.addKeywordResult("namespace");
4226 Consumer.addKeywordResult("template");
4227 }
4228
4229 if (S && S->isClassScope()) {
4230 Consumer.addKeywordResult("explicit");
4231 Consumer.addKeywordResult("friend");
4232 Consumer.addKeywordResult("mutable");
4233 Consumer.addKeywordResult("private");
4234 Consumer.addKeywordResult("protected");
4235 Consumer.addKeywordResult("public");
4236 Consumer.addKeywordResult("virtual");
4237 }
4238 }
4239
David Blaikiebbafb8a2012-03-11 07:00:24 +00004240 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004241 Consumer.addKeywordResult("using");
4242
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004243 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004244 Consumer.addKeywordResult("static_assert");
4245 }
4246 }
4247}
4248
Kaelyn Takata6c759512014-10-27 18:07:37 +00004249std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
4250 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4251 Scope *S, CXXScopeSpec *SS,
4252 std::unique_ptr<CorrectionCandidateCallback> CCC,
4253 DeclContext *MemberContext, bool EnteringContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004254 const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00004255
4256 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4257 DisableTypoCorrection)
4258 return nullptr;
4259
4260 // In Microsoft mode, don't perform typo correction in a template member
4261 // function dependent context because it interferes with the "lookup into
4262 // dependent bases of class templates" feature.
4263 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
4264 isa<CXXMethodDecl>(CurContext))
4265 return nullptr;
4266
4267 // We only attempt to correct typos for identifiers.
4268 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4269 if (!Typo)
4270 return nullptr;
4271
4272 // If the scope specifier itself was invalid, don't try to correct
4273 // typos.
4274 if (SS && SS->isInvalid())
4275 return nullptr;
4276
4277 // Never try to correct typos during template deduction or
4278 // instantiation.
4279 if (!ActiveTemplateInstantiations.empty())
4280 return nullptr;
4281
4282 // Don't try to correct 'super'.
4283 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4284 return nullptr;
4285
4286 // Abort if typo correction already failed for this specific typo.
4287 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4288 if (locs != TypoCorrectionFailures.end() &&
4289 locs->second.count(TypoName.getLoc()))
4290 return nullptr;
4291
4292 // Don't try to correct the identifier "vector" when in AltiVec mode.
4293 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4294 // remove this workaround.
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00004295 if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector"))
Kaelyn Takata6c759512014-10-27 18:07:37 +00004296 return nullptr;
4297
Nick Lewycky24653262014-12-16 21:39:02 +00004298 // Provide a stop gap for files that are just seriously broken. Trying
4299 // to correct all typos can turn into a HUGE performance penalty, causing
4300 // some files to take minutes to get rejected by the parser.
4301 unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
4302 if (Limit && TyposCorrected >= Limit)
4303 return nullptr;
4304 ++TyposCorrected;
4305
Kaelyn Takata6c759512014-10-27 18:07:37 +00004306 // If we're handling a missing symbol error, using modules, and the
4307 // special search all modules option is used, look for a missing import.
4308 if (ErrorRecovery && getLangOpts().Modules &&
4309 getLangOpts().ModulesSearchAll) {
4310 // The following has the side effect of loading the missing module.
4311 getModuleLoader().lookupMissingImports(Typo->getName(),
4312 TypoName.getLocStart());
4313 }
4314
4315 CorrectionCandidateCallback &CCCRef = *CCC;
4316 auto Consumer = llvm::make_unique<TypoCorrectionConsumer>(
4317 *this, TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
4318 EnteringContext);
4319
Kaelyn Takata6c759512014-10-27 18:07:37 +00004320 // Perform name lookup to find visible, similarly-named entities.
Nick Lewycky24653262014-12-16 21:39:02 +00004321 bool IsUnqualifiedLookup = false;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004322 DeclContext *QualifiedDC = MemberContext;
4323 if (MemberContext) {
4324 LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
4325
4326 // Look in qualified interfaces.
4327 if (OPT) {
4328 for (auto *I : OPT->quals())
4329 LookupVisibleDecls(I, LookupKind, *Consumer);
4330 }
4331 } else if (SS && SS->isSet()) {
4332 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4333 if (!QualifiedDC)
4334 return nullptr;
4335
Kaelyn Takata6c759512014-10-27 18:07:37 +00004336 LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
4337 } else {
4338 IsUnqualifiedLookup = true;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004339 }
4340
4341 // Determine whether we are going to search in the various namespaces for
4342 // corrections.
4343 bool SearchNamespaces
4344 = getLangOpts().CPlusPlus &&
4345 (IsUnqualifiedLookup || (SS && SS->isSet()));
4346
4347 if (IsUnqualifiedLookup || SearchNamespaces) {
4348 // For unqualified lookup, look through all of the names that we have
4349 // seen in this translation unit.
4350 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4351 for (const auto &I : Context.Idents)
4352 Consumer->FoundName(I.getKey());
4353
4354 // Walk through identifiers in external identifier sources.
4355 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4356 if (IdentifierInfoLookup *External
4357 = Context.Idents.getExternalIdentifierLookup()) {
4358 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4359 do {
4360 StringRef Name = Iter->Next();
4361 if (Name.empty())
4362 break;
4363
4364 Consumer->FoundName(Name);
4365 } while (true);
4366 }
4367 }
4368
4369 AddKeywordsToConsumer(*this, *Consumer, S, CCCRef, SS && SS->isNotEmpty());
4370
4371 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4372 // to search those namespaces.
4373 if (SearchNamespaces) {
4374 // Load any externally-known namespaces.
4375 if (ExternalSource && !LoadedExternalKnownNamespaces) {
4376 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
4377 LoadedExternalKnownNamespaces = true;
4378 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4379 for (auto *N : ExternalKnownNamespaces)
4380 KnownNamespaces[N] = true;
4381 }
4382
4383 Consumer->addNamespaces(KnownNamespaces);
4384 }
4385
4386 return Consumer;
4387}
4388
Douglas Gregor2d435302009-12-30 17:04:44 +00004389/// \brief Try to "correct" a typo in the source code by finding
4390/// visible declarations whose names are similar to the name that was
4391/// present in the source code.
4392///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004393/// \param TypoName the \c DeclarationNameInfo structure that contains
4394/// the name that was present in the source code along with its location.
4395///
4396/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00004397///
4398/// \param S the scope in which name lookup occurs.
4399///
4400/// \param SS the nested-name-specifier that precedes the name we're
4401/// looking for, if present.
4402///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004403/// \param CCC A CorrectionCandidateCallback object that provides further
4404/// validation of typo correction candidates. It also provides flags for
4405/// determining the set of keywords permitted.
4406///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00004407/// \param MemberContext if non-NULL, the context in which to look for
4408/// a member access expression.
4409///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004410/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00004411/// the nested-name-specifier SS.
4412///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004413/// \param OPT when non-NULL, the search for visible declarations will
4414/// also walk the protocols in the qualified interfaces of \p OPT.
4415///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004416/// \returns a \c TypoCorrection containing the corrected name if the typo
4417/// along with information such as the \c NamedDecl where the corrected name
4418/// was declared, and any additional \c NestedNameSpecifier needed to access
4419/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
4420TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
4421 Sema::LookupNameKind LookupKind,
4422 Scope *S, CXXScopeSpec *SS,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004423 std::unique_ptr<CorrectionCandidateCallback> CCC,
John Thompson2255f2c2014-04-23 12:57:01 +00004424 CorrectTypoKind Mode,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004425 DeclContext *MemberContext,
4426 bool EnteringContext,
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004427 const ObjCObjectPointerType *OPT,
4428 bool RecordFailure) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004429 assert(CCC && "CorrectTypo requires a CorrectionCandidateCallback");
4430
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004431 // Always let the ExternalSource have the first chance at correction, even
4432 // if we would otherwise have given up.
4433 if (ExternalSource) {
4434 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004435 TypoName, LookupKind, S, SS, *CCC, MemberContext, EnteringContext, OPT))
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004436 return Correction;
4437 }
4438
Kaelyn Takata6c759512014-10-27 18:07:37 +00004439 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4440 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4441 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4442 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
4443 bool ObjCMessageReceiver = CCC->WantObjCSuper && !CCC->WantRemainingKeywords;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004444
Kaelyn Takata6c759512014-10-27 18:07:37 +00004445 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Kaelyn Takata6c759512014-10-27 18:07:37 +00004446 auto Consumer = makeTypoCorrectionConsumer(
4447 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004448 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004449
Kaelyn Takata6c759512014-10-27 18:07:37 +00004450 if (!Consumer)
4451 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004452
Douglas Gregor280e1ee2010-04-14 20:04:41 +00004453 // If we haven't found anything, we're done.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004454 if (Consumer->empty())
Nick Lewycky24653262014-12-16 21:39:02 +00004455 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregor2d435302009-12-30 17:04:44 +00004456
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004457 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4458 // is not more that about a third of the length of the typo's identifier.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004459 unsigned ED = Consumer->getBestEditDistance(true);
4460 unsigned TypoLen = Typo->getName().size();
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004461 if (ED > 0 && TypoLen / ED < 3)
Nick Lewycky24653262014-12-16 21:39:02 +00004462 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004463
Kaelyn Takata6c759512014-10-27 18:07:37 +00004464 TypoCorrection BestTC = Consumer->getNextCorrection();
4465 TypoCorrection SecondBestTC = Consumer->getNextCorrection();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004466 if (!BestTC)
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004467 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004468
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004469 ED = BestTC.getEditDistance();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004470
Kaelyn Takata6c759512014-10-27 18:07:37 +00004471 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004472 // If this was an unqualified lookup and we believe the callback
4473 // object wouldn't have filtered out possible corrections, note
4474 // that no correction was found.
Nick Lewycky24653262014-12-16 21:39:02 +00004475 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004476 }
4477
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004478 // If only a single name remains, return that result.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004479 if (!SecondBestTC ||
4480 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
4481 const TypoCorrection &Result = BestTC;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004482
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00004483 // Don't correct to a keyword that's the same as the typo; the keyword
4484 // wasn't actually in scope.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004485 if (ED == 0 && Result.isKeyword())
4486 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004487
David Blaikie04ea41c2012-10-12 20:00:44 +00004488 TypoCorrection TC = Result;
4489 TC.setCorrectionRange(SS, TypoName);
Kaelyn Takataa95ebc62014-06-17 23:47:29 +00004490 checkCorrectionVisibility(*this, TC);
David Blaikie04ea41c2012-10-12 20:00:44 +00004491 return TC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004492 } else if (SecondBestTC && ObjCMessageReceiver) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004493 // Prefer 'super' when we're completing in a message-receiver
4494 // context.
4495
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004496 if (BestTC.getCorrection().getAsString() != "super") {
4497 if (SecondBestTC.getCorrection().getAsString() == "super")
4498 BestTC = SecondBestTC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004499 else if ((*Consumer)["super"].front().isKeyword())
4500 BestTC = (*Consumer)["super"].front();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004501 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004502 // Don't correct to a keyword that's the same as the typo; the keyword
4503 // wasn't actually in scope.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004504 if (BestTC.getEditDistance() == 0 ||
4505 BestTC.getCorrection().getAsString() != "super")
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004506 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004507
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004508 BestTC.setCorrectionRange(SS, TypoName);
4509 return BestTC;
Douglas Gregoraf9eb592010-10-15 13:35:25 +00004510 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004511
Kaelyn Takata73429fd2014-06-10 21:03:49 +00004512 // Record the failure's location if needed and return an empty correction. If
4513 // this was an unqualified lookup and we believe the callback object did not
4514 // filter out possible corrections, also cache the failure for the typo.
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004515 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004516}
4517
Kaelyn Takata6c759512014-10-27 18:07:37 +00004518/// \brief Try to "correct" a typo in the source code by finding
4519/// visible declarations whose names are similar to the name that was
4520/// present in the source code.
4521///
4522/// \param TypoName the \c DeclarationNameInfo structure that contains
4523/// the name that was present in the source code along with its location.
4524///
4525/// \param LookupKind the name-lookup criteria used to search for the name.
4526///
4527/// \param S the scope in which name lookup occurs.
4528///
4529/// \param SS the nested-name-specifier that precedes the name we're
4530/// looking for, if present.
4531///
4532/// \param CCC A CorrectionCandidateCallback object that provides further
4533/// validation of typo correction candidates. It also provides flags for
4534/// determining the set of keywords permitted.
4535///
4536/// \param TDG A TypoDiagnosticGenerator functor that will be used to print
4537/// diagnostics when the actual typo correction is attempted.
4538///
Kaelyn Takata8363f042014-10-27 18:07:42 +00004539/// \param TRC A TypoRecoveryCallback functor that will be used to build an
4540/// Expr from a typo correction candidate.
4541///
Kaelyn Takata6c759512014-10-27 18:07:37 +00004542/// \param MemberContext if non-NULL, the context in which to look for
4543/// a member access expression.
4544///
4545/// \param EnteringContext whether we're entering the context described by
4546/// the nested-name-specifier SS.
4547///
4548/// \param OPT when non-NULL, the search for visible declarations will
4549/// also walk the protocols in the qualified interfaces of \p OPT.
4550///
4551/// \returns a new \c TypoExpr that will later be replaced in the AST with an
4552/// Expr representing the result of performing typo correction, or nullptr if
4553/// typo correction is not possible. If nullptr is returned, no diagnostics will
4554/// be emitted and it is the responsibility of the caller to emit any that are
4555/// needed.
4556TypoExpr *Sema::CorrectTypoDelayed(
4557 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4558 Scope *S, CXXScopeSpec *SS,
4559 std::unique_ptr<CorrectionCandidateCallback> CCC,
Kaelyn Takata8363f042014-10-27 18:07:42 +00004560 TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,
Kaelyn Takata6c759512014-10-27 18:07:37 +00004561 DeclContext *MemberContext, bool EnteringContext,
4562 const ObjCObjectPointerType *OPT) {
4563 assert(CCC && "CorrectTypoDelayed requires a CorrectionCandidateCallback");
4564
4565 TypoCorrection Empty;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004566 auto Consumer = makeTypoCorrectionConsumer(
4567 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004568 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Kaelyn Takata6c759512014-10-27 18:07:37 +00004569
4570 if (!Consumer || Consumer->empty())
4571 return nullptr;
4572
4573 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4574 // is not more that about a third of the length of the typo's identifier.
4575 unsigned ED = Consumer->getBestEditDistance(true);
4576 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4577 if (ED > 0 && Typo->getName().size() / ED < 3)
4578 return nullptr;
4579
4580 ExprEvalContexts.back().NumTypos++;
Kaelyn Takata8363f042014-10-27 18:07:42 +00004581 return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC));
Kaelyn Takata6c759512014-10-27 18:07:37 +00004582}
4583
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004584void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4585 if (!CDecl) return;
4586
4587 if (isKeyword())
4588 CorrectionDecls.clear();
4589
Kaelyn Uhrainf60b55a2012-11-19 18:49:53 +00004590 CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004591
4592 if (!CorrectionName)
4593 CorrectionName = CDecl->getDeclName();
4594}
4595
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004596std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4597 if (CorrectionNameSpec) {
4598 std::string tmpBuffer;
4599 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4600 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikied4da8722013-05-14 21:04:00 +00004601 PrefixOStream << CorrectionName;
Benjamin Kramer73faad62012-04-14 08:26:28 +00004602 return PrefixOStream.str();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004603 }
4604
4605 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00004606}
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004607
Nico Weberb58e51c2014-11-19 05:21:39 +00004608bool CorrectionCandidateCallback::ValidateCandidate(
4609 const TypoCorrection &candidate) {
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004610 if (!candidate.isResolved())
4611 return true;
4612
4613 if (candidate.isKeyword())
4614 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4615 WantRemainingKeywords || WantObjCSuper;
4616
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004617 bool HasNonType = false;
4618 bool HasStaticMethod = false;
4619 bool HasNonStaticMethod = false;
4620 for (Decl *D : candidate) {
4621 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
4622 D = FTD->getTemplatedDecl();
4623 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4624 if (Method->isStatic())
4625 HasStaticMethod = true;
4626 else
4627 HasNonStaticMethod = true;
4628 }
4629 if (!isa<TypeDecl>(D))
4630 HasNonType = true;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004631 }
4632
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004633 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
4634 !candidate.getCorrectionSpecifier())
4635 return false;
4636
4637 return WantTypeSpecifiers || HasNonType;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004638}
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004639
4640FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004641 bool HasExplicitTemplateArgs,
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004642 MemberExpr *ME)
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004643 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004644 CurContext(SemaRef.CurContext), MemberFn(ME) {
Kaelyn Takatab04846b2014-07-28 18:14:02 +00004645 WantTypeSpecifiers = false;
4646 WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus && NumArgs == 1;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004647 WantRemainingKeywords = false;
4648}
4649
4650bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4651 if (!candidate.getCorrectionDecl())
4652 return candidate.isKeyword();
4653
Aaron Ballman1e606f42014-07-15 22:03:49 +00004654 for (auto *C : candidate) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004655 FunctionDecl *FD = nullptr;
Aaron Ballman1e606f42014-07-15 22:03:49 +00004656 NamedDecl *ND = C->getUnderlyingDecl();
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004657 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4658 FD = FTD->getTemplatedDecl();
4659 if (!HasExplicitTemplateArgs && !FD) {
4660 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4661 // If the Decl is neither a function nor a template function,
4662 // determine if it is a pointer or reference to a function. If so,
4663 // check against the number of arguments expected for the pointee.
4664 QualType ValType = cast<ValueDecl>(ND)->getType();
4665 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4666 ValType = ValType->getPointeeType();
4667 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
Alp Toker9cacbab2014-01-20 20:26:09 +00004668 if (FPT->getNumParams() == NumArgs)
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004669 return true;
4670 }
4671 }
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004672
4673 // Skip the current candidate if it is not a FunctionDecl or does not accept
4674 // the current number of arguments.
4675 if (!FD || !(FD->getNumParams() >= NumArgs &&
4676 FD->getMinRequiredArguments() <= NumArgs))
4677 continue;
4678
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004679 // If the current candidate is a non-static C++ method, skip the candidate
4680 // unless the method being corrected--or the current DeclContext, if the
4681 // function being corrected is not a method--is a method in the same class
4682 // or a descendent class of the candidate's parent class.
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004683 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004684 if (MemberFn || !MD->isStatic()) {
4685 CXXMethodDecl *CurMD =
4686 MemberFn
4687 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
4688 : dyn_cast_or_null<CXXMethodDecl>(CurContext);
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004689 CXXRecordDecl *CurRD =
Craig Topperc3ec1492014-05-26 06:22:03 +00004690 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004691 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
4692 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
4693 continue;
4694 }
4695 }
4696 return true;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004697 }
4698 return false;
4699}
Richard Smithf9b15102013-08-17 00:46:16 +00004700
4701void Sema::diagnoseTypo(const TypoCorrection &Correction,
4702 const PartialDiagnostic &TypoDiag,
4703 bool ErrorRecovery) {
4704 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
4705 ErrorRecovery);
4706}
4707
Richard Smithe156254d2013-08-20 20:35:18 +00004708/// Find which declaration we should import to provide the definition of
4709/// the given declaration.
Richard Smith42413142015-05-15 20:05:43 +00004710static NamedDecl *getDefinitionToImport(NamedDecl *D) {
4711 if (VarDecl *VD = dyn_cast<VarDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004712 return VD->getDefinition();
4713 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Richard Smith42413142015-05-15 20:05:43 +00004714 return FD->isDefined(FD) ? const_cast<FunctionDecl*>(FD) : nullptr;
4715 if (TagDecl *TD = dyn_cast<TagDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004716 return TD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00004717 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004718 return ID->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00004719 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004720 return PD->getDefinition();
Richard Smith42413142015-05-15 20:05:43 +00004721 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
Richard Smithe156254d2013-08-20 20:35:18 +00004722 return getDefinitionToImport(TD->getTemplatedDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004723 return nullptr;
Richard Smithe156254d2013-08-20 20:35:18 +00004724}
4725
Richard Smithf2b1eb92015-06-15 20:15:48 +00004726void Sema::diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
4727 bool NeedDefinition, bool Recover) {
4728 assert(!isVisible(Decl) && "missing import for non-hidden decl?");
4729
4730 // Suggest importing a module providing the definition of this entity, if
4731 // possible.
4732 NamedDecl *Def = getDefinitionToImport(Decl);
4733 if (!Def)
4734 Def = Decl;
4735
4736 // FIXME: Add a Fix-It that imports the corresponding module or includes
4737 // the header.
4738 Module *Owner = getOwningModule(Decl);
4739 assert(Owner && "definition of hidden declaration is not in a module");
4740
Richard Smith35c1df52015-06-17 20:16:32 +00004741 llvm::SmallVector<Module*, 8> OwningModules;
4742 OwningModules.push_back(Owner);
Richard Smithf2b1eb92015-06-15 20:15:48 +00004743 auto Merged = Context.getModulesWithMergedDefinition(Decl);
Richard Smith35c1df52015-06-17 20:16:32 +00004744 OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end());
4745
4746 diagnoseMissingImport(Loc, Decl, Decl->getLocation(), OwningModules,
4747 NeedDefinition ? MissingImportKind::Definition
4748 : MissingImportKind::Declaration,
4749 Recover);
4750}
4751
4752void Sema::diagnoseMissingImport(SourceLocation UseLoc, NamedDecl *Decl,
4753 SourceLocation DeclLoc,
4754 ArrayRef<Module *> Modules,
4755 MissingImportKind MIK, bool Recover) {
4756 assert(!Modules.empty());
4757
4758 if (Modules.size() > 1) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00004759 std::string ModuleList;
Richard Smithf2b1eb92015-06-15 20:15:48 +00004760 unsigned N = 0;
Richard Smith35c1df52015-06-17 20:16:32 +00004761 for (Module *M : Modules) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00004762 ModuleList += "\n ";
Richard Smith35c1df52015-06-17 20:16:32 +00004763 if (++N == 5 && N != Modules.size()) {
Richard Smithf2b1eb92015-06-15 20:15:48 +00004764 ModuleList += "[...]";
4765 break;
4766 }
4767 ModuleList += M->getFullModuleName();
4768 }
4769
Richard Smith35c1df52015-06-17 20:16:32 +00004770 Diag(UseLoc, diag::err_module_unimported_use_multiple)
4771 << (int)MIK << Decl << ModuleList;
Richard Smithf2b1eb92015-06-15 20:15:48 +00004772 } else {
Richard Smith35c1df52015-06-17 20:16:32 +00004773 Diag(UseLoc, diag::err_module_unimported_use)
4774 << (int)MIK << Decl << Modules[0]->getFullModuleName();
Richard Smithf2b1eb92015-06-15 20:15:48 +00004775 }
Richard Smith35c1df52015-06-17 20:16:32 +00004776
4777 unsigned DiagID;
4778 switch (MIK) {
4779 case MissingImportKind::Declaration:
4780 DiagID = diag::note_previous_declaration;
4781 break;
4782 case MissingImportKind::Definition:
4783 DiagID = diag::note_previous_definition;
4784 break;
4785 case MissingImportKind::DefaultArgument:
4786 DiagID = diag::note_default_argument_declared_here;
4787 break;
4788 }
4789 Diag(DeclLoc, DiagID);
Richard Smithf2b1eb92015-06-15 20:15:48 +00004790
4791 // Try to recover by implicitly importing this module.
4792 if (Recover)
Richard Smith35c1df52015-06-17 20:16:32 +00004793 createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
Richard Smithf2b1eb92015-06-15 20:15:48 +00004794}
4795
Richard Smithf9b15102013-08-17 00:46:16 +00004796/// \brief Diagnose a successfully-corrected typo. Separated from the correction
4797/// itself to allow external validation of the result, etc.
4798///
4799/// \param Correction The result of performing typo correction.
4800/// \param TypoDiag The diagnostic to produce. This will have the corrected
4801/// string added to it (and usually also a fixit).
4802/// \param PrevNote A note to use when indicating the location of the entity to
4803/// which we are correcting. Will have the correction string added to it.
4804/// \param ErrorRecovery If \c true (the default), the caller is going to
4805/// recover from the typo as if the corrected string had been typed.
4806/// In this case, \c PDiag must be an error, and we will attach a fixit
4807/// to it.
4808void Sema::diagnoseTypo(const TypoCorrection &Correction,
4809 const PartialDiagnostic &TypoDiag,
4810 const PartialDiagnostic &PrevNote,
4811 bool ErrorRecovery) {
4812 std::string CorrectedStr = Correction.getAsString(getLangOpts());
4813 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
4814 FixItHint FixTypo = FixItHint::CreateReplacement(
4815 Correction.getCorrectionRange(), CorrectedStr);
4816
Richard Smithe156254d2013-08-20 20:35:18 +00004817 // Maybe we're just missing a module import.
4818 if (Correction.requiresImport()) {
4819 NamedDecl *Decl = Correction.getCorrectionDecl();
4820 assert(Decl && "import required but no declaration to import");
4821
Richard Smithf2b1eb92015-06-15 20:15:48 +00004822 diagnoseMissingImport(Correction.getCorrectionRange().getBegin(), Decl,
4823 /*NeedDefinition*/ false, ErrorRecovery);
Richard Smithe156254d2013-08-20 20:35:18 +00004824 return;
4825 }
4826
Richard Smithf9b15102013-08-17 00:46:16 +00004827 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
4828 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
4829
4830 NamedDecl *ChosenDecl =
Craig Topperc3ec1492014-05-26 06:22:03 +00004831 Correction.isKeyword() ? nullptr : Correction.getCorrectionDecl();
Richard Smithf9b15102013-08-17 00:46:16 +00004832 if (PrevNote.getDiagID() && ChosenDecl)
4833 Diag(ChosenDecl->getLocation(), PrevNote)
4834 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
4835}
Kaelyn Takata6c759512014-10-27 18:07:37 +00004836
Kaelyn Takata8363f042014-10-27 18:07:42 +00004837TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
4838 TypoDiagnosticGenerator TDG,
4839 TypoRecoveryCallback TRC) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00004840 assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
4841 auto TE = new (Context) TypoExpr(Context.DependentTy);
4842 auto &State = DelayedTypos[TE];
4843 State.Consumer = std::move(TCC);
4844 State.DiagHandler = std::move(TDG);
Kaelyn Takata8363f042014-10-27 18:07:42 +00004845 State.RecoveryHandler = std::move(TRC);
Kaelyn Takata6c759512014-10-27 18:07:37 +00004846 return TE;
4847}
4848
4849const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
4850 auto Entry = DelayedTypos.find(TE);
4851 assert(Entry != DelayedTypos.end() &&
4852 "Failed to get the state for a TypoExpr!");
4853 return Entry->second;
4854}
4855
4856void Sema::clearDelayedTypo(TypoExpr *TE) {
4857 DelayedTypos.erase(TE);
4858}