blob: 012c1cf392734c4ffad5dd42223509e1d9b4aaba [file] [log] [blame]
Douglas Gregor34074322009-01-14 22:20:51 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000014#include "clang/Sema/Lookup.h"
Douglas Gregor960b5bc2009-01-15 00:26:24 +000015#include "clang/AST/ASTContext.h"
Richard Smithd9ba2242015-05-07 03:54:19 +000016#include "clang/AST/ASTMutationListener.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000018#include "clang/AST/Decl.h"
19#include "clang/AST/DeclCXX.h"
Nick Lewyckyc3921482012-04-03 21:44:08 +000020#include "clang/AST/DeclLookups.h"
Douglas Gregor34074322009-01-14 22:20:51 +000021#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000022#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000023#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000024#include "clang/AST/ExprCXX.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Douglas Gregor34074322009-01-14 22:20:51 +000026#include "clang/Basic/LangOptions.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000027#include "clang/Lex/ModuleLoader.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "clang/Sema/DeclSpec.h"
29#include "clang/Sema/ExternalSemaSource.h"
30#include "clang/Sema/Overload.h"
31#include "clang/Sema/Scope.h"
32#include "clang/Sema/ScopeInfo.h"
33#include "clang/Sema/Sema.h"
34#include "clang/Sema/SemaInternal.h"
35#include "clang/Sema/TemplateDeduction.h"
36#include "clang/Sema/TypoCorrection.h"
Douglas Gregor34074322009-01-14 22:20:51 +000037#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "llvm/ADT/SetVector.h"
Douglas Gregore254f902009-02-04 00:32:51 +000039#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0afa7f62010-10-14 20:34:08 +000040#include "llvm/ADT/StringMap.h"
Chris Lattner83cfc7c2011-07-18 01:54:02 +000041#include "llvm/ADT/TinyPtrVector.h"
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +000042#include "llvm/ADT/edit_distance.h"
John McCall6538c932009-10-10 05:48:19 +000043#include "llvm/Support/ErrorHandling.h"
Nick Lewycky13668f22012-04-03 20:26:45 +000044#include <algorithm>
45#include <iterator>
Douglas Gregor0afa7f62010-10-14 20:34:08 +000046#include <limits>
Douglas Gregor2d435302009-12-30 17:04:44 +000047#include <list>
Douglas Gregorc2fa1692011-06-28 16:20:02 +000048#include <map>
Nick Lewycky13668f22012-04-03 20:26:45 +000049#include <set>
50#include <utility>
51#include <vector>
Douglas Gregor34074322009-01-14 22:20:51 +000052
53using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000054using namespace sema;
Douglas Gregor34074322009-01-14 22:20:51 +000055
John McCallf6c8a4e2009-11-10 07:01:13 +000056namespace {
57 class UnqualUsingEntry {
58 const DeclContext *Nominated;
59 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000060
John McCallf6c8a4e2009-11-10 07:01:13 +000061 public:
62 UnqualUsingEntry(const DeclContext *Nominated,
63 const DeclContext *CommonAncestor)
64 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
65 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000066
John McCallf6c8a4e2009-11-10 07:01:13 +000067 const DeclContext *getCommonAncestor() const {
68 return CommonAncestor;
69 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000070
John McCallf6c8a4e2009-11-10 07:01:13 +000071 const DeclContext *getNominatedNamespace() const {
72 return Nominated;
73 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000074
John McCallf6c8a4e2009-11-10 07:01:13 +000075 // Sort by the pointer value of the common ancestor.
76 struct Comparator {
77 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
78 return L.getCommonAncestor() < R.getCommonAncestor();
79 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000080
John McCallf6c8a4e2009-11-10 07:01:13 +000081 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
82 return E.getCommonAncestor() < DC;
83 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000084
John McCallf6c8a4e2009-11-10 07:01:13 +000085 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
86 return DC < E.getCommonAncestor();
87 }
88 };
89 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000090
John McCallf6c8a4e2009-11-10 07:01:13 +000091 /// A collection of using directives, as used by C++ unqualified
92 /// lookup.
93 class UnqualUsingDirectiveSet {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000094 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000095
John McCallf6c8a4e2009-11-10 07:01:13 +000096 ListTy list;
97 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000098
John McCallf6c8a4e2009-11-10 07:01:13 +000099 public:
100 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +0000101
John McCallf6c8a4e2009-11-10 07:01:13 +0000102 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000103 // C++ [namespace.udir]p1:
John McCallf6c8a4e2009-11-10 07:01:13 +0000104 // During unqualified name lookup, the names appear as if they
105 // were declared in the nearest enclosing namespace which contains
106 // both the using-directive and the nominated namespace.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000107 DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
John McCallf6c8a4e2009-11-10 07:01:13 +0000108 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +0000109
John McCallf6c8a4e2009-11-10 07:01:13 +0000110 for (; S; S = S->getParent()) {
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000111 // C++ [namespace.udir]p1:
112 // A using-directive shall not appear in class scope, but may
113 // appear in namespace scope or in block scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000114 DeclContext *Ctx = S->getEntity();
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000115 if (Ctx && Ctx->isFileContext()) {
116 visit(Ctx, Ctx);
117 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
Aaron Ballman5df6aa42014-03-17 17:03:37 +0000118 for (auto *I : S->using_directives())
119 visit(I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000120 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000121 }
122 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000123
124 // Visits a context and collect all of its using directives
125 // recursively. Treats all using directives as if they were
126 // declared in the context.
127 //
128 // A given context is only every visited once, so it is important
129 // that contexts be visited from the inside out in order to get
130 // the effective DCs right.
131 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
David Blaikie82e95a32014-11-19 07:49:47 +0000132 if (!visited.insert(DC).second)
John McCallf6c8a4e2009-11-10 07:01:13 +0000133 return;
134
135 addUsingDirectives(DC, EffectiveDC);
136 }
137
138 // Visits a using directive and collects all of its using
139 // directives recursively. Treats all using directives as if they
140 // were declared in the effective DC.
141 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
142 DeclContext *NS = UD->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +0000143 if (!visited.insert(NS).second)
John McCallf6c8a4e2009-11-10 07:01:13 +0000144 return;
145
146 addUsingDirective(UD, EffectiveDC);
147 addUsingDirectives(NS, EffectiveDC);
148 }
149
150 // Adds all the using directives in a context (and those nominated
151 // by its using directives, transitively) as if they appeared in
152 // the given effective context.
153 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000154 SmallVector<DeclContext*,4> queue;
John McCallf6c8a4e2009-11-10 07:01:13 +0000155 while (true) {
Aaron Ballman804a7fb2014-03-17 17:14:12 +0000156 for (auto UD : DC->using_directives()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000157 DeclContext *NS = UD->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +0000158 if (visited.insert(NS).second) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000159 addUsingDirective(UD, EffectiveDC);
160 queue.push_back(NS);
161 }
162 }
163
164 if (queue.empty())
165 return;
166
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000167 DC = queue.pop_back_val();
John McCallf6c8a4e2009-11-10 07:01:13 +0000168 }
169 }
170
171 // Add a using directive as if it had been declared in the given
172 // context. This helps implement C++ [namespace.udir]p3:
173 // The using-directive is transitive: if a scope contains a
174 // using-directive that nominates a second namespace that itself
175 // contains using-directives, the effect is as if the
176 // using-directives from the second namespace also appeared in
177 // the first.
178 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
179 // Find the common ancestor between the effective context and
180 // the nominated namespace.
181 DeclContext *Common = UD->getNominatedNamespace();
182 while (!Common->Encloses(EffectiveDC))
183 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000184 Common = Common->getPrimaryContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000185
John McCallf6c8a4e2009-11-10 07:01:13 +0000186 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
187 }
188
189 void done() {
190 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
191 }
192
John McCallf6c8a4e2009-11-10 07:01:13 +0000193 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000194
John McCallf6c8a4e2009-11-10 07:01:13 +0000195 const_iterator begin() const { return list.begin(); }
196 const_iterator end() const { return list.end(); }
197
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000198 llvm::iterator_range<const_iterator>
John McCallf6c8a4e2009-11-10 07:01:13 +0000199 getNamespacesFor(DeclContext *DC) const {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000200 return llvm::make_range(std::equal_range(begin(), end(),
201 DC->getPrimaryContext(),
202 UnqualUsingEntry::Comparator()));
John McCallf6c8a4e2009-11-10 07:01:13 +0000203 }
204 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000205}
206
Douglas Gregor889ceb72009-02-03 19:21:40 +0000207// Retrieve the set of identifier namespaces that correspond to a
208// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000209static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
210 bool CPlusPlus,
211 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000212 unsigned IDNS = 0;
213 switch (NameKind) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +0000214 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000215 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000216 case Sema::LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +0000217 case Sema::LookupLocalFriendName:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000218 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000219 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000220 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000221 if (Redeclaration)
222 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCallea305ed2009-12-18 10:40:03 +0000223 }
Richard Smith541b38b2013-09-20 01:15:31 +0000224 if (Redeclaration)
225 IDNS |= Decl::IDNS_LocalExtern;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000226 break;
227
John McCallb9467b62010-04-24 01:30:58 +0000228 case Sema::LookupOperatorName:
229 // Operator lookup is its own crazy thing; it is not the same
230 // as (e.g.) looking up an operator name for redeclaration.
231 assert(!Redeclaration && "cannot do redeclaration operator lookup");
232 IDNS = Decl::IDNS_NonMemberOperator;
233 break;
234
Douglas Gregor889ceb72009-02-03 19:21:40 +0000235 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000236 if (CPlusPlus) {
237 IDNS = Decl::IDNS_Type;
238
239 // When looking for a redeclaration of a tag name, we add:
240 // 1) TagFriend to find undeclared friend decls
241 // 2) Namespace because they can't "overload" with tag decls.
242 // 3) Tag because it includes class templates, which can't
243 // "overload" with tag decls.
244 if (Redeclaration)
245 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
246 } else {
247 IDNS = Decl::IDNS_Tag;
248 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000249 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000250
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000251 case Sema::LookupLabel:
252 IDNS = Decl::IDNS_Label;
253 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000254
Douglas Gregor889ceb72009-02-03 19:21:40 +0000255 case Sema::LookupMemberName:
256 IDNS = Decl::IDNS_Member;
257 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000258 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000259 break;
260
261 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000262 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
263 break;
264
Douglas Gregor889ceb72009-02-03 19:21:40 +0000265 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000266 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000267 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000268
John McCall84d87672009-12-10 09:41:52 +0000269 case Sema::LookupUsingDeclName:
Richard Smith83e78f52014-04-11 01:03:38 +0000270 assert(Redeclaration && "should only be used for redecl lookup");
271 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |
272 Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend |
273 Decl::IDNS_LocalExtern;
John McCall84d87672009-12-10 09:41:52 +0000274 break;
275
Douglas Gregor79947a22009-04-24 00:11:27 +0000276 case Sema::LookupObjCProtocolName:
277 IDNS = Decl::IDNS_ObjCProtocol;
278 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000279
Douglas Gregor39982192010-08-15 06:18:01 +0000280 case Sema::LookupAnyName:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000281 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor39982192010-08-15 06:18:01 +0000282 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
283 | Decl::IDNS_Type;
284 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000285 }
286 return IDNS;
287}
288
John McCallea305ed2009-12-18 10:40:03 +0000289void LookupResult::configure() {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000290 IDNS = getIDNS(LookupKind, getSema().getLangOpts().CPlusPlus,
John McCallea305ed2009-12-18 10:40:03 +0000291 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000292
Richard Smithbdd14642014-02-04 01:14:30 +0000293 // If we're looking for one of the allocation or deallocation
294 // operators, make sure that the implicitly-declared new and delete
295 // operators can be found.
296 switch (NameInfo.getName().getCXXOverloadedOperator()) {
297 case OO_New:
298 case OO_Delete:
299 case OO_Array_New:
300 case OO_Array_Delete:
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000301 getSema().DeclareGlobalNewDelete();
Richard Smithbdd14642014-02-04 01:14:30 +0000302 break;
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000303
Richard Smithbdd14642014-02-04 01:14:30 +0000304 default:
305 break;
306 }
Douglas Gregor15197662013-04-03 23:06:26 +0000307
Richard Smithbdd14642014-02-04 01:14:30 +0000308 // Compiler builtins are always visible, regardless of where they end
309 // up being declared.
310 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
311 if (unsigned BuiltinID = Id->getBuiltinID()) {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000312 if (!getSema().Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
Richard Smithbdd14642014-02-04 01:14:30 +0000313 AllowHidden = true;
Douglas Gregor15197662013-04-03 23:06:26 +0000314 }
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000315 }
John McCallea305ed2009-12-18 10:40:03 +0000316}
317
Alp Tokerc1086762013-12-07 13:51:35 +0000318bool LookupResult::sanity() const {
Richard Smithf97ad222014-04-01 18:33:50 +0000319 // This function is never called by NDEBUG builds.
John McCall19c1bfd2010-08-25 05:32:35 +0000320 assert(ResultKind != NotFound || Decls.size() == 0);
321 assert(ResultKind != Found || Decls.size() == 1);
322 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
323 (Decls.size() == 1 &&
324 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
325 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
326 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000327 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
328 Ambiguity == AmbiguousBaseSubobjectTypes)));
Craig Topperc3ec1492014-05-26 06:22:03 +0000329 assert((Paths != nullptr) == (ResultKind == Ambiguous &&
330 (Ambiguity == AmbiguousBaseSubobjectTypes ||
331 Ambiguity == AmbiguousBaseSubobjects)));
Alp Tokerc1086762013-12-07 13:51:35 +0000332 return true;
John McCall19c1bfd2010-08-25 05:32:35 +0000333}
John McCall19c1bfd2010-08-25 05:32:35 +0000334
John McCall9f3059a2009-10-09 21:13:30 +0000335// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000336void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000337 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000338}
339
Richard Smith3876cc82013-10-30 01:02:04 +0000340/// Get a representative context for a declaration such that two declarations
341/// will have the same context if they were found within the same scope.
Benjamin Kramerfc58b042013-11-01 11:50:55 +0000342static DeclContext *getContextForScopeMatching(Decl *D) {
Richard Smith3876cc82013-10-30 01:02:04 +0000343 // For function-local declarations, use that function as the context. This
344 // doesn't account for scopes within the function; the caller must deal with
345 // those.
346 DeclContext *DC = D->getLexicalDeclContext();
347 if (DC->isFunctionOrMethod())
348 return DC;
349
350 // Otherwise, look at the semantic context of the declaration. The
351 // declaration must have been found there.
352 return D->getDeclContext()->getRedeclContext();
353}
354
John McCall283b9012009-11-22 00:44:51 +0000355/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000356void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000357 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000358
John McCall9f3059a2009-10-09 21:13:30 +0000359 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000360 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000361 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000362 return;
363 }
364
John McCall283b9012009-11-22 00:44:51 +0000365 // If there's a single decl, we need to examine it to decide what
366 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000367 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000368 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
369 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000370 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000371 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000372 ResultKind = FoundUnresolvedValue;
373 return;
374 }
John McCall9f3059a2009-10-09 21:13:30 +0000375
John McCall6538c932009-10-10 05:48:19 +0000376 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000377 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000378
John McCall9f3059a2009-10-09 21:13:30 +0000379 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor13e65872010-08-11 14:45:53 +0000380 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000381
John McCall9f3059a2009-10-09 21:13:30 +0000382 bool Ambiguous = false;
383 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000384 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000385
386 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000387
John McCall9f3059a2009-10-09 21:13:30 +0000388 unsigned I = 0;
389 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000390 NamedDecl *D = Decls[I]->getUnderlyingDecl();
391 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000392
Argyrios Kyrtzidis1fcd7fd2013-02-22 06:58:37 +0000393 // Ignore an invalid declaration unless it's the only one left.
394 if (D->isInvalidDecl() && I < N-1) {
395 Decls[I] = Decls[--N];
396 continue;
397 }
398
Douglas Gregor13e65872010-08-11 14:45:53 +0000399 // Redeclarations of types via typedef can occur both within a scope
400 // and, through using declarations and directives, across scopes. There is
401 // no ambiguity if they all refer to the same type, so unique based on the
402 // canonical type.
403 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
404 if (!TD->getDeclContext()->isRecord()) {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +0000405 QualType T = getSema().Context.getTypeDeclType(TD);
David Blaikie82e95a32014-11-19 07:49:47 +0000406 if (!UniqueTypes.insert(getSema().Context.getCanonicalType(T)).second) {
Douglas Gregor13e65872010-08-11 14:45:53 +0000407 // The type is not unique; pull something off the back and continue
408 // at this index.
409 Decls[I] = Decls[--N];
410 continue;
411 }
412 }
413 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000414
David Blaikie82e95a32014-11-19 07:49:47 +0000415 if (!Unique.insert(D).second) {
John McCall9f3059a2009-10-09 21:13:30 +0000416 // If it's not unique, pull something off the back (and
417 // continue at this index).
Richard Smithe8292b12015-02-10 03:28:10 +0000418 // FIXME: This is wrong. We need to take the more recent declaration in
Richard Smithfe620d22015-03-05 23:24:12 +0000419 // order to get the right type, default arguments, etc. We also need to
420 // prefer visible declarations to hidden ones (for redeclaration lookup
421 // in modules builds).
John McCall9f3059a2009-10-09 21:13:30 +0000422 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000423 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000424 }
425
Douglas Gregor13e65872010-08-11 14:45:53 +0000426 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000427
Douglas Gregor13e65872010-08-11 14:45:53 +0000428 if (isa<UnresolvedUsingValueDecl>(D)) {
429 HasUnresolved = true;
430 } else if (isa<TagDecl>(D)) {
431 if (HasTag)
432 Ambiguous = true;
433 UniqueTagIndex = I;
434 HasTag = true;
435 } else if (isa<FunctionTemplateDecl>(D)) {
436 HasFunction = true;
437 HasFunctionTemplate = true;
438 } else if (isa<FunctionDecl>(D)) {
439 HasFunction = true;
440 } else {
441 if (HasNonFunction)
442 Ambiguous = true;
443 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000444 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000445 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000446 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000447
John McCall9f3059a2009-10-09 21:13:30 +0000448 // C++ [basic.scope.hiding]p2:
449 // A class name or enumeration name can be hidden by the name of
450 // an object, function, or enumerator declared in the same
451 // scope. If a class or enumeration name and an object, function,
452 // or enumerator are declared in the same scope (in any order)
453 // with the same name, the class or enumeration name is hidden
454 // wherever the object, function, or enumerator name is visible.
455 // But it's still an error if there are distinct tag types found,
456 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000457 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000458 (HasFunction || HasNonFunction || HasUnresolved)) {
Richard Smith3876cc82013-10-30 01:02:04 +0000459 if (getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
460 getContextForScopeMatching(Decls[UniqueTagIndex ? 0 : N - 1])))
Douglas Gregore63d0872010-10-23 16:06:17 +0000461 Decls[UniqueTagIndex] = Decls[--N];
462 else
463 Ambiguous = true;
464 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000465
John McCall9f3059a2009-10-09 21:13:30 +0000466 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000467
John McCall80053822009-12-03 00:58:24 +0000468 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000469 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000470
John McCall9f3059a2009-10-09 21:13:30 +0000471 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000472 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000473 else if (HasUnresolved)
474 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000475 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000476 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000477 else
John McCall27b18f82009-11-17 02:14:36 +0000478 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000479}
480
John McCall5cebab12009-11-18 07:57:50 +0000481void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000482 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000483 for (I = P.begin(), E = P.end(); I != E; ++I)
David Blaikieff7d47a2012-12-19 00:45:41 +0000484 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
485 DE = I->Decls.end(); DI != DE; ++DI)
John McCall9f3059a2009-10-09 21:13:30 +0000486 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000487}
488
John McCall5cebab12009-11-18 07:57:50 +0000489void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000490 Paths = new CXXBasePaths;
491 Paths->swap(P);
492 addDeclsFromBasePaths(*Paths);
493 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000494 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000495}
496
John McCall5cebab12009-11-18 07:57:50 +0000497void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000498 Paths = new CXXBasePaths;
499 Paths->swap(P);
500 addDeclsFromBasePaths(*Paths);
501 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000502 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000503}
504
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000505void LookupResult::print(raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000506 Out << Decls.size() << " result(s)";
507 if (isAmbiguous()) Out << ", ambiguous";
508 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000509
John McCall9f3059a2009-10-09 21:13:30 +0000510 for (iterator I = begin(), E = end(); I != E; ++I) {
511 Out << "\n";
512 (*I)->print(Out, 2);
513 }
514}
515
Douglas Gregord3a59182010-02-12 05:48:04 +0000516/// \brief Lookup a builtin function, when name lookup would otherwise
517/// fail.
518static bool LookupBuiltin(Sema &S, LookupResult &R) {
519 Sema::LookupNameKind NameKind = R.getLookupKind();
520
521 // If we didn't find a use of this identifier, and if the identifier
522 // corresponds to a compiler builtin, create the decl object for the builtin
523 // now, injecting it into translation unit scope, and return it.
524 if (NameKind == Sema::LookupOrdinaryName ||
525 NameKind == Sema::LookupRedeclarationWithLinkage) {
526 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
527 if (II) {
Nico Webere1687c52013-06-20 21:44:55 +0000528 if (S.getLangOpts().CPlusPlus11 && S.getLangOpts().GNUMode &&
529 II == S.getFloat128Identifier()) {
530 // libstdc++4.7's type_traits expects type __float128 to exist, so
531 // insert a dummy type to make that header build in gnu++11 mode.
532 R.addDecl(S.getASTContext().getFloat128StubType());
533 return true;
534 }
535
Douglas Gregord3a59182010-02-12 05:48:04 +0000536 // If this is a builtin on this (or all) targets, create the decl.
537 if (unsigned BuiltinID = II->getBuiltinID()) {
538 // In C++, we don't have any predefined library functions like
539 // 'malloc'. Instead, we'll just error.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000540 if (S.getLangOpts().CPlusPlus &&
Douglas Gregord3a59182010-02-12 05:48:04 +0000541 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
542 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000543
544 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
545 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000546 R.isForRedeclaration(),
547 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000548 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000549 return true;
550 }
Douglas Gregord3a59182010-02-12 05:48:04 +0000551 }
552 }
553 }
554
555 return false;
556}
557
Douglas Gregor7454c562010-07-02 20:37:36 +0000558/// \brief Determine whether we can declare a special member function within
559/// the class at this point.
Richard Smith7d125a12012-11-27 21:20:31 +0000560static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +0000561 // We need to have a definition for the class.
562 if (!Class->getDefinition() || Class->isDependentContext())
563 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000564
Douglas Gregor7454c562010-07-02 20:37:36 +0000565 // We can't be in the middle of defining the class.
Richard Smith7d125a12012-11-27 21:20:31 +0000566 return !Class->isBeingDefined();
Douglas Gregor7454c562010-07-02 20:37:36 +0000567}
568
569void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smith7d125a12012-11-27 21:20:31 +0000570 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregora6d69502010-07-02 23:41:54 +0000571 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000572
573 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000574 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000575 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000576
Douglas Gregora6d69502010-07-02 23:41:54 +0000577 // If the copy constructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000578 if (Class->needsImplicitCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +0000579 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000580
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000581 // If the copy assignment operator has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000582 if (Class->needsImplicitCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000583 DeclareImplicitCopyAssignment(Class);
584
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000585 if (getLangOpts().CPlusPlus11) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000586 // If the move constructor has not yet been declared, do so now.
587 if (Class->needsImplicitMoveConstructor())
588 DeclareImplicitMoveConstructor(Class); // might not actually do it
589
590 // If the move assignment operator has not yet been declared, do so now.
591 if (Class->needsImplicitMoveAssignment())
592 DeclareImplicitMoveAssignment(Class); // might not actually do it
593 }
594
Douglas Gregor7454c562010-07-02 20:37:36 +0000595 // If the destructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000596 if (Class->needsImplicitDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000597 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000598}
599
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000600/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000601/// special member function.
602static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
603 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000604 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000605 case DeclarationName::CXXDestructorName:
606 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000607
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000608 case DeclarationName::CXXOperatorName:
609 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000610
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000611 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000612 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000613 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000614
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000615 return false;
616}
617
618/// \brief If there are any implicit member functions with the given name
619/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000620static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000621 DeclarationName Name,
622 const DeclContext *DC) {
623 if (!DC)
624 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000625
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000626 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000627 case DeclarationName::CXXConstructorName:
628 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith7d125a12012-11-27 21:20:31 +0000629 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000630 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000631 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000632 S.DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +0000633 if (Record->needsImplicitCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000634 S.DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000635 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000636 Record->needsImplicitMoveConstructor())
637 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000638 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000639 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000640
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000641 case DeclarationName::CXXDestructorName:
642 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith2be35f52012-12-01 02:35:44 +0000643 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smith7d125a12012-11-27 21:20:31 +0000644 CanDeclareSpecialMemberFunction(Record))
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000645 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000646 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000647
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000648 case DeclarationName::CXXOperatorName:
649 if (Name.getCXXOverloadedOperator() != OO_Equal)
650 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000651
Sebastian Redl22653ba2011-08-30 19:58:05 +0000652 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smith7d125a12012-11-27 21:20:31 +0000653 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000654 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smith2be35f52012-12-01 02:35:44 +0000655 if (Record->needsImplicitCopyAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000656 S.DeclareImplicitCopyAssignment(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000657 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000658 Record->needsImplicitMoveAssignment())
659 S.DeclareImplicitMoveAssignment(Class);
660 }
661 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000662 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000663
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000664 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000665 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000666 }
667}
Douglas Gregor7454c562010-07-02 20:37:36 +0000668
John McCall9f3059a2009-10-09 21:13:30 +0000669// Adds all qualifying matches for a name within a decl context to the
670// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000671static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000672 bool Found = false;
673
Douglas Gregor7454c562010-07-02 20:37:36 +0000674 // Lazily declare C++ special member functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000675 if (S.getLangOpts().CPlusPlus)
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000676 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000677
Douglas Gregor7454c562010-07-02 20:37:36 +0000678 // Perform lookup into this declaration context.
Richard Smithcf4bdde2015-02-21 02:45:19 +0000679 DeclContext::lookup_result DR = DC->lookup(R.getLookupName());
680 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E;
David Blaikieff7d47a2012-12-19 00:45:41 +0000681 ++I) {
John McCall401982f2010-01-20 21:53:11 +0000682 NamedDecl *D = *I;
Douglas Gregor4a814562011-12-14 16:03:29 +0000683 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000684 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000685 Found = true;
686 }
687 }
John McCall9f3059a2009-10-09 21:13:30 +0000688
Douglas Gregord3a59182010-02-12 05:48:04 +0000689 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
690 return true;
691
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000692 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000693 != DeclarationName::CXXConversionFunctionName ||
694 R.getLookupName().getCXXNameType()->isDependentType() ||
695 !isa<CXXRecordDecl>(DC))
696 return Found;
697
698 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000699 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000700 // name lookup. Instead, any conversion function templates visible in the
701 // context of the use are considered. [...]
702 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000703 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000704 return Found;
705
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +0000706 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
707 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruth3a693b72010-01-31 11:44:02 +0000708 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
709 if (!ConvTemplate)
710 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000711
Chandler Carruth3a693b72010-01-31 11:44:02 +0000712 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000713 // add the conversion function template. When we deduce template
714 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000715 // type of the new declaration with the type of the function template.
716 if (R.isForRedeclaration()) {
717 R.addDecl(ConvTemplate);
718 Found = true;
719 continue;
720 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000721
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000722 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000723 // [...] For each such operator, if argument deduction succeeds
724 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000725 // name lookup.
726 //
727 // When referencing a conversion function for any purpose other than
728 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000729 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000730 // specialization into the result set. We do this to avoid forcing all
731 // callers to perform special deduction for conversion functions.
Craig Toppere6706e42012-09-19 02:26:47 +0000732 TemplateDeductionInfo Info(R.getNameLoc());
Craig Topperc3ec1492014-05-26 06:22:03 +0000733 FunctionDecl *Specialization = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000734
735 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000736 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
737 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000738
Chandler Carruth3a693b72010-01-31 11:44:02 +0000739 // Compute the type of the function that we would expect the conversion
740 // function to have, if it were to match the name given.
741 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000742 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
Reid Kleckner78af0702013-08-27 23:08:25 +0000743 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
Richard Smith8acb4282014-07-31 21:57:55 +0000744 EPI.ExceptionSpec = EST_None;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000745 QualType ExpectedType
746 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000747 None, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000748
Chandler Carruth3a693b72010-01-31 11:44:02 +0000749 // Perform template argument deduction against the type that we would
750 // expect the function to have.
Craig Topperc3ec1492014-05-26 06:22:03 +0000751 if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
Chandler Carruth3a693b72010-01-31 11:44:02 +0000752 Specialization, Info)
753 == Sema::TDK_Success) {
754 R.addDecl(Specialization);
755 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000756 }
757 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000758
John McCall9f3059a2009-10-09 21:13:30 +0000759 return Found;
760}
761
John McCallf6c8a4e2009-11-10 07:01:13 +0000762// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000763static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000764CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000765 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000766
767 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
768
John McCallf6c8a4e2009-11-10 07:01:13 +0000769 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000770 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000771
John McCallf6c8a4e2009-11-10 07:01:13 +0000772 // Perform direct name lookup into the namespaces nominated by the
773 // using directives whose common ancestor is this namespace.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000774 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
775 if (LookupDirect(S, R, UUE.getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000776 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000777
778 R.resolveKind();
779
780 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000781}
782
783static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000784 if (DeclContext *Ctx = S->getEntity())
Douglas Gregor700792c2009-02-05 19:25:20 +0000785 return Ctx->isFileContext();
786 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000787}
Douglas Gregored8f2882009-01-30 01:04:22 +0000788
Douglas Gregor66230062010-03-15 14:33:29 +0000789// Find the next outer declaration context from this scope. This
790// routine actually returns the semantic outer context, which may
791// differ from the lexical context (encoded directly in the Scope
792// stack) when we are parsing a member of a class template. In this
793// case, the second element of the pair will be true, to indicate that
794// name lookup should continue searching in this semantic context when
795// it leaves the current template parameter scope.
796static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000797 DeclContext *DC = S->getEntity();
Craig Topperc3ec1492014-05-26 06:22:03 +0000798 DeclContext *Lexical = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000799 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000800 OuterS = OuterS->getParent()) {
801 if (OuterS->getEntity()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000802 Lexical = OuterS->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +0000803 break;
804 }
805 }
806
807 // C++ [temp.local]p8:
808 // In the definition of a member of a class template that appears
809 // outside of the namespace containing the class template
810 // definition, the name of a template-parameter hides the name of
811 // a member of this namespace.
812 //
813 // Example:
814 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000815 // namespace N {
816 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000817 //
818 // template<class T> class B {
819 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000820 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000821 // }
822 //
823 // template<class C> void N::B<C>::f(C) {
824 // C b; // C is the template parameter, not N::C
825 // }
826 //
827 // In this example, the lexical context we return is the
828 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000829 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000830 !S->getParent()->isTemplateParamScope())
831 return std::make_pair(Lexical, false);
832
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000833 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000834 // For the example, this is the scope for the template parameters of
835 // template<class C>.
836 Scope *OutermostTemplateScope = S->getParent();
837 while (OutermostTemplateScope->getParent() &&
838 OutermostTemplateScope->getParent()->isTemplateParamScope())
839 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000840
Douglas Gregor66230062010-03-15 14:33:29 +0000841 // Find the namespace context in which the original scope occurs. In
842 // the example, this is namespace N.
843 DeclContext *Semantic = DC;
844 while (!Semantic->isFileContext())
845 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000846
Douglas Gregor66230062010-03-15 14:33:29 +0000847 // Find the declaration context just outside of the template
848 // parameter scope. This is the context in which the template is
849 // being lexically declaration (a namespace context). In the
850 // example, this is the global scope.
851 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
852 Lexical->Encloses(Semantic))
853 return std::make_pair(Semantic, true);
854
855 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000856}
857
Richard Smith541b38b2013-09-20 01:15:31 +0000858namespace {
859/// An RAII object to specify that we want to find block scope extern
860/// declarations.
861struct FindLocalExternScope {
862 FindLocalExternScope(LookupResult &R)
863 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
864 Decl::IDNS_LocalExtern) {
865 R.setFindLocalExtern(R.getIdentifierNamespace() & Decl::IDNS_Ordinary);
866 }
867 void restore() {
868 R.setFindLocalExtern(OldFindLocalExtern);
869 }
870 ~FindLocalExternScope() {
871 restore();
872 }
873 LookupResult &R;
874 bool OldFindLocalExtern;
875};
876}
877
John McCall27b18f82009-11-17 02:14:36 +0000878bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000879 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000880
881 DeclarationName Name = R.getLookupName();
Richard Smith1c34fb72013-08-13 18:18:50 +0000882 Sema::LookupNameKind NameKind = R.getLookupKind();
John McCall27b18f82009-11-17 02:14:36 +0000883
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000884 // If this is the name of an implicitly-declared special member function,
885 // go through the scope stack to implicitly declare
886 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
887 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +0000888 if (DeclContext *DC = PreS->getEntity())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000889 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
890 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000891
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000892 // Implicitly declare member functions with the name we're looking for, if in
893 // fact we are in a scope where it matters.
894
Douglas Gregor889ceb72009-02-03 19:21:40 +0000895 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000896 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000897 I = IdResolver.begin(Name),
898 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000899
Douglas Gregor889ceb72009-02-03 19:21:40 +0000900 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000901 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000902 // ...During unqualified name lookup (3.4.1), the names appear as if
903 // they were declared in the nearest enclosing namespace which contains
904 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000905 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000906 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000907 //
908 // For example:
909 // namespace A { int i; }
910 // void foo() {
911 // int i;
912 // {
913 // using namespace A;
914 // ++i; // finds local 'i', A::i appears at global scope
915 // }
916 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000917 //
Douglas Gregorcc9406c2013-04-08 23:11:25 +0000918 UnqualUsingDirectiveSet UDirs;
919 bool VisitedUsingDirectives = false;
Richard Smith1c34fb72013-08-13 18:18:50 +0000920 bool LeftStartingScope = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000921 DeclContext *OutsideOfTemplateParamDC = nullptr;
Richard Smith541b38b2013-09-20 01:15:31 +0000922
923 // When performing a scope lookup, we want to find local extern decls.
924 FindLocalExternScope FindLocals(R);
925
Douglas Gregor700792c2009-02-05 19:25:20 +0000926 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000927 DeclContext *Ctx = S->getEntity();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000928
Douglas Gregor889ceb72009-02-03 19:21:40 +0000929 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000930 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000931 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000932 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Richard Smith1c34fb72013-08-13 18:18:50 +0000933 if (NameKind == LookupRedeclarationWithLinkage) {
934 // Determine whether this (or a previous) declaration is
935 // out-of-scope.
936 if (!LeftStartingScope && !Initial->isDeclScope(*I))
937 LeftStartingScope = true;
938
939 // If we found something outside of our starting scope that
Richard Smith9a00bbf2013-10-16 21:12:00 +0000940 // does not have linkage, skip it. If it's a template parameter,
941 // we still find it, so we can diagnose the invalid redeclaration.
942 if (LeftStartingScope && !((*I)->hasLinkage()) &&
943 !(*I)->isTemplateParameter()) {
Richard Smith1c34fb72013-08-13 18:18:50 +0000944 R.setShadowed();
945 continue;
946 }
947 }
948
John McCall9f3059a2009-10-09 21:13:30 +0000949 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +0000950 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000951 }
952 }
John McCall9f3059a2009-10-09 21:13:30 +0000953 if (Found) {
954 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000955 if (S->isClassScope())
956 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
957 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000958 return true;
959 }
960
Richard Smith1c34fb72013-08-13 18:18:50 +0000961 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
Richard Smith114394f2013-08-09 04:35:01 +0000962 // C++11 [class.friend]p11:
963 // If a friend declaration appears in a local class and the name
964 // specified is an unqualified name, a prior declaration is
965 // looked up without considering scopes that are outside the
966 // innermost enclosing non-class scope.
967 return false;
968 }
969
Douglas Gregor66230062010-03-15 14:33:29 +0000970 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
971 S->getParent() && !S->getParent()->isTemplateParamScope()) {
972 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000973 // found nothing, so look into the contexts between the
Douglas Gregor66230062010-03-15 14:33:29 +0000974 // lexical and semantic declaration contexts returned by
975 // findOuterContext(). This implements the name lookup behavior
976 // of C++ [temp.local]p8.
977 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +0000978 OutsideOfTemplateParamDC = nullptr;
Douglas Gregor66230062010-03-15 14:33:29 +0000979 }
980
981 if (Ctx) {
982 DeclContext *OuterCtx;
983 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000984 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregor66230062010-03-15 14:33:29 +0000985 if (SearchAfterTemplateScope)
986 OutsideOfTemplateParamDC = OuterCtx;
987
Douglas Gregorea166062010-03-15 15:26:48 +0000988 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000989 // We do not directly look into transparent contexts, since
990 // those entities will be found in the nearest enclosing
991 // non-transparent context.
992 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000993 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000994
995 // We do not look directly into function or method contexts,
996 // since all of the local variables and parameters of the
997 // function/method are present within the Scope.
998 if (Ctx->isFunctionOrMethod()) {
999 // If we have an Objective-C instance method, look for ivars
1000 // in the corresponding interface.
1001 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
1002 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1003 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1004 ObjCInterfaceDecl *ClassDeclared;
1005 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001006 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +00001007 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001008 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1009 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +00001010 R.resolveKind();
1011 return true;
1012 }
1013 }
1014 }
1015 }
1016
1017 continue;
1018 }
1019
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001020 // If this is a file context, we need to perform unqualified name
1021 // lookup considering using directives.
1022 if (Ctx->isFileContext()) {
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001023 // If we haven't handled using directives yet, do so now.
1024 if (!VisitedUsingDirectives) {
1025 // Add using directives from this context up to the top level.
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001026 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1027 if (UCtx->isTransparentContext())
1028 continue;
1029
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001030 UDirs.visit(UCtx, UCtx);
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001031 }
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001032
1033 // Find the innermost file scope, so we can add using directives
1034 // from local scopes.
1035 Scope *InnermostFileScope = S;
1036 while (InnermostFileScope &&
1037 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1038 InnermostFileScope = InnermostFileScope->getParent();
1039 UDirs.visitScopeChain(Initial, InnermostFileScope);
1040
1041 UDirs.done();
1042
1043 VisitedUsingDirectives = true;
1044 }
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001045
1046 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1047 R.resolveKind();
1048 return true;
1049 }
1050
1051 continue;
1052 }
1053
Douglas Gregor7f737c02009-09-10 16:57:35 +00001054 // Perform qualified name lookup into this context.
1055 // FIXME: In some cases, we know that every name that could be found by
1056 // this qualified name lookup will also be on the identifier chain. For
1057 // example, inside a class without any base classes, we never need to
1058 // perform qualified lookup because all of the members are on top of the
1059 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001060 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +00001061 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +00001062 }
Douglas Gregor700792c2009-02-05 19:25:20 +00001063 }
Douglas Gregored8f2882009-01-30 01:04:22 +00001064 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001065
John McCallf6c8a4e2009-11-10 07:01:13 +00001066 // Stop if we ran out of scopes.
1067 // FIXME: This really, really shouldn't be happening.
1068 if (!S) return false;
1069
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001070 // If we are looking for members, no need to look into global/namespace scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00001071 if (NameKind == LookupMemberName)
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001072 return false;
1073
Douglas Gregor700792c2009-02-05 19:25:20 +00001074 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +00001075 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +00001076 //
Mike Stump87c57ac2009-05-16 07:39:55 +00001077 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1078 // don't build it for each lookup!
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001079 if (!VisitedUsingDirectives) {
1080 UDirs.visitScopeChain(Initial, S);
1081 UDirs.done();
1082 }
Richard Smith541b38b2013-09-20 01:15:31 +00001083
1084 // If we're not performing redeclaration lookup, do not look for local
1085 // extern declarations outside of a function scope.
1086 if (!R.isForRedeclaration())
1087 FindLocals.restore();
1088
Douglas Gregor700792c2009-02-05 19:25:20 +00001089 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +00001090 // Unqualified name lookup in C++ requires looking into scopes
1091 // that aren't strictly lexical, and therefore we walk through the
1092 // context as well as walking through the scopes.
1093 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001094 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +00001095 bool Found = false;
John McCall48871652010-08-21 09:40:31 +00001096 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001097 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001098 // We found something. Look for anything else in our scope
1099 // with this same name and in an acceptable identifier
1100 // namespace, so that we can construct an overload set if we
1101 // need to.
John McCall9f3059a2009-10-09 21:13:30 +00001102 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +00001103 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001104 }
1105 }
1106
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001107 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +00001108 R.resolveKind();
1109 return true;
1110 }
1111
Ted Kremenekc37877d2013-10-08 17:08:03 +00001112 DeclContext *Ctx = S->getEntity();
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001113 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1114 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1115 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001116 // found nothing, so look into the contexts between the
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001117 // lexical and semantic declaration contexts returned by
1118 // findOuterContext(). This implements the name lookup behavior
1119 // of C++ [temp.local]p8.
1120 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +00001121 OutsideOfTemplateParamDC = nullptr;
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001122 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001123
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001124 if (Ctx) {
1125 DeclContext *OuterCtx;
1126 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001127 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001128 if (SearchAfterTemplateScope)
1129 OutsideOfTemplateParamDC = OuterCtx;
1130
1131 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1132 // We do not directly look into transparent contexts, since
1133 // those entities will be found in the nearest enclosing
1134 // non-transparent context.
1135 if (Ctx->isTransparentContext())
1136 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001137
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001138 // If we have a context, and it's not a context stashed in the
1139 // template parameter scope for an out-of-line definition, also
1140 // look into that context.
1141 if (!(Found && S && S->isTemplateParamScope())) {
1142 assert(Ctx->isFileContext() &&
1143 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001144
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001145 // Look into context considering using-directives.
1146 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1147 Found = true;
1148 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001149
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001150 if (Found) {
1151 R.resolveKind();
1152 return true;
1153 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001154
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001155 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1156 return false;
1157 }
1158 }
1159
Douglas Gregor3ce74932010-02-05 07:07:10 +00001160 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001161 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001162 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001163
John McCall9f3059a2009-10-09 21:13:30 +00001164 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001165}
1166
Richard Smith0e5d7b82013-07-25 23:08:39 +00001167/// \brief Find the declaration that a class temploid member specialization was
1168/// instantiated from, or the member itself if it is an explicit specialization.
1169static Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) {
1170 return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom();
1171}
1172
Richard Smithd9ba2242015-05-07 03:54:19 +00001173void Sema::makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc) {
1174 if (auto *Listener = getASTMutationListener())
1175 Listener->RedefinedHiddenDefinition(ND, Loc);
1176 ND->setHidden(false);
1177}
1178
Richard Smith0e5d7b82013-07-25 23:08:39 +00001179/// \brief Find the module in which the given declaration was defined.
1180static Module *getDefiningModule(Decl *Entity) {
1181 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1182 // If this function was instantiated from a template, the defining module is
1183 // the module containing the pattern.
1184 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1185 Entity = Pattern;
1186 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
Reid Klecknere7367d62014-10-14 20:28:40 +00001187 if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
1188 Entity = Pattern;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001189 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1190 if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo())
1191 Entity = getInstantiatedFrom(ED, MSInfo);
1192 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1193 // FIXME: Map from variable template specializations back to the template.
1194 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo())
1195 Entity = getInstantiatedFrom(VD, MSInfo);
1196 }
1197
1198 // Walk up to the containing context. That might also have been instantiated
1199 // from a template.
1200 DeclContext *Context = Entity->getDeclContext();
1201 if (Context->isFileContext())
1202 return Entity->getOwningModule();
1203 return getDefiningModule(cast<Decl>(Context));
1204}
1205
1206llvm::DenseSet<Module*> &Sema::getLookupModules() {
1207 unsigned N = ActiveTemplateInstantiations.size();
1208 for (unsigned I = ActiveTemplateInstantiationLookupModules.size();
1209 I != N; ++I) {
1210 Module *M = getDefiningModule(ActiveTemplateInstantiations[I].Entity);
1211 if (M && !LookupModulesCache.insert(M).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00001212 M = nullptr;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001213 ActiveTemplateInstantiationLookupModules.push_back(M);
1214 }
1215 return LookupModulesCache;
1216}
1217
1218/// \brief Determine whether a declaration is visible to name lookup.
1219///
1220/// This routine determines whether the declaration D is visible in the current
1221/// lookup context, taking into account the current template instantiation
1222/// stack. During template instantiation, a declaration is visible if it is
1223/// visible from a module containing any entity on the template instantiation
1224/// path (by instantiating a template, you allow it to see the declarations that
1225/// your module can see, including those later on in your module).
1226bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001227 assert(D->isHidden() && "should not call this: not in slow case");
Richard Smith0e5d7b82013-07-25 23:08:39 +00001228 Module *DeclModule = D->getOwningModule();
1229 assert(DeclModule && "hidden decl not from a module");
1230
Richard Smithbe3980b2015-03-27 00:41:57 +00001231 // If this declaration is not at namespace scope nor module-private,
1232 // then it is visible if its lexical parent has a visible definition.
1233 DeclContext *DC = D->getLexicalDeclContext();
1234 if (!D->isModulePrivate() &&
1235 DC && !DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) {
Richard Smith9a71c992015-03-27 20:16:58 +00001236 if (SemaRef.hasVisibleDefinition(cast<NamedDecl>(DC))) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001237 if (SemaRef.ActiveTemplateInstantiations.empty()) {
1238 // Cache the fact that this declaration is implicitly visible because
1239 // its parent has a visible definition.
1240 D->setHidden(false);
1241 }
1242 return true;
1243 }
1244 return false;
1245 }
1246
Richard Smith0e5d7b82013-07-25 23:08:39 +00001247 // Find the extra places where we need to look.
1248 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
1249 if (LookupModules.empty())
1250 return false;
1251
1252 // If our lookup set contains the decl's module, it's visible.
1253 if (LookupModules.count(DeclModule))
1254 return true;
1255
1256 // If the declaration isn't exported, it's not visible in any other module.
1257 if (D->isModulePrivate())
1258 return false;
1259
1260 // Check whether DeclModule is transitively exported to an import of
1261 // the lookup set.
1262 for (llvm::DenseSet<Module *>::iterator I = LookupModules.begin(),
1263 E = LookupModules.end();
1264 I != E; ++I)
1265 if ((*I)->isModuleVisible(DeclModule))
1266 return true;
1267 return false;
1268}
1269
Douglas Gregor4a814562011-12-14 16:03:29 +00001270/// \brief Retrieve the visible declaration corresponding to D, if any.
1271///
1272/// This routine determines whether the declaration D is visible in the current
1273/// module, with the current imports. If not, it checks whether any
1274/// redeclaration of D is visible, and if so, returns that declaration.
Richard Smith0e5d7b82013-07-25 23:08:39 +00001275///
Douglas Gregor4a814562011-12-14 16:03:29 +00001276/// \returns D, or a visible previous declaration of D, whichever is more recent
1277/// and visible. If no declaration of D is visible, returns null.
Richard Smithe156254d2013-08-20 20:35:18 +00001278static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
1279 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
Richard Smith0e5d7b82013-07-25 23:08:39 +00001280
Aaron Ballman86c93902014-03-06 23:45:36 +00001281 for (auto RD : D->redecls()) {
1282 if (auto ND = dyn_cast<NamedDecl>(RD)) {
Richard Smithe8292b12015-02-10 03:28:10 +00001283 // FIXME: This is wrong in the case where the previous declaration is not
1284 // visible in the same scope as D. This needs to be done much more
1285 // carefully.
Richard Smithe156254d2013-08-20 20:35:18 +00001286 if (LookupResult::isVisible(SemaRef, ND))
Douglas Gregor54079202012-01-06 22:05:37 +00001287 return ND;
1288 }
Douglas Gregor4a814562011-12-14 16:03:29 +00001289 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001290
Craig Topperc3ec1492014-05-26 06:22:03 +00001291 return nullptr;
Douglas Gregor4a814562011-12-14 16:03:29 +00001292}
1293
Richard Smithe156254d2013-08-20 20:35:18 +00001294NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
Kaelyn Takatafc8c61a2014-11-11 23:00:42 +00001295 return findAcceptableDecl(getSema(), D);
Richard Smithe156254d2013-08-20 20:35:18 +00001296}
1297
Douglas Gregor34074322009-01-14 22:20:51 +00001298/// @brief Perform unqualified name lookup starting from a given
1299/// scope.
1300///
1301/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1302/// used to find names within the current scope. For example, 'x' in
1303/// @code
1304/// int x;
1305/// int f() {
1306/// return x; // unqualified name look finds 'x' in the global scope
1307/// }
1308/// @endcode
1309///
1310/// Different lookup criteria can find different names. For example, a
1311/// particular scope can have both a struct and a function of the same
1312/// name, and each can be found by certain lookup criteria. For more
1313/// information about lookup criteria, see the documentation for the
1314/// class LookupCriteria.
1315///
1316/// @param S The scope from which unqualified name lookup will
1317/// begin. If the lookup criteria permits, name lookup may also search
1318/// in the parent scopes.
1319///
James Dennett91738ff2012-06-22 10:32:46 +00001320/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1321/// look up and the lookup kind), and is updated with the results of lookup
1322/// including zero or more declarations and possibly additional information
1323/// used to diagnose ambiguities.
Douglas Gregor34074322009-01-14 22:20:51 +00001324///
James Dennett91738ff2012-06-22 10:32:46 +00001325/// @returns \c true if lookup succeeded and false otherwise.
John McCall27b18f82009-11-17 02:14:36 +00001326bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1327 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001328 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001329
John McCall27b18f82009-11-17 02:14:36 +00001330 LookupNameKind NameKind = R.getLookupKind();
1331
David Blaikiebbafb8a2012-03-11 07:00:24 +00001332 if (!getLangOpts().CPlusPlus) {
Douglas Gregor34074322009-01-14 22:20:51 +00001333 // Unqualified name lookup in C/Objective-C is purely lexical, so
1334 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001335 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001336 // Find the nearest non-transparent declaration scope.
1337 while (!(S->getFlags() & Scope::DeclScope) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001338 (S->getEntity() && S->getEntity()->isTransparentContext()))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001339 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001340 }
1341
Richard Smith541b38b2013-09-20 01:15:31 +00001342 // When performing a scope lookup, we want to find local extern decls.
1343 FindLocalExternScope FindLocals(R);
1344
Douglas Gregor34074322009-01-14 22:20:51 +00001345 // Scan up the scope chain looking for a decl that matches this
1346 // identifier that is in the appropriate namespace. This search
1347 // should not take long, as shadowing of names is uncommon, and
1348 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001349 bool LeftStartingScope = false;
1350
Douglas Gregored8f2882009-01-30 01:04:22 +00001351 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001352 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001353 I != IEnd; ++I)
Richard Smith0e5d7b82013-07-25 23:08:39 +00001354 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001355 if (NameKind == LookupRedeclarationWithLinkage) {
1356 // Determine whether this (or a previous) declaration is
1357 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001358 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001359 LeftStartingScope = true;
1360
1361 // If we found something outside of our starting scope that
1362 // does not have linkage, skip it.
Richard Smith1c34fb72013-08-13 18:18:50 +00001363 if (LeftStartingScope && !((*I)->hasLinkage())) {
1364 R.setShadowed();
Douglas Gregoreddf4332009-02-24 20:03:32 +00001365 continue;
Richard Smith1c34fb72013-08-13 18:18:50 +00001366 }
Douglas Gregoreddf4332009-02-24 20:03:32 +00001367 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001368 else if (NameKind == LookupObjCImplicitSelfParam &&
1369 !isa<ImplicitParamDecl>(*I))
1370 continue;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001371
Douglas Gregor4a814562011-12-14 16:03:29 +00001372 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001373
Douglas Gregorb59643b2012-01-03 23:26:26 +00001374 // Check whether there are any other declarations with the same name
1375 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001376 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001377 // Find the scope in which this declaration was declared (if it
1378 // actually exists in a Scope).
1379 while (S && !S->isDeclScope(D))
1380 S = S->getParent();
1381
1382 // If the scope containing the declaration is the translation unit,
1383 // then we'll need to perform our checks based on the matching
1384 // DeclContexts rather than matching scopes.
1385 if (S && isNamespaceOrTranslationUnitScope(S))
Craig Topperc3ec1492014-05-26 06:22:03 +00001386 S = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001387
1388 // Compute the DeclContext, if we need it.
Craig Topperc3ec1492014-05-26 06:22:03 +00001389 DeclContext *DC = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001390 if (!S)
1391 DC = (*I)->getDeclContext()->getRedeclContext();
1392
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001393 IdentifierResolver::iterator LastI = I;
1394 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001395 if (S) {
1396 // Match based on scope.
1397 if (!S->isDeclScope(*LastI))
1398 break;
1399 } else {
1400 // Match based on DeclContext.
1401 DeclContext *LastDC
1402 = (*LastI)->getDeclContext()->getRedeclContext();
1403 if (!LastDC->Equals(DC))
1404 break;
1405 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001406
1407 // If the declaration is in the right namespace and visible, add it.
1408 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1409 R.addDecl(LastD);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001410 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001411
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001412 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001413 }
Richard Smith541b38b2013-09-20 01:15:31 +00001414
John McCall9f3059a2009-10-09 21:13:30 +00001415 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001416 }
Douglas Gregor34074322009-01-14 22:20:51 +00001417 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001418 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001419 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001420 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001421 }
1422
1423 // If we didn't find a use of this identifier, and if the identifier
1424 // corresponds to a compiler builtin, create the decl object for the builtin
1425 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001426 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1427 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001428
Axel Naumann016538a2011-02-24 16:47:47 +00001429 // If we didn't find a use of this identifier, the ExternalSource
1430 // may be able to handle the situation.
1431 // Note: some lookup failures are expected!
1432 // See e.g. R.isForRedeclaration().
1433 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001434}
1435
John McCall6538c932009-10-10 05:48:19 +00001436/// @brief Perform qualified name lookup in the namespaces nominated by
1437/// using directives by the given context.
1438///
1439/// C++98 [namespace.qual]p2:
James Dennett51a8d8b2012-06-19 21:05:49 +00001440/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6538c932009-10-10 05:48:19 +00001441/// (where X is the global namespace), let S be the set of all
1442/// declarations of m in X and in the transitive closure of all
1443/// namespaces nominated by using-directives in X and its used
1444/// namespaces, except that using-directives are ignored in any
1445/// namespace, including X, directly containing one or more
1446/// declarations of m. No namespace is searched more than once in
1447/// the lookup of a name. If S is the empty set, the program is
1448/// ill-formed. Otherwise, if S has exactly one member, or if the
1449/// context of the reference is a using-declaration
1450/// (namespace.udecl), S is the required set of declarations of
1451/// m. Otherwise if the use of m is not one that allows a unique
1452/// declaration to be chosen from S, the program is ill-formed.
James Dennett51a8d8b2012-06-19 21:05:49 +00001453///
John McCall6538c932009-10-10 05:48:19 +00001454/// C++98 [namespace.qual]p5:
1455/// During the lookup of a qualified namespace member name, if the
1456/// lookup finds more than one declaration of the member, and if one
1457/// declaration introduces a class name or enumeration name and the
1458/// other declarations either introduce the same object, the same
1459/// enumerator or a set of functions, the non-type name hides the
1460/// class or enumeration name if and only if the declarations are
1461/// from the same namespace; otherwise (the declarations are from
1462/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001463static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001464 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001465 assert(StartDC->isFileContext() && "start context is not a file context");
1466
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001467 DeclContext::udir_range UsingDirectives = StartDC->using_directives();
1468 if (UsingDirectives.begin() == UsingDirectives.end()) return false;
John McCall6538c932009-10-10 05:48:19 +00001469
1470 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001471 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001472 Visited.insert(StartDC);
1473
1474 // We have not yet looked into these namespaces, much less added
1475 // their "using-children" to the queue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001476 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001477
1478 // We have already looked into the initial namespace; seed the queue
1479 // with its using-children.
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001480 for (auto *I : UsingDirectives) {
1481 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +00001482 if (Visited.insert(ND).second)
John McCall6538c932009-10-10 05:48:19 +00001483 Queue.push_back(ND);
1484 }
1485
1486 // The easiest way to implement the restriction in [namespace.qual]p5
1487 // is to check whether any of the individual results found a tag
1488 // and, if so, to declare an ambiguity if the final result is not
1489 // a tag.
1490 bool FoundTag = false;
1491 bool FoundNonTag = false;
1492
John McCall5cebab12009-11-18 07:57:50 +00001493 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001494
1495 bool Found = false;
1496 while (!Queue.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001497 NamespaceDecl *ND = Queue.pop_back_val();
John McCall6538c932009-10-10 05:48:19 +00001498
1499 // We go through some convolutions here to avoid copying results
1500 // between LookupResults.
1501 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001502 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001503 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001504
1505 if (FoundDirect) {
1506 // First do any local hiding.
1507 DirectR.resolveKind();
1508
1509 // If the local result is a tag, remember that.
1510 if (DirectR.isSingleTagDecl())
1511 FoundTag = true;
1512 else
1513 FoundNonTag = true;
1514
1515 // Append the local results to the total results if necessary.
1516 if (UseLocal) {
1517 R.addAllDecls(LocalR);
1518 LocalR.clear();
1519 }
1520 }
1521
1522 // If we find names in this namespace, ignore its using directives.
1523 if (FoundDirect) {
1524 Found = true;
1525 continue;
1526 }
1527
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001528 for (auto I : ND->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00001529 NamespaceDecl *Nom = I->getNominatedNamespace();
David Blaikie82e95a32014-11-19 07:49:47 +00001530 if (Visited.insert(Nom).second)
John McCall6538c932009-10-10 05:48:19 +00001531 Queue.push_back(Nom);
1532 }
1533 }
1534
1535 if (Found) {
1536 if (FoundTag && FoundNonTag)
1537 R.setAmbiguousQualifiedTagHiding();
1538 else
1539 R.resolveKind();
1540 }
1541
1542 return Found;
1543}
1544
Douglas Gregor39982192010-08-15 06:18:01 +00001545/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001546static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor39982192010-08-15 06:18:01 +00001547 CXXBasePath &Path,
1548 void *Name) {
1549 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001550
Douglas Gregor39982192010-08-15 06:18:01 +00001551 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1552 Path.Decls = BaseRecord->lookup(N);
David Blaikieff7d47a2012-12-19 00:45:41 +00001553 return !Path.Decls.empty();
Douglas Gregor39982192010-08-15 06:18:01 +00001554}
1555
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001556/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001557/// static members, nested types, and enumerators.
1558template<typename InputIterator>
1559static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1560 Decl *D = (*First)->getUnderlyingDecl();
1561 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1562 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001563
Douglas Gregorc0d24902010-10-22 22:08:47 +00001564 if (isa<CXXMethodDecl>(D)) {
1565 // Determine whether all of the methods are static.
1566 bool AllMethodsAreStatic = true;
1567 for(; First != Last; ++First) {
1568 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001569
Douglas Gregorc0d24902010-10-22 22:08:47 +00001570 if (!isa<CXXMethodDecl>(D)) {
1571 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1572 break;
1573 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001574
Douglas Gregorc0d24902010-10-22 22:08:47 +00001575 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1576 AllMethodsAreStatic = false;
1577 break;
1578 }
1579 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001580
Douglas Gregorc0d24902010-10-22 22:08:47 +00001581 if (AllMethodsAreStatic)
1582 return true;
1583 }
1584
1585 return false;
1586}
1587
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001588/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001589///
1590/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1591/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001592/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001593///
1594/// Different lookup criteria can find different names. For example, a
1595/// particular scope can have both a struct and a function of the same
1596/// name, and each can be found by certain lookup criteria. For more
1597/// information about lookup criteria, see the documentation for the
1598/// class LookupCriteria.
1599///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001600/// \param R captures both the lookup criteria and any lookup results found.
1601///
1602/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001603/// search. If the lookup criteria permits, name lookup may also search
1604/// in the parent contexts or (for C++ classes) base classes.
1605///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001606/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001607/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001608///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001609/// \returns true if lookup succeeded, false if it failed.
1610bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1611 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001612 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001613
John McCall27b18f82009-11-17 02:14:36 +00001614 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001615 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001616
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001617 // Make sure that the declaration context is complete.
1618 assert((!isa<TagDecl>(LookupCtx) ||
1619 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00001620 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith7d137e32012-03-23 03:33:32 +00001621 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001622 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001623
Douglas Gregor34074322009-01-14 22:20:51 +00001624 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001625 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001626 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001627 if (isa<CXXRecordDecl>(LookupCtx))
1628 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001629 return true;
1630 }
Douglas Gregor34074322009-01-14 22:20:51 +00001631
John McCall6538c932009-10-10 05:48:19 +00001632 // Don't descend into implied contexts for redeclarations.
1633 // C++98 [namespace.qual]p6:
1634 // In a declaration for a namespace member in which the
1635 // declarator-id is a qualified-id, given that the qualified-id
1636 // for the namespace member has the form
1637 // nested-name-specifier unqualified-id
1638 // the unqualified-id shall name a member of the namespace
1639 // designated by the nested-name-specifier.
1640 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001641 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001642 return false;
1643
John McCall27b18f82009-11-17 02:14:36 +00001644 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001645 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001646 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001647
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001648 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001649 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001650 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001651 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001652 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001653
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001654 // If we're performing qualified name lookup into a dependent class,
1655 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001656 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001657 // template instantiation time (at which point all bases will be available)
1658 // or we have to fail.
1659 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1660 LookupRec->hasAnyDependentBases()) {
1661 R.setNotFoundInCurrentInstantiation();
1662 return false;
1663 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001664
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001665 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001666 CXXBasePaths Paths;
1667 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001668
1669 // Look for this member in our base classes
Craig Topperc3ec1492014-05-26 06:22:03 +00001670 CXXRecordDecl::BaseMatchesCallback *BaseCallback = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00001671 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001672 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001673 case LookupOrdinaryName:
1674 case LookupMemberName:
1675 case LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +00001676 case LookupLocalFriendName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001677 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1678 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001679
Douglas Gregor36d1b142009-10-06 17:59:45 +00001680 case LookupTagName:
1681 BaseCallback = &CXXRecordDecl::FindTagMember;
1682 break;
John McCall84d87672009-12-10 09:41:52 +00001683
Douglas Gregor39982192010-08-15 06:18:01 +00001684 case LookupAnyName:
1685 BaseCallback = &LookupAnyMember;
1686 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001687
John McCall84d87672009-12-10 09:41:52 +00001688 case LookupUsingDeclName:
1689 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001690
Douglas Gregor36d1b142009-10-06 17:59:45 +00001691 case LookupOperatorName:
1692 case LookupNamespaceName:
1693 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001694 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001695 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001696 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001697
Douglas Gregor36d1b142009-10-06 17:59:45 +00001698 case LookupNestedNameSpecifierName:
1699 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1700 break;
1701 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001702
John McCall27b18f82009-11-17 02:14:36 +00001703 if (!LookupRec->lookupInBases(BaseCallback,
1704 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001705 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001706
John McCall553c0792010-01-23 00:46:32 +00001707 R.setNamingClass(LookupRec);
1708
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001709 // C++ [class.member.lookup]p2:
1710 // [...] If the resulting set of declarations are not all from
1711 // sub-objects of the same type, or the set has a nonstatic member
1712 // and includes members from distinct sub-objects, there is an
1713 // ambiguity and the program is ill-formed. Otherwise that set is
1714 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001715 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001716 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001717 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001718
Douglas Gregor36d1b142009-10-06 17:59:45 +00001719 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001720 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001721 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001722
John McCall401982f2010-01-20 21:53:11 +00001723 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1724 // across all paths.
1725 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001726
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001727 // Determine whether we're looking at a distinct sub-object or not.
1728 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001729 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001730 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1731 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001732 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001733 }
1734
Douglas Gregorc0d24902010-10-22 22:08:47 +00001735 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001736 != Context.getCanonicalType(PathElement.Base->getType())) {
1737 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001738 // different types. If the declaration sets aren't the same, this
Nikola Smiljanic1c125682014-07-09 05:42:35 +00001739 // lookup is ambiguous.
David Blaikieff7d47a2012-12-19 00:45:41 +00001740 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00001741 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikieff7d47a2012-12-19 00:45:41 +00001742 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
1743 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001744
David Blaikieff7d47a2012-12-19 00:45:41 +00001745 while (FirstD != FirstPath->Decls.end() &&
1746 CurrentD != Path->Decls.end()) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00001747 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1748 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1749 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001750
Douglas Gregorc0d24902010-10-22 22:08:47 +00001751 ++FirstD;
1752 ++CurrentD;
1753 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001754
David Blaikieff7d47a2012-12-19 00:45:41 +00001755 if (FirstD == FirstPath->Decls.end() &&
1756 CurrentD == Path->Decls.end())
Douglas Gregorc0d24902010-10-22 22:08:47 +00001757 continue;
1758 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001759
John McCall9f3059a2009-10-09 21:13:30 +00001760 R.setAmbiguousBaseSubobjectTypes(Paths);
1761 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001762 }
1763
Douglas Gregorc0d24902010-10-22 22:08:47 +00001764 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001765 // We have a different subobject of the same type.
1766
1767 // C++ [class.member.lookup]p5:
1768 // A static member, a nested type or an enumerator defined in
1769 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001770 // has more than one base class subobject of type T.
David Blaikieff7d47a2012-12-19 00:45:41 +00001771 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001772 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001773
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001774 // We have found a nonstatic member name in multiple, distinct
1775 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001776 R.setAmbiguousBaseSubobjects(Paths);
1777 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001778 }
1779 }
1780
1781 // Lookup in a base class succeeded; return these results.
1782
Aaron Ballman1e606f42014-07-15 22:03:49 +00001783 for (auto *D : Paths.front().Decls) {
John McCall553c0792010-01-23 00:46:32 +00001784 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1785 D->getAccess());
1786 R.addDecl(D, AS);
1787 }
John McCall9f3059a2009-10-09 21:13:30 +00001788 R.resolveKind();
1789 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001790}
1791
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00001792/// \brief Performs qualified name lookup or special type of lookup for
1793/// "__super::" scope specifier.
1794///
1795/// This routine is a convenience overload meant to be called from contexts
1796/// that need to perform a qualified name lookup with an optional C++ scope
1797/// specifier that might require special kind of lookup.
1798///
1799/// \param R captures both the lookup criteria and any lookup results found.
1800///
1801/// \param LookupCtx The context in which qualified name lookup will
1802/// search.
1803///
1804/// \param SS An optional C++ scope-specifier.
1805///
1806/// \returns true if lookup succeeded, false if it failed.
1807bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1808 CXXScopeSpec &SS) {
1809 auto *NNS = SS.getScopeRep();
1810 if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
1811 return LookupInSuper(R, NNS->getAsRecordDecl());
1812 else
1813
1814 return LookupQualifiedName(R, LookupCtx);
1815}
1816
Douglas Gregor34074322009-01-14 22:20:51 +00001817/// @brief Performs name lookup for a name that was parsed in the
1818/// source code, and may contain a C++ scope specifier.
1819///
1820/// This routine is a convenience routine meant to be called from
1821/// contexts that receive a name and an optional C++ scope specifier
1822/// (e.g., "N::M::x"). It will then perform either qualified or
1823/// unqualified name lookup (with LookupQualifiedName or LookupName,
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00001824/// respectively) on the given name and return those results. It will
1825/// perform a special type of lookup for "__super::" scope specifier.
Douglas Gregor34074322009-01-14 22:20:51 +00001826///
1827/// @param S The scope from which unqualified name lookup will
1828/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001829///
Douglas Gregore861bac2009-08-25 22:51:20 +00001830/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001831///
Douglas Gregore861bac2009-08-25 22:51:20 +00001832/// @param EnteringContext Indicates whether we are going to enter the
1833/// context of the scope-specifier SS (if present).
1834///
John McCall9f3059a2009-10-09 21:13:30 +00001835/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001836bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001837 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001838 if (SS && SS->isInvalid()) {
1839 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001840 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001841 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001842 }
Mike Stump11289f42009-09-09 15:08:12 +00001843
Douglas Gregore861bac2009-08-25 22:51:20 +00001844 if (SS && SS->isSet()) {
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00001845 NestedNameSpecifier *NNS = SS->getScopeRep();
1846 if (NNS->getKind() == NestedNameSpecifier::Super)
1847 return LookupInSuper(R, NNS->getAsRecordDecl());
1848
Douglas Gregore861bac2009-08-25 22:51:20 +00001849 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001850 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001851 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001852 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001853 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001854
John McCall27b18f82009-11-17 02:14:36 +00001855 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00001856 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001857 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001858
Douglas Gregore861bac2009-08-25 22:51:20 +00001859 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001860 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001861 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00001862 R.setNotFoundInCurrentInstantiation();
1863 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00001864 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001865 }
1866
Mike Stump11289f42009-09-09 15:08:12 +00001867 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001868 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001869}
1870
Nikola Smiljanic67860242014-09-26 00:28:20 +00001871/// \brief Perform qualified name lookup into all base classes of the given
1872/// class.
1873///
1874/// \param R captures both the lookup criteria and any lookup results found.
1875///
1876/// \param Class The context in which qualified name lookup will
1877/// search. Name lookup will search in all base classes merging the results.
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00001878///
1879/// @returns True if any decls were found (but possibly ambiguous)
1880bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
Nikola Smiljanic67860242014-09-26 00:28:20 +00001881 for (const auto &BaseSpec : Class->bases()) {
1882 CXXRecordDecl *RD = cast<CXXRecordDecl>(
1883 BaseSpec.getType()->castAs<RecordType>()->getDecl());
1884 LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
1885 Result.setBaseObjectType(Context.getRecordType(Class));
1886 LookupQualifiedName(Result, RD);
1887 for (auto *Decl : Result)
1888 R.addDecl(Decl);
1889 }
1890
1891 R.resolveKind();
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00001892
1893 return !R.empty();
Nikola Smiljanic67860242014-09-26 00:28:20 +00001894}
Douglas Gregor889ceb72009-02-03 19:21:40 +00001895
James Dennett41725122012-06-22 10:16:05 +00001896/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001897/// from name lookup.
1898///
James Dennett41725122012-06-22 10:16:05 +00001899/// \param Result The result of the ambiguous lookup to be diagnosed.
Serge Pavlov99292092013-08-29 07:23:24 +00001900void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001901 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1902
John McCall27b18f82009-11-17 02:14:36 +00001903 DeclarationName Name = Result.getLookupName();
1904 SourceLocation NameLoc = Result.getNameLoc();
1905 SourceRange LookupRange = Result.getContextRange();
1906
John McCall6538c932009-10-10 05:48:19 +00001907 switch (Result.getAmbiguityKind()) {
1908 case LookupResult::AmbiguousBaseSubobjects: {
1909 CXXBasePaths *Paths = Result.getBasePaths();
1910 QualType SubobjectType = Paths->front().back().Base->getType();
1911 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1912 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1913 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001914
David Blaikieff7d47a2012-12-19 00:45:41 +00001915 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6538c932009-10-10 05:48:19 +00001916 while (isa<CXXMethodDecl>(*Found) &&
1917 cast<CXXMethodDecl>(*Found)->isStatic())
1918 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001919
John McCall6538c932009-10-10 05:48:19 +00001920 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
Serge Pavlov99292092013-08-29 07:23:24 +00001921 break;
John McCall6538c932009-10-10 05:48:19 +00001922 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001923
John McCall6538c932009-10-10 05:48:19 +00001924 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001925 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1926 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001927
John McCall6538c932009-10-10 05:48:19 +00001928 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001929 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001930 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1931 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001932 Path != PathEnd; ++Path) {
David Blaikieff7d47a2012-12-19 00:45:41 +00001933 Decl *D = Path->Decls.front();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001934 if (DeclsPrinted.insert(D).second)
1935 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1936 }
Serge Pavlov99292092013-08-29 07:23:24 +00001937 break;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001938 }
1939
John McCall6538c932009-10-10 05:48:19 +00001940 case LookupResult::AmbiguousTagHiding: {
1941 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001942
John McCall6538c932009-10-10 05:48:19 +00001943 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1944
Aaron Ballman1e606f42014-07-15 22:03:49 +00001945 for (auto *D : Result)
1946 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
John McCall6538c932009-10-10 05:48:19 +00001947 TagDecls.insert(TD);
1948 Diag(TD->getLocation(), diag::note_hidden_tag);
1949 }
1950
Aaron Ballman1e606f42014-07-15 22:03:49 +00001951 for (auto *D : Result)
1952 if (!isa<TagDecl>(D))
1953 Diag(D->getLocation(), diag::note_hiding_object);
John McCall6538c932009-10-10 05:48:19 +00001954
1955 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001956 LookupResult::Filter F = Result.makeFilter();
1957 while (F.hasNext()) {
1958 if (TagDecls.count(F.next()))
1959 F.erase();
1960 }
1961 F.done();
Serge Pavlov99292092013-08-29 07:23:24 +00001962 break;
John McCall6538c932009-10-10 05:48:19 +00001963 }
1964
1965 case LookupResult::AmbiguousReference: {
1966 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001967
Aaron Ballman1e606f42014-07-15 22:03:49 +00001968 for (auto *D : Result)
1969 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
Serge Pavlov99292092013-08-29 07:23:24 +00001970 break;
John McCall6538c932009-10-10 05:48:19 +00001971 }
Serge Pavlov99292092013-08-29 07:23:24 +00001972 }
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001973}
Douglas Gregore254f902009-02-04 00:32:51 +00001974
John McCallf24d7bb2010-05-28 18:45:08 +00001975namespace {
1976 struct AssociatedLookup {
John McCall7d8b0412012-08-24 20:38:34 +00001977 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallf24d7bb2010-05-28 18:45:08 +00001978 Sema::AssociatedNamespaceSet &Namespaces,
1979 Sema::AssociatedClassSet &Classes)
John McCall7d8b0412012-08-24 20:38:34 +00001980 : S(S), Namespaces(Namespaces), Classes(Classes),
1981 InstantiationLoc(InstantiationLoc) {
John McCallf24d7bb2010-05-28 18:45:08 +00001982 }
1983
1984 Sema &S;
1985 Sema::AssociatedNamespaceSet &Namespaces;
1986 Sema::AssociatedClassSet &Classes;
John McCall7d8b0412012-08-24 20:38:34 +00001987 SourceLocation InstantiationLoc;
John McCallf24d7bb2010-05-28 18:45:08 +00001988 };
1989}
1990
Mike Stump11289f42009-09-09 15:08:12 +00001991static void
John McCallf24d7bb2010-05-28 18:45:08 +00001992addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001993
Douglas Gregor8b895222010-04-30 07:08:38 +00001994static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1995 DeclContext *Ctx) {
1996 // Add the associated namespace for this class.
1997
1998 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1999 // be a locally scoped record.
2000
Sebastian Redlbd595762010-08-31 20:53:31 +00002001 // We skip out of inline namespaces. The innermost non-inline namespace
2002 // contains all names of all its nested inline namespaces anyway, so we can
2003 // replace the entire inline namespace tree with its root.
2004 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
2005 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00002006 Ctx = Ctx->getParent();
2007
John McCallc7e8e792009-08-07 22:18:02 +00002008 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00002009 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00002010}
Douglas Gregor197e5f72009-07-08 07:51:57 +00002011
Mike Stump11289f42009-09-09 15:08:12 +00002012// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00002013// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00002014static void
John McCallf24d7bb2010-05-28 18:45:08 +00002015addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2016 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002017 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00002018 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00002019 switch (Arg.getKind()) {
2020 case TemplateArgument::Null:
2021 break;
Mike Stump11289f42009-09-09 15:08:12 +00002022
Douglas Gregor197e5f72009-07-08 07:51:57 +00002023 case TemplateArgument::Type:
2024 // [...] the namespaces and classes associated with the types of the
2025 // template arguments provided for template type parameters (excluding
2026 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00002027 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00002028 break;
Mike Stump11289f42009-09-09 15:08:12 +00002029
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002030 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002031 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00002032 // [...] the namespaces in which any template template arguments are
2033 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00002034 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002035 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00002036 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002037 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00002038 DeclContext *Ctx = ClassTemplate->getDeclContext();
2039 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002040 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002041 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002042 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002043 }
2044 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002045 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002046
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002047 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00002048 case TemplateArgument::Integral:
2049 case TemplateArgument::Expression:
Eli Friedmanb826a002012-09-26 02:36:12 +00002050 case TemplateArgument::NullPtr:
Mike Stump11289f42009-09-09 15:08:12 +00002051 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00002052 // associated namespaces. ]
2053 break;
Mike Stump11289f42009-09-09 15:08:12 +00002054
Douglas Gregor197e5f72009-07-08 07:51:57 +00002055 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00002056 for (const auto &P : Arg.pack_elements())
2057 addAssociatedClassesAndNamespaces(Result, P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002058 break;
2059 }
2060}
2061
Douglas Gregore254f902009-02-04 00:32:51 +00002062// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00002063// argument-dependent lookup with an argument of class type
2064// (C++ [basic.lookup.koenig]p2).
2065static void
John McCallf24d7bb2010-05-28 18:45:08 +00002066addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2067 CXXRecordDecl *Class) {
2068
2069 // Just silently ignore anything whose name is __va_list_tag.
2070 if (Class->getDeclName() == Result.S.VAListTagName)
2071 return;
2072
Douglas Gregore254f902009-02-04 00:32:51 +00002073 // C++ [basic.lookup.koenig]p2:
2074 // [...]
2075 // -- If T is a class type (including unions), its associated
2076 // classes are: the class itself; the class of which it is a
2077 // member, if any; and its direct and indirect base
2078 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00002079 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00002080
2081 // Add the class of which it is a member, if any.
2082 DeclContext *Ctx = Class->getDeclContext();
2083 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002084 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002085 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002086 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002087
Douglas Gregore254f902009-02-04 00:32:51 +00002088 // Add the class itself. If we've already seen this class, we don't
2089 // need to visit base classes.
Richard Smith594461f2014-03-14 22:07:27 +00002090 //
2091 // FIXME: That's not correct, we may have added this class only because it
2092 // was the enclosing class of another class, and in that case we won't have
2093 // added its base classes yet.
David Blaikie82e95a32014-11-19 07:49:47 +00002094 if (!Result.Classes.insert(Class).second)
Douglas Gregore254f902009-02-04 00:32:51 +00002095 return;
2096
Mike Stump11289f42009-09-09 15:08:12 +00002097 // -- If T is a template-id, its associated namespaces and classes are
2098 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002099 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00002100 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00002101 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00002102 // namespaces in which any template template arguments are defined; and
2103 // the classes in which any member templates used as template template
2104 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00002105 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00002106 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00002107 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2108 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2109 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002110 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002111 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002112 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002113
Douglas Gregor197e5f72009-07-08 07:51:57 +00002114 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2115 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00002116 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002117 }
Mike Stump11289f42009-09-09 15:08:12 +00002118
John McCall67da35c2010-02-04 22:26:26 +00002119 // Only recurse into base classes for complete types.
Richard Smith594461f2014-03-14 22:07:27 +00002120 if (!Class->hasDefinition())
2121 return;
John McCall67da35c2010-02-04 22:26:26 +00002122
Douglas Gregore254f902009-02-04 00:32:51 +00002123 // Add direct and indirect base classes along with their associated
2124 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002125 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00002126 Bases.push_back(Class);
2127 while (!Bases.empty()) {
2128 // Pop this class off the stack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002129 Class = Bases.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002130
2131 // Visit the base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +00002132 for (const auto &Base : Class->bases()) {
2133 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00002134 // In dependent contexts, we do ADL twice, and the first time around,
2135 // the base type might be a dependent TemplateSpecializationType, or a
2136 // TemplateTypeParmType. If that happens, simply ignore it.
2137 // FIXME: If we want to support export, we probably need to add the
2138 // namespace of the template in a TemplateSpecializationType, or even
2139 // the classes and namespaces of known non-dependent arguments.
2140 if (!BaseType)
2141 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002142 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
David Blaikie82e95a32014-11-19 07:49:47 +00002143 if (Result.Classes.insert(BaseDecl).second) {
Douglas Gregore254f902009-02-04 00:32:51 +00002144 // Find the associated namespace for this base class.
2145 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00002146 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00002147
2148 // Make sure we visit the bases of this base class.
2149 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2150 Bases.push_back(BaseDecl);
2151 }
2152 }
2153 }
2154}
2155
2156// \brief Add the associated classes and namespaces for
2157// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00002158// (C++ [basic.lookup.koenig]p2).
2159static void
John McCallf24d7bb2010-05-28 18:45:08 +00002160addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00002161 // C++ [basic.lookup.koenig]p2:
2162 //
2163 // For each argument type T in the function call, there is a set
2164 // of zero or more associated namespaces and a set of zero or more
2165 // associated classes to be considered. The sets of namespaces and
2166 // classes is determined entirely by the types of the function
2167 // arguments (and the namespace of any template template
2168 // argument). Typedef names and using-declarations used to specify
2169 // the types do not contribute to this set. The sets of namespaces
2170 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00002171
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002172 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00002173 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2174
Douglas Gregore254f902009-02-04 00:32:51 +00002175 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00002176 switch (T->getTypeClass()) {
2177
2178#define TYPE(Class, Base)
2179#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2180#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2181#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2182#define ABSTRACT_TYPE(Class, Base)
2183#include "clang/AST/TypeNodes.def"
2184 // T is canonical. We can also ignore dependent types because
2185 // we don't need to do ADL at the definition point, but if we
2186 // wanted to implement template export (or if we find some other
2187 // use for associated classes and namespaces...) this would be
2188 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00002189 break;
Douglas Gregore254f902009-02-04 00:32:51 +00002190
John McCall0af3d3b2010-05-28 06:08:54 +00002191 // -- If T is a pointer to U or an array of U, its associated
2192 // namespaces and classes are those associated with U.
2193 case Type::Pointer:
2194 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2195 continue;
2196 case Type::ConstantArray:
2197 case Type::IncompleteArray:
2198 case Type::VariableArray:
2199 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2200 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002201
John McCall0af3d3b2010-05-28 06:08:54 +00002202 // -- If T is a fundamental type, its associated sets of
2203 // namespaces and classes are both empty.
2204 case Type::Builtin:
2205 break;
2206
2207 // -- If T is a class type (including unions), its associated
2208 // classes are: the class itself; the class of which it is a
2209 // member, if any; and its direct and indirect base
2210 // classes. Its associated namespaces are the namespaces in
2211 // which its associated classes are defined.
2212 case Type::Record: {
Richard Smith594461f2014-03-14 22:07:27 +00002213 Result.S.RequireCompleteType(Result.InstantiationLoc, QualType(T, 0),
2214 /*no diagnostic*/ 0);
John McCall0af3d3b2010-05-28 06:08:54 +00002215 CXXRecordDecl *Class
2216 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002217 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00002218 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00002219 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00002220
John McCall0af3d3b2010-05-28 06:08:54 +00002221 // -- If T is an enumeration type, its associated namespace is
2222 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002223 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00002224 // it has no associated class.
2225 case Type::Enum: {
2226 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002227
John McCall0af3d3b2010-05-28 06:08:54 +00002228 DeclContext *Ctx = Enum->getDeclContext();
2229 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002230 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002231
John McCall0af3d3b2010-05-28 06:08:54 +00002232 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002233 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00002234
John McCall0af3d3b2010-05-28 06:08:54 +00002235 break;
2236 }
2237
2238 // -- If T is a function type, its associated namespaces and
2239 // classes are those associated with the function parameter
2240 // types and those associated with the return type.
2241 case Type::FunctionProto: {
2242 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002243 for (const auto &Arg : Proto->param_types())
2244 Queue.push_back(Arg.getTypePtr());
John McCall0af3d3b2010-05-28 06:08:54 +00002245 // fallthrough
2246 }
2247 case Type::FunctionNoProto: {
2248 const FunctionType *FnType = cast<FunctionType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00002249 T = FnType->getReturnType().getTypePtr();
John McCall0af3d3b2010-05-28 06:08:54 +00002250 continue;
2251 }
2252
2253 // -- If T is a pointer to a member function of a class X, its
2254 // associated namespaces and classes are those associated
2255 // with the function parameter types and return type,
2256 // together with those associated with X.
2257 //
2258 // -- If T is a pointer to a data member of class X, its
2259 // associated namespaces and classes are those associated
2260 // with the member type together with those associated with
2261 // X.
2262 case Type::MemberPointer: {
2263 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2264
2265 // Queue up the class type into which this points.
2266 Queue.push_back(MemberPtr->getClass());
2267
2268 // And directly continue with the pointee type.
2269 T = MemberPtr->getPointeeType().getTypePtr();
2270 continue;
2271 }
2272
2273 // As an extension, treat this like a normal pointer.
2274 case Type::BlockPointer:
2275 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2276 continue;
2277
2278 // References aren't covered by the standard, but that's such an
2279 // obvious defect that we cover them anyway.
2280 case Type::LValueReference:
2281 case Type::RValueReference:
2282 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2283 continue;
2284
2285 // These are fundamental types.
2286 case Type::Vector:
2287 case Type::ExtVector:
2288 case Type::Complex:
2289 break;
2290
Richard Smith27d807c2013-04-30 13:56:41 +00002291 // Non-deduced auto types only get here for error cases.
2292 case Type::Auto:
2293 break;
2294
Douglas Gregor8e936662011-04-12 01:02:45 +00002295 // If T is an Objective-C object or interface type, or a pointer to an
2296 // object or interface type, the associated namespace is the global
2297 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002298 case Type::ObjCObject:
2299 case Type::ObjCInterface:
2300 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002301 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002302 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002303
2304 // Atomic types are just wrappers; use the associations of the
2305 // contained type.
2306 case Type::Atomic:
2307 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2308 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002309 }
2310
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002311 if (Queue.empty())
2312 break;
2313 T = Queue.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002314 }
Douglas Gregore254f902009-02-04 00:32:51 +00002315}
2316
2317/// \brief Find the associated classes and namespaces for
2318/// argument-dependent lookup for a call with the given set of
2319/// arguments.
2320///
2321/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002322/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002323/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00002324void Sema::FindAssociatedClassesAndNamespaces(
2325 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2326 AssociatedNamespaceSet &AssociatedNamespaces,
2327 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002328 AssociatedNamespaces.clear();
2329 AssociatedClasses.clear();
2330
John McCall7d8b0412012-08-24 20:38:34 +00002331 AssociatedLookup Result(*this, InstantiationLoc,
2332 AssociatedNamespaces, AssociatedClasses);
John McCallf24d7bb2010-05-28 18:45:08 +00002333
Douglas Gregore254f902009-02-04 00:32:51 +00002334 // C++ [basic.lookup.koenig]p2:
2335 // For each argument type T in the function call, there is a set
2336 // of zero or more associated namespaces and a set of zero or more
2337 // associated classes to be considered. The sets of namespaces and
2338 // classes is determined entirely by the types of the function
2339 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002340 // argument).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002341 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregore254f902009-02-04 00:32:51 +00002342 Expr *Arg = Args[ArgIdx];
2343
2344 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002345 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002346 continue;
2347 }
2348
2349 // [...] In addition, if the argument is the name or address of a
2350 // set of overloaded functions and/or function templates, its
2351 // associated classes and namespaces are the union of those
2352 // associated with each of the members of the set: the namespace
2353 // in which the function or function template is defined and the
2354 // classes and namespaces associated with its (non-dependent)
2355 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002356 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002357 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002358 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002359 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002360
John McCallf24d7bb2010-05-28 18:45:08 +00002361 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2362 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002363
Aaron Ballman1e606f42014-07-15 22:03:49 +00002364 for (const auto *D : ULE->decls()) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002365 // Look through any using declarations to find the underlying function.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002366 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
Douglas Gregore254f902009-02-04 00:32:51 +00002367
2368 // Add the classes and namespaces associated with the parameter
2369 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002370 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002371 }
2372 }
2373}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002374
John McCall5cebab12009-11-18 07:57:50 +00002375NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002376 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002377 LookupNameKind NameKind,
2378 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002379 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002380 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002381 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002382}
2383
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002384/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002385ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002386 SourceLocation IdLoc,
2387 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002388 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002389 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002390 return cast_or_null<ObjCProtocolDecl>(D);
2391}
2392
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002393void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002394 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002395 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002396 // C++ [over.match.oper]p3:
2397 // -- The set of non-member candidates is the result of the
2398 // unqualified lookup of operator@ in the context of the
2399 // expression according to the usual rules for name lookup in
2400 // unqualified function calls (3.4.2) except that all member
Richard Smith100b24a2014-04-17 01:52:14 +00002401 // functions are ignored.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002402 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002403 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2404 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002405
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002406 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
Richard Smith100b24a2014-04-17 01:52:14 +00002407 Functions.append(Operators.begin(), Operators.end());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002408}
2409
Alexis Hunt1da39282011-06-24 02:11:39 +00002410Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002411 CXXSpecialMember SM,
2412 bool ConstArg,
2413 bool VolatileArg,
2414 bool RValueThis,
2415 bool ConstThis,
2416 bool VolatileThis) {
Richard Smith7d125a12012-11-27 21:20:31 +00002417 assert(CanDeclareSpecialMemberFunction(RD) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002418 "doing special member lookup into record that isn't fully complete");
Richard Smith7d125a12012-11-27 21:20:31 +00002419 RD = RD->getDefinition();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002420 if (RValueThis || ConstThis || VolatileThis)
2421 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2422 "constructors and destructors always have unqualified lvalue this");
2423 if (ConstArg || VolatileArg)
2424 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2425 "parameter-less special members can't have qualified arguments");
2426
2427 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002428 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002429 ID.AddInteger(SM);
2430 ID.AddInteger(ConstArg);
2431 ID.AddInteger(VolatileArg);
2432 ID.AddInteger(RValueThis);
2433 ID.AddInteger(ConstThis);
2434 ID.AddInteger(VolatileThis);
2435
2436 void *InsertPoint;
2437 SpecialMemberOverloadResult *Result =
2438 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2439
2440 // This was already cached
2441 if (Result)
2442 return Result;
2443
Alexis Huntba8e18d2011-06-07 00:11:58 +00002444 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2445 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002446 SpecialMemberCache.InsertNode(Result, InsertPoint);
2447
2448 if (SM == CXXDestructor) {
Richard Smith2be35f52012-12-01 02:35:44 +00002449 if (RD->needsImplicitDestructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002450 DeclareImplicitDestructor(RD);
2451 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002452 assert(DD && "record without a destructor");
2453 Result->setMethod(DD);
Richard Smith852265f2012-03-30 20:53:28 +00002454 Result->setKind(DD->isDeleted() ?
2455 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith83c478d2012-04-20 18:46:14 +00002456 SpecialMemberOverloadResult::Success);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002457 return Result;
2458 }
2459
Alexis Hunteef8ee02011-06-10 03:50:41 +00002460 // Prepare for overload resolution. Here we construct a synthetic argument
2461 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002462 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002463 DeclarationName Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002464 Expr *Arg = nullptr;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002465 unsigned NumArgs;
2466
Richard Smith83c478d2012-04-20 18:46:14 +00002467 QualType ArgType = CanTy;
2468 ExprValueKind VK = VK_LValue;
2469
Alexis Hunteef8ee02011-06-10 03:50:41 +00002470 if (SM == CXXDefaultConstructor) {
2471 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2472 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002473 if (RD->needsImplicitDefaultConstructor())
2474 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002475 } else {
2476 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2477 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smith2be35f52012-12-01 02:35:44 +00002478 if (RD->needsImplicitCopyConstructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002479 DeclareImplicitCopyConstructor(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002480 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002481 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002482 } else {
2483 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smith2be35f52012-12-01 02:35:44 +00002484 if (RD->needsImplicitCopyAssignment())
Alexis Hunt1da39282011-06-24 02:11:39 +00002485 DeclareImplicitCopyAssignment(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002486 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002487 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002488 }
2489
Alexis Hunteef8ee02011-06-10 03:50:41 +00002490 if (ConstArg)
2491 ArgType.addConst();
2492 if (VolatileArg)
2493 ArgType.addVolatile();
2494
2495 // This isn't /really/ specified by the standard, but it's implied
2496 // we should be working from an RValue in the case of move to ensure
2497 // that we prefer to bind to rvalue references, and an LValue in the
2498 // case of copy to ensure we don't bind to rvalue references.
2499 // Possibly an XValue is actually correct in the case of move, but
2500 // there is no semantic difference for class types in this restricted
2501 // case.
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002502 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002503 VK = VK_LValue;
2504 else
2505 VK = VK_RValue;
Richard Smith83c478d2012-04-20 18:46:14 +00002506 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00002507
Richard Smith83c478d2012-04-20 18:46:14 +00002508 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2509
2510 if (SM != CXXDefaultConstructor) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002511 NumArgs = 1;
Richard Smith83c478d2012-04-20 18:46:14 +00002512 Arg = &FakeArg;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002513 }
2514
2515 // Create the object argument
2516 QualType ThisTy = CanTy;
2517 if (ConstThis)
2518 ThisTy.addConst();
2519 if (VolatileThis)
2520 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002521 Expr::Classification Classification =
Richard Smith83c478d2012-04-20 18:46:14 +00002522 OpaqueValueExpr(SourceLocation(), ThisTy,
2523 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002524
2525 // Now we perform lookup on the name we computed earlier and do overload
2526 // resolution. Lookup is only performed directly into the class since there
2527 // will always be a (possibly implicit) declaration to shadow any others.
Richard Smith100b24a2014-04-17 01:52:14 +00002528 OverloadCandidateSet OCS(RD->getLocation(), OverloadCandidateSet::CSK_Normal);
David Blaikieff7d47a2012-12-19 00:45:41 +00002529 DeclContext::lookup_result R = RD->lookup(Name);
Richard Smith8c37ab52015-02-11 01:48:47 +00002530
2531 if (R.empty()) {
2532 // We might have no default constructor because we have a lambda's closure
2533 // type, rather than because there's some other declared constructor.
2534 // Every class has a copy/move constructor, copy/move assignment, and
2535 // destructor.
2536 assert(SM == CXXDefaultConstructor &&
2537 "lookup for a constructor or assignment operator was empty");
2538 Result->setMethod(nullptr);
2539 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
2540 return Result;
2541 }
Chandler Carruth7deaae72013-08-18 07:20:52 +00002542
2543 // Copy the candidates as our processing of them may load new declarations
2544 // from an external source and invalidate lookup_result.
2545 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2546
Aaron Ballman1e606f42014-07-15 22:03:49 +00002547 for (auto *Cand : Candidates) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002548 if (Cand->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002549 continue;
2550
Alexis Hunt1da39282011-06-24 02:11:39 +00002551 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2552 // FIXME: [namespace.udecl]p15 says that we should only consider a
2553 // using declaration here if it does not match a declaration in the
2554 // derived class. We do not implement this correctly in other cases
2555 // either.
2556 Cand = U->getTargetDecl();
2557
2558 if (Cand->isInvalidDecl())
2559 continue;
2560 }
2561
2562 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002563 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Alexis Hunt1da39282011-06-24 02:11:39 +00002564 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002565 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2566 OCS, true);
Alexis Hunt080709f2011-06-23 00:26:20 +00002567 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002568 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2569 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt2949f022011-06-22 02:58:46 +00002570 } else if (FunctionTemplateDecl *Tmpl =
Alexis Hunt1da39282011-06-24 02:11:39 +00002571 dyn_cast<FunctionTemplateDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002572 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2573 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Craig Topperc3ec1492014-05-26 06:22:03 +00002574 RD, nullptr, ThisTy, Classification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002575 llvm::makeArrayRef(&Arg, NumArgs),
Alexis Hunt080709f2011-06-23 00:26:20 +00002576 OCS, true);
2577 else
2578 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Craig Topperc3ec1492014-05-26 06:22:03 +00002579 nullptr, llvm::makeArrayRef(&Arg, NumArgs),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002580 OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002581 } else {
2582 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002583 }
2584 }
2585
2586 OverloadCandidateSet::iterator Best;
2587 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2588 case OR_Success:
2589 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith83c478d2012-04-20 18:46:14 +00002590 Result->setKind(SpecialMemberOverloadResult::Success);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002591 break;
2592
2593 case OR_Deleted:
2594 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith852265f2012-03-30 20:53:28 +00002595 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002596 break;
2597
2598 case OR_Ambiguous:
Craig Topperc3ec1492014-05-26 06:22:03 +00002599 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00002600 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2601 break;
2602
Alexis Hunteef8ee02011-06-10 03:50:41 +00002603 case OR_No_Viable_Function:
Craig Topperc3ec1492014-05-26 06:22:03 +00002604 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00002605 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002606 break;
2607 }
2608
2609 return Result;
2610}
2611
2612/// \brief Look up the default constructor for the given class.
2613CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002614 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002615 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2616 false, false);
2617
2618 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002619}
2620
Alexis Hunt491ec602011-06-21 23:42:56 +00002621/// \brief Look up the copying constructor for the given class.
2622CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith83c478d2012-04-20 18:46:14 +00002623 unsigned Quals) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002624 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2625 "non-const, non-volatile qualifiers for copy ctor arg");
2626 SpecialMemberOverloadResult *Result =
2627 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2628 Quals & Qualifiers::Volatile, false, false, false);
2629
Alexis Hunt899bd442011-06-10 04:44:37 +00002630 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2631}
2632
Sebastian Redl22653ba2011-08-30 19:58:05 +00002633/// \brief Look up the moving constructor for the given class.
Richard Smith1c6461e2012-07-18 03:36:00 +00002634CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2635 unsigned Quals) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002636 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002637 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2638 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002639
2640 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2641}
2642
Douglas Gregor52b72822010-07-02 23:12:18 +00002643/// \brief Look up the constructors for the given class.
2644DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002645 // If the implicit constructors have not yet been declared, do so now.
Richard Smith7d125a12012-11-27 21:20:31 +00002646 if (CanDeclareSpecialMemberFunction(Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00002647 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002648 DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +00002649 if (Class->needsImplicitCopyConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002650 DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002651 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002652 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00002653 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002654
Douglas Gregor52b72822010-07-02 23:12:18 +00002655 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2656 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2657 return Class->lookup(Name);
2658}
2659
Alexis Hunt491ec602011-06-21 23:42:56 +00002660/// \brief Look up the copying assignment operator for the given class.
2661CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2662 unsigned Quals, bool RValueThis,
Richard Smith83c478d2012-04-20 18:46:14 +00002663 unsigned ThisQuals) {
Alexis Hunt491ec602011-06-21 23:42:56 +00002664 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2665 "non-const, non-volatile qualifiers for copy assignment arg");
2666 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2667 "non-const, non-volatile qualifiers for copy assignment this");
2668 SpecialMemberOverloadResult *Result =
2669 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2670 Quals & Qualifiers::Volatile, RValueThis,
2671 ThisQuals & Qualifiers::Const,
2672 ThisQuals & Qualifiers::Volatile);
2673
Alexis Hunt491ec602011-06-21 23:42:56 +00002674 return Result->getMethod();
2675}
2676
Sebastian Redl22653ba2011-08-30 19:58:05 +00002677/// \brief Look up the moving assignment operator for the given class.
2678CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith1c6461e2012-07-18 03:36:00 +00002679 unsigned Quals,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002680 bool RValueThis,
2681 unsigned ThisQuals) {
2682 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2683 "non-const, non-volatile qualifiers for copy assignment this");
2684 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002685 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2686 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002687 ThisQuals & Qualifiers::Const,
2688 ThisQuals & Qualifiers::Volatile);
2689
2690 return Result->getMethod();
2691}
2692
Douglas Gregore71edda2010-07-01 22:47:18 +00002693/// \brief Look for the destructor of the given class.
2694///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00002695/// During semantic analysis, this routine should be used in lieu of
2696/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00002697///
2698/// \returns The destructor for this class.
2699CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002700 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2701 false, false, false,
2702 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00002703}
2704
Richard Smithbcc22fc2012-03-09 08:00:36 +00002705/// LookupLiteralOperator - Determine which literal operator should be used for
2706/// a user-defined literal, per C++11 [lex.ext].
2707///
2708/// Normal overload resolution is not used to select which literal operator to
2709/// call for a user-defined literal. Look up the provided literal operator name,
2710/// and filter the results to the appropriate set for the given argument types.
2711Sema::LiteralOperatorLookupResult
2712Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2713 ArrayRef<QualType> ArgTys,
Richard Smithb8b41d32013-10-07 19:57:58 +00002714 bool AllowRaw, bool AllowTemplate,
2715 bool AllowStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002716 LookupName(R, S);
2717 assert(R.getResultKind() != LookupResult::Ambiguous &&
2718 "literal operator lookup can't be ambiguous");
2719
2720 // Filter the lookup results appropriately.
2721 LookupResult::Filter F = R.makeFilter();
2722
Richard Smithbcc22fc2012-03-09 08:00:36 +00002723 bool FoundRaw = false;
Richard Smithb8b41d32013-10-07 19:57:58 +00002724 bool FoundTemplate = false;
2725 bool FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002726 bool FoundExactMatch = false;
2727
2728 while (F.hasNext()) {
2729 Decl *D = F.next();
2730 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2731 D = USD->getTargetDecl();
2732
Douglas Gregorc1970572013-04-10 05:18:00 +00002733 // If the declaration we found is invalid, skip it.
2734 if (D->isInvalidDecl()) {
2735 F.erase();
2736 continue;
2737 }
2738
Richard Smithb8b41d32013-10-07 19:57:58 +00002739 bool IsRaw = false;
2740 bool IsTemplate = false;
2741 bool IsStringTemplate = false;
2742 bool IsExactMatch = false;
2743
Richard Smithbcc22fc2012-03-09 08:00:36 +00002744 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2745 if (FD->getNumParams() == 1 &&
2746 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2747 IsRaw = true;
Richard Smith550de452013-01-15 07:12:59 +00002748 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002749 IsExactMatch = true;
2750 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2751 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2752 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2753 IsExactMatch = false;
2754 break;
2755 }
2756 }
2757 }
2758 }
Richard Smithb8b41d32013-10-07 19:57:58 +00002759 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
2760 TemplateParameterList *Params = FD->getTemplateParameters();
2761 if (Params->size() == 1)
2762 IsTemplate = true;
2763 else
2764 IsStringTemplate = true;
2765 }
Richard Smithbcc22fc2012-03-09 08:00:36 +00002766
2767 if (IsExactMatch) {
2768 FoundExactMatch = true;
Richard Smithb8b41d32013-10-07 19:57:58 +00002769 AllowRaw = false;
2770 AllowTemplate = false;
2771 AllowStringTemplate = false;
2772 if (FoundRaw || FoundTemplate || FoundStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002773 // Go through again and remove the raw and template decls we've
2774 // already found.
2775 F.restart();
Richard Smithb8b41d32013-10-07 19:57:58 +00002776 FoundRaw = FoundTemplate = FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002777 }
Richard Smithb8b41d32013-10-07 19:57:58 +00002778 } else if (AllowRaw && IsRaw) {
2779 FoundRaw = true;
2780 } else if (AllowTemplate && IsTemplate) {
2781 FoundTemplate = true;
2782 } else if (AllowStringTemplate && IsStringTemplate) {
2783 FoundStringTemplate = true;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002784 } else {
2785 F.erase();
2786 }
2787 }
2788
2789 F.done();
2790
2791 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2792 // parameter type, that is used in preference to a raw literal operator
2793 // or literal operator template.
2794 if (FoundExactMatch)
2795 return LOLR_Cooked;
2796
2797 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2798 // operator template, but not both.
2799 if (FoundRaw && FoundTemplate) {
2800 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
Alp Tokera2794f92014-01-22 07:29:52 +00002801 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2802 NoteOverloadCandidate((*I)->getUnderlyingDecl()->getAsFunction());
Richard Smithbcc22fc2012-03-09 08:00:36 +00002803 return LOLR_Error;
2804 }
2805
2806 if (FoundRaw)
2807 return LOLR_Raw;
2808
2809 if (FoundTemplate)
2810 return LOLR_Template;
2811
Richard Smithb8b41d32013-10-07 19:57:58 +00002812 if (FoundStringTemplate)
2813 return LOLR_StringTemplate;
2814
Richard Smithbcc22fc2012-03-09 08:00:36 +00002815 // Didn't find anything we could use.
2816 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2817 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
Richard Smithb8b41d32013-10-07 19:57:58 +00002818 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
2819 << (AllowTemplate || AllowStringTemplate);
Richard Smithbcc22fc2012-03-09 08:00:36 +00002820 return LOLR_Error;
2821}
2822
John McCall8fe68082010-01-26 07:16:45 +00002823void ADLResult::insert(NamedDecl *New) {
2824 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2825
2826 // If we haven't yet seen a decl for this key, or the last decl
2827 // was exactly this one, we're done.
Craig Topperc3ec1492014-05-26 06:22:03 +00002828 if (Old == nullptr || Old == New) {
John McCall8fe68082010-01-26 07:16:45 +00002829 Old = New;
2830 return;
2831 }
2832
2833 // Otherwise, decide which is a more recent redeclaration.
Alp Tokera2794f92014-01-22 07:29:52 +00002834 FunctionDecl *OldFD = Old->getAsFunction();
2835 FunctionDecl *NewFD = New->getAsFunction();
John McCall8fe68082010-01-26 07:16:45 +00002836
2837 FunctionDecl *Cursor = NewFD;
2838 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002839 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00002840
2841 // If we got to the end without finding OldFD, OldFD is the newer
2842 // declaration; leave things as they are.
2843 if (!Cursor) return;
2844
2845 // If we do find OldFD, then NewFD is newer.
2846 if (Cursor == OldFD) break;
2847
2848 // Otherwise, keep looking.
2849 }
2850
2851 Old = New;
2852}
2853
Richard Smith100b24a2014-04-17 01:52:14 +00002854void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
2855 ArrayRef<Expr *> Args, ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002856 // Find all of the associated namespaces and classes based on the
2857 // arguments we have.
2858 AssociatedNamespaceSet AssociatedNamespaces;
2859 AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00002860 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCallc7e8e792009-08-07 22:18:02 +00002861 AssociatedNamespaces,
2862 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002863
2864 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002865 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2866 // and let Y be the lookup set produced by argument dependent
2867 // lookup (defined as follows). If X contains [...] then Y is
2868 // empty. Otherwise Y is the set of declarations found in the
2869 // namespaces associated with the argument types as described
2870 // below. The set of declarations found by the lookup of the name
2871 // is the union of X and Y.
2872 //
2873 // Here, we compute Y and add its members to the overloaded
2874 // candidate set.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002875 for (auto *NS : AssociatedNamespaces) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002876 // When considering an associated namespace, the lookup is the
2877 // same as the lookup performed when the associated namespace is
2878 // used as a qualifier (3.4.3.2) except that:
2879 //
2880 // -- Any using-directives in the associated namespace are
2881 // ignored.
2882 //
John McCallc7e8e792009-08-07 22:18:02 +00002883 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002884 // associated classes are visible within their respective
2885 // namespaces even if they are not visible during an ordinary
2886 // lookup (11.4).
Aaron Ballman1e606f42014-07-15 22:03:49 +00002887 DeclContext::lookup_result R = NS->lookup(Name);
2888 for (auto *D : R) {
John McCallaa74a0c2009-08-28 07:59:38 +00002889 // If the only declaration here is an ordinary friend, consider
2890 // it only if it was declared in an associated classes.
Richard Smith541b38b2013-09-20 01:15:31 +00002891 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) {
2892 // If it's neither ordinarily visible nor a friend, we can't find it.
2893 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0)
2894 continue;
2895
Richard Smith64017682013-07-17 23:53:16 +00002896 bool DeclaredInAssociatedClass = false;
2897 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
2898 DeclContext *LexDC = DI->getLexicalDeclContext();
2899 if (isa<CXXRecordDecl>(LexDC) &&
2900 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) {
2901 DeclaredInAssociatedClass = true;
2902 break;
2903 }
2904 }
2905 if (!DeclaredInAssociatedClass)
John McCalld1e9d832009-08-11 06:59:38 +00002906 continue;
2907 }
Mike Stump11289f42009-09-09 15:08:12 +00002908
John McCall91f61fc2010-01-26 06:04:06 +00002909 if (isa<UsingShadowDecl>(D))
2910 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002911
Richard Smith100b24a2014-04-17 01:52:14 +00002912 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D))
John McCall8fe68082010-01-26 07:16:45 +00002913 continue;
2914
2915 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002916 }
2917 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002918}
Douglas Gregor2d435302009-12-30 17:04:44 +00002919
2920//----------------------------------------------------------------------------
2921// Search for all visible declarations.
2922//----------------------------------------------------------------------------
2923VisibleDeclConsumer::~VisibleDeclConsumer() { }
2924
Richard Smithe156254d2013-08-20 20:35:18 +00002925bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
2926
Douglas Gregor2d435302009-12-30 17:04:44 +00002927namespace {
2928
2929class ShadowContextRAII;
2930
2931class VisibleDeclsRecord {
2932public:
2933 /// \brief An entry in the shadow map, which is optimized to store a
2934 /// single declaration (the common case) but can also store a list
2935 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002936 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00002937
2938private:
2939 /// \brief A mapping from declaration names to the declarations that have
2940 /// this name within a particular scope.
2941 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2942
2943 /// \brief A list of shadow maps, which is used to model name hiding.
2944 std::list<ShadowMap> ShadowMaps;
2945
2946 /// \brief The declaration contexts we have already visited.
2947 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2948
2949 friend class ShadowContextRAII;
2950
2951public:
2952 /// \brief Determine whether we have already visited this context
2953 /// (and, if not, note that we are going to visit that context now).
2954 bool visitedContext(DeclContext *Ctx) {
David Blaikie82e95a32014-11-19 07:49:47 +00002955 return !VisitedContexts.insert(Ctx).second;
Douglas Gregor2d435302009-12-30 17:04:44 +00002956 }
2957
Douglas Gregor39982192010-08-15 06:18:01 +00002958 bool alreadyVisitedContext(DeclContext *Ctx) {
2959 return VisitedContexts.count(Ctx);
2960 }
2961
Douglas Gregor2d435302009-12-30 17:04:44 +00002962 /// \brief Determine whether the given declaration is hidden in the
2963 /// current scope.
2964 ///
2965 /// \returns the declaration that hides the given declaration, or
2966 /// NULL if no such declaration exists.
2967 NamedDecl *checkHidden(NamedDecl *ND);
2968
2969 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002970 void add(NamedDecl *ND) {
2971 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2972 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002973};
2974
2975/// \brief RAII object that records when we've entered a shadow context.
2976class ShadowContextRAII {
2977 VisibleDeclsRecord &Visible;
2978
2979 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2980
2981public:
2982 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2983 Visible.ShadowMaps.push_back(ShadowMap());
2984 }
2985
2986 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00002987 Visible.ShadowMaps.pop_back();
2988 }
2989};
2990
2991} // end anonymous namespace
2992
Douglas Gregor2d435302009-12-30 17:04:44 +00002993NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002994 // Look through using declarations.
2995 ND = ND->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002996
Douglas Gregor2d435302009-12-30 17:04:44 +00002997 unsigned IDNS = ND->getIdentifierNamespace();
2998 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2999 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3000 SM != SMEnd; ++SM) {
3001 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
3002 if (Pos == SM->end())
3003 continue;
3004
Aaron Ballman1e606f42014-07-15 22:03:49 +00003005 for (auto *D : Pos->second) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003006 // A tag declaration does not hide a non-tag declaration.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003007 if (D->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003008 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00003009 Decl::IDNS_ObjCProtocol)))
3010 continue;
3011
3012 // Protocols are in distinct namespaces from everything else.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003013 if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor2d435302009-12-30 17:04:44 +00003014 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Aaron Ballman1e606f42014-07-15 22:03:49 +00003015 D->getIdentifierNamespace() != IDNS)
Douglas Gregor2d435302009-12-30 17:04:44 +00003016 continue;
3017
Douglas Gregor09bbc652010-01-14 15:47:35 +00003018 // Functions and function templates in the same scope overload
3019 // rather than hide. FIXME: Look for hiding based on function
3020 // signatures!
Aaron Ballman1e606f42014-07-15 22:03:49 +00003021 if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Alp Tokera2794f92014-01-22 07:29:52 +00003022 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00003023 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00003024 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003025
Douglas Gregor2d435302009-12-30 17:04:44 +00003026 // We've found a declaration that hides this one.
Aaron Ballman1e606f42014-07-15 22:03:49 +00003027 return D;
Douglas Gregor2d435302009-12-30 17:04:44 +00003028 }
3029 }
3030
Craig Topperc3ec1492014-05-26 06:22:03 +00003031 return nullptr;
Douglas Gregor2d435302009-12-30 17:04:44 +00003032}
3033
3034static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
3035 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003036 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00003037 VisibleDeclConsumer &Consumer,
3038 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00003039 if (!Ctx)
3040 return;
3041
Douglas Gregor2d435302009-12-30 17:04:44 +00003042 // Make sure we don't visit the same context twice.
3043 if (Visited.visitedContext(Ctx->getPrimaryContext()))
3044 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003045
Richard Smith9e2341d2015-03-23 03:25:59 +00003046 // Outside C++, lookup results for the TU live on identifiers.
3047 if (isa<TranslationUnitDecl>(Ctx) &&
3048 !Result.getSema().getLangOpts().CPlusPlus) {
3049 auto &S = Result.getSema();
3050 auto &Idents = S.Context.Idents;
3051
3052 // Ensure all external identifiers are in the identifier table.
3053 if (IdentifierInfoLookup *External = Idents.getExternalIdentifierLookup()) {
3054 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
3055 for (StringRef Name = Iter->Next(); !Name.empty(); Name = Iter->Next())
3056 Idents.get(Name);
3057 }
3058
3059 // Walk all lookup results in the TU for each identifier.
3060 for (const auto &Ident : Idents) {
3061 for (auto I = S.IdResolver.begin(Ident.getValue()),
3062 E = S.IdResolver.end();
3063 I != E; ++I) {
3064 if (S.IdResolver.isDeclInScope(*I, Ctx)) {
3065 if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
3066 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3067 Visited.add(ND);
3068 }
3069 }
3070 }
3071 }
3072
3073 return;
3074 }
3075
Douglas Gregor7454c562010-07-02 20:37:36 +00003076 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3077 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3078
Douglas Gregor2d435302009-12-30 17:04:44 +00003079 // Enumerate all of the results in this context.
Richard Trieu20abd6b2015-04-15 03:48:48 +00003080 for (DeclContextLookupResult R : Ctx->lookups()) {
Richard Smith9e2341d2015-03-23 03:25:59 +00003081 for (auto *D : R) {
3082 if (auto *ND = Result.getAcceptableDecl(D)) {
3083 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3084 Visited.add(ND);
Douglas Gregora3b23b02010-12-09 21:44:02 +00003085 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003086 }
3087 }
3088
3089 // Traverse using directives for qualified name lookup.
3090 if (QualifiedNameLookup) {
3091 ShadowContextRAII Shadow(Visited);
Aaron Ballman804a7fb2014-03-17 17:14:12 +00003092 for (auto I : Ctx->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00003093 LookupVisibleDecls(I->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003094 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003095 }
3096 }
3097
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003098 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00003099 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00003100 if (!Record->hasDefinition())
3101 return;
3102
Aaron Ballman574705e2014-03-13 15:41:46 +00003103 for (const auto &B : Record->bases()) {
3104 QualType BaseType = B.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003105
Douglas Gregor2d435302009-12-30 17:04:44 +00003106 // Don't look into dependent bases, because name lookup can't look
3107 // there anyway.
3108 if (BaseType->isDependentType())
3109 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003110
Douglas Gregor2d435302009-12-30 17:04:44 +00003111 const RecordType *Record = BaseType->getAs<RecordType>();
3112 if (!Record)
3113 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003114
Douglas Gregor2d435302009-12-30 17:04:44 +00003115 // FIXME: It would be nice to be able to determine whether referencing
3116 // a particular member would be ambiguous. For example, given
3117 //
3118 // struct A { int member; };
3119 // struct B { int member; };
3120 // struct C : A, B { };
3121 //
3122 // void f(C *c) { c->### }
3123 //
3124 // accessing 'member' would result in an ambiguity. However, we
3125 // could be smart enough to qualify the member with the base
3126 // class, e.g.,
3127 //
3128 // c->B::member
3129 //
3130 // or
3131 //
3132 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003133
Douglas Gregor2d435302009-12-30 17:04:44 +00003134 // Find results in this base class (and its bases).
3135 ShadowContextRAII Shadow(Visited);
3136 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003137 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003138 }
3139 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003140
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003141 // Traverse the contexts of Objective-C classes.
3142 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3143 // Traverse categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003144 for (auto *Cat : IFace->visible_categories()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003145 ShadowContextRAII Shadow(Visited);
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003146 LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003147 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003148 }
3149
3150 // Traverse protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003151 for (auto *I : IFace->all_referenced_protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003152 ShadowContextRAII Shadow(Visited);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003153 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003154 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003155 }
3156
3157 // Traverse the superclass.
3158 if (IFace->getSuperClass()) {
3159 ShadowContextRAII Shadow(Visited);
3160 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003161 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003162 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003163
Douglas Gregor0b59e802010-04-19 18:02:19 +00003164 // If there is an implementation, traverse it. We do this to find
3165 // synthesized ivars.
3166 if (IFace->getImplementation()) {
3167 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003168 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky13668f22012-04-03 20:26:45 +00003169 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor0b59e802010-04-19 18:02:19 +00003170 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003171 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003172 for (auto *I : Protocol->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003173 ShadowContextRAII Shadow(Visited);
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003174 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003175 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003176 }
3177 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003178 for (auto *I : Category->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003179 ShadowContextRAII Shadow(Visited);
Aaron Ballman19a41762014-03-14 12:55:57 +00003180 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003181 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003182 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003183
Douglas Gregor0b59e802010-04-19 18:02:19 +00003184 // If there is an implementation, traverse it.
3185 if (Category->getImplementation()) {
3186 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003187 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00003188 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003189 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003190 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003191}
3192
3193static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3194 UnqualUsingDirectiveSet &UDirs,
3195 VisibleDeclConsumer &Consumer,
3196 VisibleDeclsRecord &Visited) {
3197 if (!S)
3198 return;
3199
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003200 if (!S->getEntity() ||
3201 (!S->getParent() &&
Ted Kremenekc37877d2013-10-08 17:08:03 +00003202 !Visited.alreadyVisitedContext(S->getEntity())) ||
3203 (S->getEntity())->isFunctionOrMethod()) {
Richard Smith541b38b2013-09-20 01:15:31 +00003204 FindLocalExternScope FindLocals(Result);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003205 // Walk through the declarations in this Scope.
Aaron Ballman35c54952014-03-17 16:55:25 +00003206 for (auto *D : S->decls()) {
3207 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Douglas Gregor4a814562011-12-14 16:03:29 +00003208 if ((ND = Result.getAcceptableDecl(ND))) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003209 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003210 Visited.add(ND);
3211 }
3212 }
3213 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003214
Douglas Gregor66230062010-03-15 14:33:29 +00003215 // FIXME: C++ [temp.local]p8
Craig Topperc3ec1492014-05-26 06:22:03 +00003216 DeclContext *Entity = nullptr;
Douglas Gregor4f248632010-01-01 17:44:25 +00003217 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003218 // Look into this scope's declaration context, along with any of its
3219 // parent lookup contexts (e.g., enclosing classes), up to the point
3220 // where we hit the context stored in the next outer scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00003221 Entity = S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00003222 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003223
Douglas Gregorea166062010-03-15 15:26:48 +00003224 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00003225 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003226 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3227 if (Method->isInstanceMethod()) {
3228 // For instance methods, look for ivars in the method's interface.
3229 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3230 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003231 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003232 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Richard Smithe156254d2013-08-20 20:35:18 +00003233 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003234 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003235 }
3236
3237 // We've already performed all of the name lookup that we need
3238 // to for Objective-C methods; the next context will be the
3239 // outer scope.
3240 break;
3241 }
3242
Douglas Gregor2d435302009-12-30 17:04:44 +00003243 if (Ctx->isFunctionOrMethod())
3244 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003245
3246 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003247 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003248 }
3249 } else if (!S->getParent()) {
3250 // Look into the translation unit scope. We walk through the translation
3251 // unit's declaration context, because the Scope itself won't have all of
3252 // the declarations if we loaded a precompiled header.
3253 // FIXME: We would like the translation unit's Scope object to point to the
3254 // translation unit, so we don't need this special "if" branch. However,
3255 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003256 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00003257 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003258 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00003259 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003260 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003261 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003262 }
3263
Douglas Gregor2d435302009-12-30 17:04:44 +00003264 if (Entity) {
3265 // Lookup visible declarations in any namespaces found by using
3266 // directives.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003267 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
3268 LookupVisibleDecls(const_cast<DeclContext *>(UUE.getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003269 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003270 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003271 }
3272
3273 // Lookup names in the parent scope.
3274 ShadowContextRAII Shadow(Visited);
3275 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3276}
3277
3278void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003279 VisibleDeclConsumer &Consumer,
3280 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003281 // Determine the set of using directives available during
3282 // unqualified name lookup.
3283 Scope *Initial = S;
3284 UnqualUsingDirectiveSet UDirs;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003285 if (getLangOpts().CPlusPlus) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003286 // Find the first namespace or translation-unit scope.
3287 while (S && !isNamespaceOrTranslationUnitScope(S))
3288 S = S->getParent();
3289
3290 UDirs.visitScopeChain(Initial, S);
3291 }
3292 UDirs.done();
3293
3294 // Look for visible declarations.
3295 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003296 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003297 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003298 if (!IncludeGlobalScope)
3299 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003300 ShadowContextRAII Shadow(Visited);
3301 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3302}
3303
3304void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003305 VisibleDeclConsumer &Consumer,
3306 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003307 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003308 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003309 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003310 if (!IncludeGlobalScope)
3311 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003312 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003313 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003314 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003315}
3316
Chris Lattner43e7f312011-02-18 02:08:43 +00003317/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003318/// If GnuLabelLoc is a valid source location, then this is a definition
3319/// of an __label__ label name, otherwise it is a normal label definition
3320/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003321LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003322 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003323 // Do a lookup to see if we have a label with this name already.
Craig Topperc3ec1492014-05-26 06:22:03 +00003324 NamedDecl *Res = nullptr;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003325
3326 if (GnuLabelLoc.isValid()) {
3327 // Local label definitions always shadow existing labels.
3328 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3329 Scope *S = CurScope;
3330 PushOnScopeChains(Res, S, true);
3331 return cast<LabelDecl>(Res);
3332 }
3333
3334 // Not a GNU local label.
3335 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3336 // If we found a label, check to see if it is in the same context as us.
3337 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003338 if (Res && Res->getDeclContext() != CurContext)
Craig Topperc3ec1492014-05-26 06:22:03 +00003339 Res = nullptr;
3340 if (!Res) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003341 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003342 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3343 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003344 assert(S && "Not in a function?");
3345 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003346 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003347 return cast<LabelDecl>(Res);
3348}
3349
3350//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003351// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003352//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003353
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003354static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3355 TypoCorrection &Candidate) {
3356 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3357 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3358}
3359
3360static void LookupPotentialTypoResult(Sema &SemaRef,
3361 LookupResult &Res,
3362 IdentifierInfo *Name,
3363 Scope *S, CXXScopeSpec *SS,
3364 DeclContext *MemberContext,
3365 bool EnteringContext,
3366 bool isObjCIvarLookup,
3367 bool FindHidden);
3368
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003369/// \brief Check whether the declarations found for a typo correction are
3370/// visible, and if none of them are, convert the correction to an 'import
3371/// a module' correction.
3372static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
3373 if (TC.begin() == TC.end())
3374 return;
3375
3376 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3377
3378 for (/**/; DI != DE; ++DI)
3379 if (!LookupResult::isVisible(SemaRef, *DI))
3380 break;
3381 // Nothing to do if all decls are visible.
3382 if (DI == DE)
3383 return;
3384
3385 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3386 bool AnyVisibleDecls = !NewDecls.empty();
3387
3388 for (/**/; DI != DE; ++DI) {
3389 NamedDecl *VisibleDecl = *DI;
3390 if (!LookupResult::isVisible(SemaRef, *DI))
3391 VisibleDecl = findAcceptableDecl(SemaRef, *DI);
3392
3393 if (VisibleDecl) {
3394 if (!AnyVisibleDecls) {
3395 // Found a visible decl, discard all hidden ones.
3396 AnyVisibleDecls = true;
3397 NewDecls.clear();
3398 }
3399 NewDecls.push_back(VisibleDecl);
3400 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
3401 NewDecls.push_back(*DI);
3402 }
3403
3404 if (NewDecls.empty())
3405 TC = TypoCorrection();
3406 else {
3407 TC.setCorrectionDecls(NewDecls);
3408 TC.setRequiresImport(!AnyVisibleDecls);
3409 }
3410}
3411
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003412// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3413// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3414// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3415static void getNestedNameSpecifierIdentifiers(
3416 NestedNameSpecifier *NNS,
3417 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3418 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3419 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3420 else
3421 Identifiers.clear();
3422
3423 const IdentifierInfo *II = nullptr;
3424
3425 switch (NNS->getKind()) {
3426 case NestedNameSpecifier::Identifier:
3427 II = NNS->getAsIdentifier();
3428 break;
3429
3430 case NestedNameSpecifier::Namespace:
3431 if (NNS->getAsNamespace()->isAnonymousNamespace())
3432 return;
3433 II = NNS->getAsNamespace()->getIdentifier();
3434 break;
3435
3436 case NestedNameSpecifier::NamespaceAlias:
3437 II = NNS->getAsNamespaceAlias()->getIdentifier();
3438 break;
3439
3440 case NestedNameSpecifier::TypeSpecWithTemplate:
3441 case NestedNameSpecifier::TypeSpec:
3442 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3443 break;
3444
3445 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00003446 case NestedNameSpecifier::Super:
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003447 return;
3448 }
3449
3450 if (II)
3451 Identifiers.push_back(II);
3452}
3453
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003454void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003455 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003456 // Don't consider hidden names for typo correction.
3457 if (Hiding)
3458 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003459
Douglas Gregor2d435302009-12-30 17:04:44 +00003460 // Only consider entities with identifiers for names, ignoring
3461 // special names (constructors, overloaded operators, selectors,
3462 // etc.).
3463 IdentifierInfo *Name = ND->getIdentifier();
3464 if (!Name)
3465 return;
3466
Richard Smithe156254d2013-08-20 20:35:18 +00003467 // Only consider visible declarations and declarations from modules with
3468 // names that exactly match.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003469 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo &&
Richard Smithe156254d2013-08-20 20:35:18 +00003470 !findAcceptableDecl(SemaRef, ND))
3471 return;
3472
Douglas Gregor57756ea2010-10-14 22:11:03 +00003473 FoundName(Name->getName());
3474}
3475
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003476void TypoCorrectionConsumer::FoundName(StringRef Name) {
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003477 // Compute the edit distance between the typo and the name of this
3478 // entity, and add the identifier to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003479 addName(Name, nullptr);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003480}
3481
3482void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3483 // Compute the edit distance between the typo and this keyword,
3484 // and add the keyword to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003485 addName(Keyword, nullptr, nullptr, true);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003486}
3487
3488void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
3489 NestedNameSpecifier *NNS, bool isKeyword) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003490 // Use a simple length-based heuristic to determine the minimum possible
3491 // edit distance. If the minimum isn't good enough, bail out early.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003492 StringRef TypoStr = Typo->getName();
3493 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
3494 if (MinED && TypoStr.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00003495 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003496
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003497 // Compute an upper bound on the allowable edit distance, so that the
3498 // edit-distance algorithm can short-circuit.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003499 unsigned UpperBound = (TypoStr.size() + 2) / 3 + 1;
3500 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003501 if (ED >= UpperBound) return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003502
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003503 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003504 if (isKeyword) TC.makeKeyword();
Kaelyn Takata0a313022014-11-20 22:06:26 +00003505 TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003506 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003507}
3508
Kaelyn Takatad2287c32014-10-27 18:07:13 +00003509static const unsigned MaxTypoDistanceResultSets = 5;
3510
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003511void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003512 StringRef TypoStr = Typo->getName();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003513 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003514
3515 // For very short typos, ignore potential corrections that have a different
3516 // base identifier from the typo or which have a normalized edit distance
3517 // longer than the typo itself.
3518 if (TypoStr.size() < 3 &&
3519 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
3520 return;
3521
3522 // If the correction is resolved but is not viable, ignore it.
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003523 if (Correction.isResolved()) {
3524 checkCorrectionVisibility(SemaRef, Correction);
3525 if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
3526 return;
3527 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003528
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003529 TypoResultList &CList =
3530 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003531
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003532 if (!CList.empty() && !CList.back().isResolved())
3533 CList.pop_back();
3534 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3535 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3536 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3537 RI != RIEnd; ++RI) {
3538 // If the Correction refers to a decl already in the result list,
3539 // replace the existing result if the string representation of Correction
3540 // comes before the current result alphabetically, then stop as there is
3541 // nothing more to be done to add Correction to the candidate set.
3542 if (RI->getCorrectionDecl() == NewND) {
3543 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3544 *RI = Correction;
3545 return;
3546 }
3547 }
3548 }
3549 if (CList.empty() || Correction.isResolved())
3550 CList.push_back(Correction);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003551
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003552 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003553 CorrectionResults.erase(std::prev(CorrectionResults.end()));
3554}
3555
3556void TypoCorrectionConsumer::addNamespaces(
3557 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
3558 SearchNamespaces = true;
3559
3560 for (auto KNPair : KnownNamespaces)
3561 Namespaces.addNameSpecifier(KNPair.first);
3562
3563 bool SSIsTemplate = false;
3564 if (NestedNameSpecifier *NNS =
3565 (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
3566 if (const Type *T = NNS->getAsType())
3567 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
3568 }
3569 for (const auto *TI : SemaRef.getASTContext().types()) {
3570 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
3571 CD = CD->getCanonicalDecl();
3572 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
3573 !CD->isUnion() && CD->getIdentifier() &&
3574 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
3575 (CD->isBeingDefined() || CD->isCompleteDefinition()))
3576 Namespaces.addNameSpecifier(CD);
3577 }
3578 }
3579}
3580
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003581const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
3582 if (++CurrentTCIndex < ValidatedCorrections.size())
3583 return ValidatedCorrections[CurrentTCIndex];
3584
3585 CurrentTCIndex = ValidatedCorrections.size();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003586 while (!CorrectionResults.empty()) {
3587 auto DI = CorrectionResults.begin();
3588 if (DI->second.empty()) {
3589 CorrectionResults.erase(DI);
3590 continue;
3591 }
3592
3593 auto RI = DI->second.begin();
3594 if (RI->second.empty()) {
3595 DI->second.erase(RI);
3596 performQualifiedLookups();
3597 continue;
3598 }
3599
3600 TypoCorrection TC = RI->second.pop_back_val();
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003601 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003602 ValidatedCorrections.push_back(TC);
3603 return ValidatedCorrections[CurrentTCIndex];
3604 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003605 }
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003606 return ValidatedCorrections[0]; // The empty correction.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003607}
3608
3609bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
3610 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
3611 DeclContext *TempMemberContext = MemberContext;
Kaelyn Takata6c759512014-10-27 18:07:37 +00003612 CXXScopeSpec *TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003613retry_lookup:
3614 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
3615 EnteringContext,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00003616 CorrectionValidator->IsObjCIvarLookup,
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003617 Name == Typo && !Candidate.WillReplaceSpecifier());
3618 switch (Result.getResultKind()) {
3619 case LookupResult::NotFound:
3620 case LookupResult::NotFoundInCurrentInstantiation:
3621 case LookupResult::FoundUnresolvedValue:
3622 if (TempSS) {
3623 // Immediately retry the lookup without the given CXXScopeSpec
3624 TempSS = nullptr;
3625 Candidate.WillReplaceSpecifier(true);
3626 goto retry_lookup;
3627 }
3628 if (TempMemberContext) {
3629 if (SS && !TempSS)
Kaelyn Takata6c759512014-10-27 18:07:37 +00003630 TempSS = SS.get();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003631 TempMemberContext = nullptr;
3632 goto retry_lookup;
3633 }
3634 if (SearchNamespaces)
3635 QualifiedResults.push_back(Candidate);
3636 break;
3637
3638 case LookupResult::Ambiguous:
3639 // We don't deal with ambiguities.
3640 break;
3641
3642 case LookupResult::Found:
3643 case LookupResult::FoundOverloaded:
3644 // Store all of the Decls for overloaded symbols
3645 for (auto *TRD : Result)
3646 Candidate.addCorrectionDecl(TRD);
Kaelyn Takata9ab7fb62014-10-27 18:07:40 +00003647 checkCorrectionVisibility(SemaRef, Candidate);
Kaelyn Takata89c881b2014-10-27 18:07:29 +00003648 if (!isCandidateViable(*CorrectionValidator, Candidate)) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003649 if (SearchNamespaces)
3650 QualifiedResults.push_back(Candidate);
3651 break;
3652 }
Kaelyn Takata20deb1d2015-01-28 00:46:09 +00003653 Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003654 return true;
3655 }
3656 return false;
3657}
3658
3659void TypoCorrectionConsumer::performQualifiedLookups() {
3660 unsigned TypoLen = Typo->getName().size();
3661 for (auto QR : QualifiedResults) {
3662 for (auto NSI : Namespaces) {
3663 DeclContext *Ctx = NSI.DeclCtx;
3664 const Type *NSType = NSI.NameSpecifier->getAsType();
3665
3666 // If the current NestedNameSpecifier refers to a class and the
3667 // current correction candidate is the name of that class, then skip
3668 // it as it is unlikely a qualified version of the class' constructor
3669 // is an appropriate correction.
3670 if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() : 0) {
3671 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
3672 continue;
3673 }
3674
3675 TypoCorrection TC(QR);
3676 TC.ClearCorrectionDecls();
3677 TC.setCorrectionSpecifier(NSI.NameSpecifier);
3678 TC.setQualifierDistance(NSI.EditDistance);
3679 TC.setCallbackDistance(0); // Reset the callback distance
3680
3681 // If the current correction candidate and namespace combination are
3682 // too far away from the original typo based on the normalized edit
3683 // distance, then skip performing a qualified name lookup.
3684 unsigned TmpED = TC.getEditDistance(true);
3685 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
3686 TypoLen / TmpED < 3)
3687 continue;
3688
3689 Result.clear();
3690 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
3691 if (!SemaRef.LookupQualifiedName(Result, Ctx))
3692 continue;
3693
3694 // Any corrections added below will be validated in subsequent
3695 // iterations of the main while() loop over the Consumer's contents.
3696 switch (Result.getResultKind()) {
3697 case LookupResult::Found:
3698 case LookupResult::FoundOverloaded: {
3699 if (SS && SS->isValid()) {
3700 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
3701 std::string OldQualified;
3702 llvm::raw_string_ostream OldOStream(OldQualified);
3703 SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
3704 OldOStream << Typo->getName();
3705 // If correction candidate would be an identical written qualified
3706 // identifer, then the existing CXXScopeSpec probably included a
3707 // typedef that didn't get accounted for properly.
3708 if (OldOStream.str() == NewQualified)
3709 break;
3710 }
3711 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
3712 TRD != TRDEnd; ++TRD) {
3713 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
3714 NSType ? NSType->getAsCXXRecordDecl()
3715 : nullptr,
3716 TRD.getPair()) == Sema::AR_accessible)
3717 TC.addCorrectionDecl(*TRD);
3718 }
Kaelyn Takata0a313022014-11-20 22:06:26 +00003719 if (TC.isResolved()) {
3720 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003721 addCorrection(TC);
Kaelyn Takata0a313022014-11-20 22:06:26 +00003722 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003723 break;
3724 }
3725 case LookupResult::NotFound:
3726 case LookupResult::NotFoundInCurrentInstantiation:
3727 case LookupResult::Ambiguous:
3728 case LookupResult::FoundUnresolvedValue:
3729 break;
3730 }
3731 }
3732 }
3733 QualifiedResults.clear();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003734}
3735
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00003736TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
3737 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
Benjamin Kramer15537272015-03-13 16:10:42 +00003738 : Context(Context), CurContextChain(buildContextChain(CurContext)) {
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00003739 if (NestedNameSpecifier *NNS =
3740 CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
3741 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
3742 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3743
3744 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
3745 }
3746 // Build the list of identifiers that would be used for an absolute
3747 // (from the global context) NestedNameSpecifier referring to the current
3748 // context.
3749 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3750 CEnd = CurContextChain.rend();
3751 C != CEnd; ++C) {
3752 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3753 CurContextIdentifiers.push_back(ND->getIdentifier());
3754 }
3755
3756 // Add the global context as a NestedNameSpecifier
Hans Wennborg66010132014-06-11 21:24:13 +00003757 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
3758 NestedNameSpecifier::GlobalSpecifier(Context), 1};
3759 DistanceMap[1].push_back(SI);
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00003760}
3761
Kaelyn Takata7dcc0e62014-06-11 18:07:08 +00003762auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
3763 DeclContext *Start) -> DeclContextList {
Nick Lewycky0d9b3192013-04-08 21:55:21 +00003764 assert(Start && "Building a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003765 DeclContextList Chain;
Craig Topperc3ec1492014-05-26 06:22:03 +00003766 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003767 DC = DC->getLookupParent()) {
3768 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3769 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3770 !(ND && ND->isAnonymousNamespace()))
3771 Chain.push_back(DC->getPrimaryContext());
3772 }
3773 return Chain;
3774}
3775
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003776unsigned
3777TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
3778 DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003779 unsigned NumSpecifiers = 0;
3780 for (DeclContextList::reverse_iterator C = DeclChain.rbegin(),
3781 CEnd = DeclChain.rend();
3782 C != CEnd; ++C) {
3783 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) {
3784 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3785 ++NumSpecifiers;
3786 } else if (RecordDecl *RD = dyn_cast_or_null<RecordDecl>(*C)) {
3787 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
3788 RD->getTypeForDecl());
3789 ++NumSpecifiers;
3790 }
3791 }
3792 return NumSpecifiers;
3793}
3794
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003795void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
3796 DeclContext *Ctx) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003797 NestedNameSpecifier *NNS = nullptr;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003798 unsigned NumSpecifiers = 0;
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003799 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003800 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
3801
3802 // Eliminate common elements from the two DeclContext chains.
3803 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3804 CEnd = CurContextChain.rend();
3805 C != CEnd && !NamespaceDeclChain.empty() &&
3806 NamespaceDeclChain.back() == *C; ++C) {
3807 NamespaceDeclChain.pop_back();
3808 }
3809
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003810 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003811 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003812
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003813 // Add an explicit leading '::' specifier if needed.
3814 if (NamespaceDeclChain.empty()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003815 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003816 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003817 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003818 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003819 } else if (NamedDecl *ND =
3820 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003821 IdentifierInfo *Name = ND->getIdentifier();
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003822 bool SameNameSpecifier = false;
3823 if (std::find(CurNameSpecifierIdentifiers.begin(),
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003824 CurNameSpecifierIdentifiers.end(),
3825 Name) != CurNameSpecifierIdentifiers.end()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003826 std::string NewNameSpecifier;
3827 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
3828 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
3829 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3830 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3831 SpecifierOStream.flush();
3832 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003833 }
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003834 if (SameNameSpecifier ||
3835 std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3836 Name) != CurContextIdentifiers.end()) {
3837 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
3838 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3839 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003840 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003841 }
3842 }
3843
3844 // If the built NestedNameSpecifier would be replacing an existing
3845 // NestedNameSpecifier, use the number of component identifiers that
3846 // would need to be changed as the edit distance instead of the number
3847 // of components in the built NestedNameSpecifier.
3848 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3849 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3850 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3851 NumSpecifiers = llvm::ComputeEditDistance(
Craig Topper8c2a2a02014-08-30 16:55:39 +00003852 llvm::makeArrayRef(CurNameSpecifierIdentifiers),
3853 llvm::makeArrayRef(NewNameSpecifierIdentifiers));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003854 }
3855
Hans Wennborg66010132014-06-11 21:24:13 +00003856 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
3857 DistanceMap[NumSpecifiers].push_back(SI);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003858}
3859
Douglas Gregord507d772010-10-20 03:06:34 +00003860/// \brief Perform name lookup for a possible result for typo correction.
3861static void LookupPotentialTypoResult(Sema &SemaRef,
3862 LookupResult &Res,
3863 IdentifierInfo *Name,
3864 Scope *S, CXXScopeSpec *SS,
3865 DeclContext *MemberContext,
3866 bool EnteringContext,
Richard Smithe156254d2013-08-20 20:35:18 +00003867 bool isObjCIvarLookup,
3868 bool FindHidden) {
Douglas Gregord507d772010-10-20 03:06:34 +00003869 Res.suppressDiagnostics();
3870 Res.clear();
3871 Res.setLookupName(Name);
Richard Smithe156254d2013-08-20 20:35:18 +00003872 Res.setAllowHidden(FindHidden);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003873 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00003874 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003875 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00003876 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3877 Res.addDecl(Ivar);
3878 Res.resolveKind();
3879 return;
3880 }
3881 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003882
Douglas Gregord507d772010-10-20 03:06:34 +00003883 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3884 Res.addDecl(Prop);
3885 Res.resolveKind();
3886 return;
3887 }
3888 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003889
Douglas Gregord507d772010-10-20 03:06:34 +00003890 SemaRef.LookupQualifiedName(Res, MemberContext);
3891 return;
3892 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003893
3894 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00003895 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003896
Douglas Gregord507d772010-10-20 03:06:34 +00003897 // Fake ivar lookup; this should really be part of
3898 // LookupParsedName.
3899 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3900 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003901 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00003902 (Res.isSingleResult() &&
3903 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003904 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00003905 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3906 Res.addDecl(IV);
3907 Res.resolveKind();
3908 }
3909 }
3910 }
3911}
3912
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003913/// \brief Add keywords to the consumer as possible typo corrections.
3914static void AddKeywordsToConsumer(Sema &SemaRef,
3915 TypoCorrectionConsumer &Consumer,
Richard Smithb3a1df02012-06-08 21:35:42 +00003916 Scope *S, CorrectionCandidateCallback &CCC,
3917 bool AfterNestedNameSpecifier) {
3918 if (AfterNestedNameSpecifier) {
3919 // For 'X::', we know exactly which keywords can appear next.
3920 Consumer.addKeywordResult("template");
3921 if (CCC.WantExpressionKeywords)
3922 Consumer.addKeywordResult("operator");
3923 return;
3924 }
3925
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003926 if (CCC.WantObjCSuper)
3927 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003928
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003929 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003930 // Add type-specifier keywords to the set of results.
Craig Topperd6d31ac2013-07-15 08:24:27 +00003931 static const char *const CTypeSpecs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003932 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00003933 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003934 "_Complex", "_Imaginary",
3935 // storage-specifiers as well
3936 "extern", "inline", "static", "typedef"
3937 };
3938
Craig Toppere5ce8312013-07-15 03:38:40 +00003939 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003940 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3941 Consumer.addKeywordResult(CTypeSpecs[I]);
3942
David Blaikiebbafb8a2012-03-11 07:00:24 +00003943 if (SemaRef.getLangOpts().C99)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003944 Consumer.addKeywordResult("restrict");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003945 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003946 Consumer.addKeywordResult("bool");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003947 else if (SemaRef.getLangOpts().C99)
Douglas Gregor3b22a882011-07-01 21:27:45 +00003948 Consumer.addKeywordResult("_Bool");
3949
David Blaikiebbafb8a2012-03-11 07:00:24 +00003950 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003951 Consumer.addKeywordResult("class");
3952 Consumer.addKeywordResult("typename");
3953 Consumer.addKeywordResult("wchar_t");
3954
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003955 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003956 Consumer.addKeywordResult("char16_t");
3957 Consumer.addKeywordResult("char32_t");
3958 Consumer.addKeywordResult("constexpr");
3959 Consumer.addKeywordResult("decltype");
3960 Consumer.addKeywordResult("thread_local");
3961 }
3962 }
3963
David Blaikiebbafb8a2012-03-11 07:00:24 +00003964 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003965 Consumer.addKeywordResult("typeof");
Kaelyn Takatab04846b2014-07-28 18:14:02 +00003966 } else if (CCC.WantFunctionLikeCasts) {
3967 static const char *const CastableTypeSpecs[] = {
3968 "char", "double", "float", "int", "long", "short",
3969 "signed", "unsigned", "void"
3970 };
3971 for (auto *kw : CastableTypeSpecs)
3972 Consumer.addKeywordResult(kw);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003973 }
3974
David Blaikiebbafb8a2012-03-11 07:00:24 +00003975 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003976 Consumer.addKeywordResult("const_cast");
3977 Consumer.addKeywordResult("dynamic_cast");
3978 Consumer.addKeywordResult("reinterpret_cast");
3979 Consumer.addKeywordResult("static_cast");
3980 }
3981
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003982 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003983 Consumer.addKeywordResult("sizeof");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003984 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003985 Consumer.addKeywordResult("false");
3986 Consumer.addKeywordResult("true");
3987 }
3988
David Blaikiebbafb8a2012-03-11 07:00:24 +00003989 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topperd6d31ac2013-07-15 08:24:27 +00003990 static const char *const CXXExprs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003991 "delete", "new", "operator", "throw", "typeid"
3992 };
Craig Toppere5ce8312013-07-15 03:38:40 +00003993 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003994 for (unsigned I = 0; I != NumCXXExprs; ++I)
3995 Consumer.addKeywordResult(CXXExprs[I]);
3996
3997 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3998 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3999 Consumer.addKeywordResult("this");
4000
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004001 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004002 Consumer.addKeywordResult("alignof");
4003 Consumer.addKeywordResult("nullptr");
4004 }
4005 }
Jordan Rose58d54722012-06-30 21:33:57 +00004006
4007 if (SemaRef.getLangOpts().C11) {
4008 // FIXME: We should not suggest _Alignof if the alignof macro
4009 // is present.
4010 Consumer.addKeywordResult("_Alignof");
4011 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004012 }
4013
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004014 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004015 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
4016 // Statements.
Craig Topperd6d31ac2013-07-15 08:24:27 +00004017 static const char *const CStmts[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004018 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Toppere5ce8312013-07-15 03:38:40 +00004019 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004020 for (unsigned I = 0; I != NumCStmts; ++I)
4021 Consumer.addKeywordResult(CStmts[I]);
4022
David Blaikiebbafb8a2012-03-11 07:00:24 +00004023 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004024 Consumer.addKeywordResult("catch");
4025 Consumer.addKeywordResult("try");
4026 }
4027
4028 if (S && S->getBreakParent())
4029 Consumer.addKeywordResult("break");
4030
4031 if (S && S->getContinueParent())
4032 Consumer.addKeywordResult("continue");
4033
4034 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
4035 Consumer.addKeywordResult("case");
4036 Consumer.addKeywordResult("default");
4037 }
4038 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004039 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004040 Consumer.addKeywordResult("namespace");
4041 Consumer.addKeywordResult("template");
4042 }
4043
4044 if (S && S->isClassScope()) {
4045 Consumer.addKeywordResult("explicit");
4046 Consumer.addKeywordResult("friend");
4047 Consumer.addKeywordResult("mutable");
4048 Consumer.addKeywordResult("private");
4049 Consumer.addKeywordResult("protected");
4050 Consumer.addKeywordResult("public");
4051 Consumer.addKeywordResult("virtual");
4052 }
4053 }
4054
David Blaikiebbafb8a2012-03-11 07:00:24 +00004055 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004056 Consumer.addKeywordResult("using");
4057
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004058 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004059 Consumer.addKeywordResult("static_assert");
4060 }
4061 }
4062}
4063
Kaelyn Takata6c759512014-10-27 18:07:37 +00004064std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
4065 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4066 Scope *S, CXXScopeSpec *SS,
4067 std::unique_ptr<CorrectionCandidateCallback> CCC,
4068 DeclContext *MemberContext, bool EnteringContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004069 const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00004070
4071 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4072 DisableTypoCorrection)
4073 return nullptr;
4074
4075 // In Microsoft mode, don't perform typo correction in a template member
4076 // function dependent context because it interferes with the "lookup into
4077 // dependent bases of class templates" feature.
4078 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
4079 isa<CXXMethodDecl>(CurContext))
4080 return nullptr;
4081
4082 // We only attempt to correct typos for identifiers.
4083 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4084 if (!Typo)
4085 return nullptr;
4086
4087 // If the scope specifier itself was invalid, don't try to correct
4088 // typos.
4089 if (SS && SS->isInvalid())
4090 return nullptr;
4091
4092 // Never try to correct typos during template deduction or
4093 // instantiation.
4094 if (!ActiveTemplateInstantiations.empty())
4095 return nullptr;
4096
4097 // Don't try to correct 'super'.
4098 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4099 return nullptr;
4100
4101 // Abort if typo correction already failed for this specific typo.
4102 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4103 if (locs != TypoCorrectionFailures.end() &&
4104 locs->second.count(TypoName.getLoc()))
4105 return nullptr;
4106
4107 // Don't try to correct the identifier "vector" when in AltiVec mode.
4108 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4109 // remove this workaround.
4110 if (getLangOpts().AltiVec && Typo->isStr("vector"))
4111 return nullptr;
4112
Nick Lewycky24653262014-12-16 21:39:02 +00004113 // Provide a stop gap for files that are just seriously broken. Trying
4114 // to correct all typos can turn into a HUGE performance penalty, causing
4115 // some files to take minutes to get rejected by the parser.
4116 unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
4117 if (Limit && TyposCorrected >= Limit)
4118 return nullptr;
4119 ++TyposCorrected;
4120
Kaelyn Takata6c759512014-10-27 18:07:37 +00004121 // If we're handling a missing symbol error, using modules, and the
4122 // special search all modules option is used, look for a missing import.
4123 if (ErrorRecovery && getLangOpts().Modules &&
4124 getLangOpts().ModulesSearchAll) {
4125 // The following has the side effect of loading the missing module.
4126 getModuleLoader().lookupMissingImports(Typo->getName(),
4127 TypoName.getLocStart());
4128 }
4129
4130 CorrectionCandidateCallback &CCCRef = *CCC;
4131 auto Consumer = llvm::make_unique<TypoCorrectionConsumer>(
4132 *this, TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
4133 EnteringContext);
4134
Kaelyn Takata6c759512014-10-27 18:07:37 +00004135 // Perform name lookup to find visible, similarly-named entities.
Nick Lewycky24653262014-12-16 21:39:02 +00004136 bool IsUnqualifiedLookup = false;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004137 DeclContext *QualifiedDC = MemberContext;
4138 if (MemberContext) {
4139 LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
4140
4141 // Look in qualified interfaces.
4142 if (OPT) {
4143 for (auto *I : OPT->quals())
4144 LookupVisibleDecls(I, LookupKind, *Consumer);
4145 }
4146 } else if (SS && SS->isSet()) {
4147 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4148 if (!QualifiedDC)
4149 return nullptr;
4150
Kaelyn Takata6c759512014-10-27 18:07:37 +00004151 LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
4152 } else {
4153 IsUnqualifiedLookup = true;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004154 }
4155
4156 // Determine whether we are going to search in the various namespaces for
4157 // corrections.
4158 bool SearchNamespaces
4159 = getLangOpts().CPlusPlus &&
4160 (IsUnqualifiedLookup || (SS && SS->isSet()));
4161
4162 if (IsUnqualifiedLookup || SearchNamespaces) {
4163 // For unqualified lookup, look through all of the names that we have
4164 // seen in this translation unit.
4165 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4166 for (const auto &I : Context.Idents)
4167 Consumer->FoundName(I.getKey());
4168
4169 // Walk through identifiers in external identifier sources.
4170 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4171 if (IdentifierInfoLookup *External
4172 = Context.Idents.getExternalIdentifierLookup()) {
4173 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4174 do {
4175 StringRef Name = Iter->Next();
4176 if (Name.empty())
4177 break;
4178
4179 Consumer->FoundName(Name);
4180 } while (true);
4181 }
4182 }
4183
4184 AddKeywordsToConsumer(*this, *Consumer, S, CCCRef, SS && SS->isNotEmpty());
4185
4186 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4187 // to search those namespaces.
4188 if (SearchNamespaces) {
4189 // Load any externally-known namespaces.
4190 if (ExternalSource && !LoadedExternalKnownNamespaces) {
4191 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
4192 LoadedExternalKnownNamespaces = true;
4193 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4194 for (auto *N : ExternalKnownNamespaces)
4195 KnownNamespaces[N] = true;
4196 }
4197
4198 Consumer->addNamespaces(KnownNamespaces);
4199 }
4200
4201 return Consumer;
4202}
4203
Douglas Gregor2d435302009-12-30 17:04:44 +00004204/// \brief Try to "correct" a typo in the source code by finding
4205/// visible declarations whose names are similar to the name that was
4206/// present in the source code.
4207///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004208/// \param TypoName the \c DeclarationNameInfo structure that contains
4209/// the name that was present in the source code along with its location.
4210///
4211/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00004212///
4213/// \param S the scope in which name lookup occurs.
4214///
4215/// \param SS the nested-name-specifier that precedes the name we're
4216/// looking for, if present.
4217///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004218/// \param CCC A CorrectionCandidateCallback object that provides further
4219/// validation of typo correction candidates. It also provides flags for
4220/// determining the set of keywords permitted.
4221///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00004222/// \param MemberContext if non-NULL, the context in which to look for
4223/// a member access expression.
4224///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004225/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00004226/// the nested-name-specifier SS.
4227///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004228/// \param OPT when non-NULL, the search for visible declarations will
4229/// also walk the protocols in the qualified interfaces of \p OPT.
4230///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004231/// \returns a \c TypoCorrection containing the corrected name if the typo
4232/// along with information such as the \c NamedDecl where the corrected name
4233/// was declared, and any additional \c NestedNameSpecifier needed to access
4234/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
4235TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
4236 Sema::LookupNameKind LookupKind,
4237 Scope *S, CXXScopeSpec *SS,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004238 std::unique_ptr<CorrectionCandidateCallback> CCC,
John Thompson2255f2c2014-04-23 12:57:01 +00004239 CorrectTypoKind Mode,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004240 DeclContext *MemberContext,
4241 bool EnteringContext,
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004242 const ObjCObjectPointerType *OPT,
4243 bool RecordFailure) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004244 assert(CCC && "CorrectTypo requires a CorrectionCandidateCallback");
4245
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004246 // Always let the ExternalSource have the first chance at correction, even
4247 // if we would otherwise have given up.
4248 if (ExternalSource) {
4249 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004250 TypoName, LookupKind, S, SS, *CCC, MemberContext, EnteringContext, OPT))
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004251 return Correction;
4252 }
4253
Kaelyn Takata6c759512014-10-27 18:07:37 +00004254 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4255 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4256 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4257 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
4258 bool ObjCMessageReceiver = CCC->WantObjCSuper && !CCC->WantRemainingKeywords;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004259
Kaelyn Takata6c759512014-10-27 18:07:37 +00004260 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Kaelyn Takata6c759512014-10-27 18:07:37 +00004261 auto Consumer = makeTypoCorrectionConsumer(
4262 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Nick Lewycky24653262014-12-16 21:39:02 +00004263 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004264
Kaelyn Takata6c759512014-10-27 18:07:37 +00004265 if (!Consumer)
4266 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004267
Douglas Gregor280e1ee2010-04-14 20:04:41 +00004268 // If we haven't found anything, we're done.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004269 if (Consumer->empty())
Nick Lewycky24653262014-12-16 21:39:02 +00004270 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregor2d435302009-12-30 17:04:44 +00004271
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004272 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4273 // is not more that about a third of the length of the typo's identifier.
Kaelyn Takata6c759512014-10-27 18:07:37 +00004274 unsigned ED = Consumer->getBestEditDistance(true);
4275 unsigned TypoLen = Typo->getName().size();
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004276 if (ED > 0 && TypoLen / ED < 3)
Nick Lewycky24653262014-12-16 21:39:02 +00004277 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004278
Kaelyn Takata6c759512014-10-27 18:07:37 +00004279 TypoCorrection BestTC = Consumer->getNextCorrection();
4280 TypoCorrection SecondBestTC = Consumer->getNextCorrection();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004281 if (!BestTC)
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004282 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004283
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004284 ED = BestTC.getEditDistance();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004285
Kaelyn Takata6c759512014-10-27 18:07:37 +00004286 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004287 // If this was an unqualified lookup and we believe the callback
4288 // object wouldn't have filtered out possible corrections, note
4289 // that no correction was found.
Nick Lewycky24653262014-12-16 21:39:02 +00004290 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004291 }
4292
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004293 // If only a single name remains, return that result.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004294 if (!SecondBestTC ||
4295 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
4296 const TypoCorrection &Result = BestTC;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004297
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00004298 // Don't correct to a keyword that's the same as the typo; the keyword
4299 // wasn't actually in scope.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004300 if (ED == 0 && Result.isKeyword())
4301 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004302
David Blaikie04ea41c2012-10-12 20:00:44 +00004303 TypoCorrection TC = Result;
4304 TC.setCorrectionRange(SS, TypoName);
Kaelyn Takataa95ebc62014-06-17 23:47:29 +00004305 checkCorrectionVisibility(*this, TC);
David Blaikie04ea41c2012-10-12 20:00:44 +00004306 return TC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004307 } else if (SecondBestTC && ObjCMessageReceiver) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004308 // Prefer 'super' when we're completing in a message-receiver
4309 // context.
4310
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004311 if (BestTC.getCorrection().getAsString() != "super") {
4312 if (SecondBestTC.getCorrection().getAsString() == "super")
4313 BestTC = SecondBestTC;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004314 else if ((*Consumer)["super"].front().isKeyword())
4315 BestTC = (*Consumer)["super"].front();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004316 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004317 // Don't correct to a keyword that's the same as the typo; the keyword
4318 // wasn't actually in scope.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004319 if (BestTC.getEditDistance() == 0 ||
4320 BestTC.getCorrection().getAsString() != "super")
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004321 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004322
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004323 BestTC.setCorrectionRange(SS, TypoName);
4324 return BestTC;
Douglas Gregoraf9eb592010-10-15 13:35:25 +00004325 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004326
Kaelyn Takata73429fd2014-06-10 21:03:49 +00004327 // Record the failure's location if needed and return an empty correction. If
4328 // this was an unqualified lookup and we believe the callback object did not
4329 // filter out possible corrections, also cache the failure for the typo.
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004330 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004331}
4332
Kaelyn Takata6c759512014-10-27 18:07:37 +00004333/// \brief Try to "correct" a typo in the source code by finding
4334/// visible declarations whose names are similar to the name that was
4335/// present in the source code.
4336///
4337/// \param TypoName the \c DeclarationNameInfo structure that contains
4338/// the name that was present in the source code along with its location.
4339///
4340/// \param LookupKind the name-lookup criteria used to search for the name.
4341///
4342/// \param S the scope in which name lookup occurs.
4343///
4344/// \param SS the nested-name-specifier that precedes the name we're
4345/// looking for, if present.
4346///
4347/// \param CCC A CorrectionCandidateCallback object that provides further
4348/// validation of typo correction candidates. It also provides flags for
4349/// determining the set of keywords permitted.
4350///
4351/// \param TDG A TypoDiagnosticGenerator functor that will be used to print
4352/// diagnostics when the actual typo correction is attempted.
4353///
Kaelyn Takata8363f042014-10-27 18:07:42 +00004354/// \param TRC A TypoRecoveryCallback functor that will be used to build an
4355/// Expr from a typo correction candidate.
4356///
Kaelyn Takata6c759512014-10-27 18:07:37 +00004357/// \param MemberContext if non-NULL, the context in which to look for
4358/// a member access expression.
4359///
4360/// \param EnteringContext whether we're entering the context described by
4361/// the nested-name-specifier SS.
4362///
4363/// \param OPT when non-NULL, the search for visible declarations will
4364/// also walk the protocols in the qualified interfaces of \p OPT.
4365///
4366/// \returns a new \c TypoExpr that will later be replaced in the AST with an
4367/// Expr representing the result of performing typo correction, or nullptr if
4368/// typo correction is not possible. If nullptr is returned, no diagnostics will
4369/// be emitted and it is the responsibility of the caller to emit any that are
4370/// needed.
4371TypoExpr *Sema::CorrectTypoDelayed(
4372 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4373 Scope *S, CXXScopeSpec *SS,
4374 std::unique_ptr<CorrectionCandidateCallback> CCC,
Kaelyn Takata8363f042014-10-27 18:07:42 +00004375 TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,
Kaelyn Takata6c759512014-10-27 18:07:37 +00004376 DeclContext *MemberContext, bool EnteringContext,
4377 const ObjCObjectPointerType *OPT) {
4378 assert(CCC && "CorrectTypoDelayed requires a CorrectionCandidateCallback");
4379
4380 TypoCorrection Empty;
Kaelyn Takata6c759512014-10-27 18:07:37 +00004381 auto Consumer = makeTypoCorrectionConsumer(
4382 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
Kaelyn Takataae9e97c2015-01-16 22:11:04 +00004383 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
Kaelyn Takata6c759512014-10-27 18:07:37 +00004384
4385 if (!Consumer || Consumer->empty())
4386 return nullptr;
4387
4388 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4389 // is not more that about a third of the length of the typo's identifier.
4390 unsigned ED = Consumer->getBestEditDistance(true);
4391 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4392 if (ED > 0 && Typo->getName().size() / ED < 3)
4393 return nullptr;
4394
4395 ExprEvalContexts.back().NumTypos++;
Kaelyn Takata8363f042014-10-27 18:07:42 +00004396 return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC));
Kaelyn Takata6c759512014-10-27 18:07:37 +00004397}
4398
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004399void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4400 if (!CDecl) return;
4401
4402 if (isKeyword())
4403 CorrectionDecls.clear();
4404
Kaelyn Uhrainf60b55a2012-11-19 18:49:53 +00004405 CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004406
4407 if (!CorrectionName)
4408 CorrectionName = CDecl->getDeclName();
4409}
4410
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004411std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4412 if (CorrectionNameSpec) {
4413 std::string tmpBuffer;
4414 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4415 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikied4da8722013-05-14 21:04:00 +00004416 PrefixOStream << CorrectionName;
Benjamin Kramer73faad62012-04-14 08:26:28 +00004417 return PrefixOStream.str();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004418 }
4419
4420 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00004421}
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004422
Nico Weberb58e51c2014-11-19 05:21:39 +00004423bool CorrectionCandidateCallback::ValidateCandidate(
4424 const TypoCorrection &candidate) {
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004425 if (!candidate.isResolved())
4426 return true;
4427
4428 if (candidate.isKeyword())
4429 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4430 WantRemainingKeywords || WantObjCSuper;
4431
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004432 bool HasNonType = false;
4433 bool HasStaticMethod = false;
4434 bool HasNonStaticMethod = false;
4435 for (Decl *D : candidate) {
4436 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
4437 D = FTD->getTemplatedDecl();
4438 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4439 if (Method->isStatic())
4440 HasStaticMethod = true;
4441 else
4442 HasNonStaticMethod = true;
4443 }
4444 if (!isa<TypeDecl>(D))
4445 HasNonType = true;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004446 }
4447
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004448 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
4449 !candidate.getCorrectionSpecifier())
4450 return false;
4451
4452 return WantTypeSpecifiers || HasNonType;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004453}
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004454
4455FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004456 bool HasExplicitTemplateArgs,
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004457 MemberExpr *ME)
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004458 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004459 CurContext(SemaRef.CurContext), MemberFn(ME) {
Kaelyn Takatab04846b2014-07-28 18:14:02 +00004460 WantTypeSpecifiers = false;
4461 WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus && NumArgs == 1;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004462 WantRemainingKeywords = false;
4463}
4464
4465bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4466 if (!candidate.getCorrectionDecl())
4467 return candidate.isKeyword();
4468
Aaron Ballman1e606f42014-07-15 22:03:49 +00004469 for (auto *C : candidate) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004470 FunctionDecl *FD = nullptr;
Aaron Ballman1e606f42014-07-15 22:03:49 +00004471 NamedDecl *ND = C->getUnderlyingDecl();
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004472 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4473 FD = FTD->getTemplatedDecl();
4474 if (!HasExplicitTemplateArgs && !FD) {
4475 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4476 // If the Decl is neither a function nor a template function,
4477 // determine if it is a pointer or reference to a function. If so,
4478 // check against the number of arguments expected for the pointee.
4479 QualType ValType = cast<ValueDecl>(ND)->getType();
4480 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4481 ValType = ValType->getPointeeType();
4482 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
Alp Toker9cacbab2014-01-20 20:26:09 +00004483 if (FPT->getNumParams() == NumArgs)
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004484 return true;
4485 }
4486 }
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004487
4488 // Skip the current candidate if it is not a FunctionDecl or does not accept
4489 // the current number of arguments.
4490 if (!FD || !(FD->getNumParams() >= NumArgs &&
4491 FD->getMinRequiredArguments() <= NumArgs))
4492 continue;
4493
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004494 // If the current candidate is a non-static C++ method, skip the candidate
4495 // unless the method being corrected--or the current DeclContext, if the
4496 // function being corrected is not a method--is a method in the same class
4497 // or a descendent class of the candidate's parent class.
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004498 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004499 if (MemberFn || !MD->isStatic()) {
4500 CXXMethodDecl *CurMD =
4501 MemberFn
4502 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
4503 : dyn_cast_or_null<CXXMethodDecl>(CurContext);
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004504 CXXRecordDecl *CurRD =
Craig Topperc3ec1492014-05-26 06:22:03 +00004505 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004506 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
4507 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
4508 continue;
4509 }
4510 }
4511 return true;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004512 }
4513 return false;
4514}
Richard Smithf9b15102013-08-17 00:46:16 +00004515
4516void Sema::diagnoseTypo(const TypoCorrection &Correction,
4517 const PartialDiagnostic &TypoDiag,
4518 bool ErrorRecovery) {
4519 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
4520 ErrorRecovery);
4521}
4522
Richard Smithe156254d2013-08-20 20:35:18 +00004523/// Find which declaration we should import to provide the definition of
4524/// the given declaration.
4525static const NamedDecl *getDefinitionToImport(const NamedDecl *D) {
4526 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4527 return VD->getDefinition();
4528 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +00004529 return FD->isDefined(FD) ? FD : nullptr;
Richard Smithe156254d2013-08-20 20:35:18 +00004530 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
4531 return TD->getDefinition();
4532 if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
4533 return ID->getDefinition();
4534 if (const ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
4535 return PD->getDefinition();
4536 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
4537 return getDefinitionToImport(TD->getTemplatedDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004538 return nullptr;
Richard Smithe156254d2013-08-20 20:35:18 +00004539}
4540
Richard Smithf9b15102013-08-17 00:46:16 +00004541/// \brief Diagnose a successfully-corrected typo. Separated from the correction
4542/// itself to allow external validation of the result, etc.
4543///
4544/// \param Correction The result of performing typo correction.
4545/// \param TypoDiag The diagnostic to produce. This will have the corrected
4546/// string added to it (and usually also a fixit).
4547/// \param PrevNote A note to use when indicating the location of the entity to
4548/// which we are correcting. Will have the correction string added to it.
4549/// \param ErrorRecovery If \c true (the default), the caller is going to
4550/// recover from the typo as if the corrected string had been typed.
4551/// In this case, \c PDiag must be an error, and we will attach a fixit
4552/// to it.
4553void Sema::diagnoseTypo(const TypoCorrection &Correction,
4554 const PartialDiagnostic &TypoDiag,
4555 const PartialDiagnostic &PrevNote,
4556 bool ErrorRecovery) {
4557 std::string CorrectedStr = Correction.getAsString(getLangOpts());
4558 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
4559 FixItHint FixTypo = FixItHint::CreateReplacement(
4560 Correction.getCorrectionRange(), CorrectedStr);
4561
Richard Smithe156254d2013-08-20 20:35:18 +00004562 // Maybe we're just missing a module import.
4563 if (Correction.requiresImport()) {
4564 NamedDecl *Decl = Correction.getCorrectionDecl();
4565 assert(Decl && "import required but no declaration to import");
4566
4567 // Suggest importing a module providing the definition of this entity, if
4568 // possible.
4569 const NamedDecl *Def = getDefinitionToImport(Decl);
4570 if (!Def)
4571 Def = Decl;
4572 Module *Owner = Def->getOwningModule();
4573 assert(Owner && "definition of hidden declaration is not in a module");
4574
4575 Diag(Correction.getCorrectionRange().getBegin(),
4576 diag::err_module_private_declaration)
4577 << Def << Owner->getFullModuleName();
4578 Diag(Def->getLocation(), diag::note_previous_declaration);
4579
4580 // Recover by implicitly importing this module.
Richard Smith3d23c422014-05-07 02:25:43 +00004581 if (ErrorRecovery)
4582 createImplicitModuleImportForErrorRecovery(
4583 Correction.getCorrectionRange().getBegin(), Owner);
Richard Smithe156254d2013-08-20 20:35:18 +00004584 return;
4585 }
4586
Richard Smithf9b15102013-08-17 00:46:16 +00004587 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
4588 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
4589
4590 NamedDecl *ChosenDecl =
Craig Topperc3ec1492014-05-26 06:22:03 +00004591 Correction.isKeyword() ? nullptr : Correction.getCorrectionDecl();
Richard Smithf9b15102013-08-17 00:46:16 +00004592 if (PrevNote.getDiagID() && ChosenDecl)
4593 Diag(ChosenDecl->getLocation(), PrevNote)
4594 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
4595}
Kaelyn Takata6c759512014-10-27 18:07:37 +00004596
Kaelyn Takata8363f042014-10-27 18:07:42 +00004597TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
4598 TypoDiagnosticGenerator TDG,
4599 TypoRecoveryCallback TRC) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00004600 assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
4601 auto TE = new (Context) TypoExpr(Context.DependentTy);
4602 auto &State = DelayedTypos[TE];
4603 State.Consumer = std::move(TCC);
4604 State.DiagHandler = std::move(TDG);
Kaelyn Takata8363f042014-10-27 18:07:42 +00004605 State.RecoveryHandler = std::move(TRC);
Kaelyn Takata6c759512014-10-27 18:07:37 +00004606 return TE;
4607}
4608
4609const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
4610 auto Entry = DelayedTypos.find(TE);
4611 assert(Entry != DelayedTypos.end() &&
4612 "Failed to get the state for a TypoExpr!");
4613 return Entry->second;
4614}
4615
4616void Sema::clearDelayedTypo(TypoExpr *TE) {
4617 DelayedTypos.erase(TE);
4618}