blob: e0d530a55e6d2667e229e108d56c1bf050948f01 [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"
Douglas Gregor36d1b142009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000017#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
Nick Lewyckyc3921482012-04-03 21:44:08 +000019#include "clang/AST/DeclLookups.h"
Douglas Gregor34074322009-01-14 22:20:51 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000022#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000023#include "clang/AST/ExprCXX.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Douglas Gregor34074322009-01-14 22:20:51 +000025#include "clang/Basic/LangOptions.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000026#include "clang/Lex/ModuleLoader.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "clang/Sema/DeclSpec.h"
28#include "clang/Sema/ExternalSemaSource.h"
29#include "clang/Sema/Overload.h"
30#include "clang/Sema/Scope.h"
31#include "clang/Sema/ScopeInfo.h"
32#include "clang/Sema/Sema.h"
33#include "clang/Sema/SemaInternal.h"
34#include "clang/Sema/TemplateDeduction.h"
35#include "clang/Sema/TypoCorrection.h"
Douglas Gregor34074322009-01-14 22:20:51 +000036#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "llvm/ADT/SetVector.h"
Douglas Gregore254f902009-02-04 00:32:51 +000038#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0afa7f62010-10-14 20:34:08 +000039#include "llvm/ADT/StringMap.h"
Chris Lattner83cfc7c2011-07-18 01:54:02 +000040#include "llvm/ADT/TinyPtrVector.h"
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +000041#include "llvm/ADT/edit_distance.h"
John McCall6538c932009-10-10 05:48:19 +000042#include "llvm/Support/ErrorHandling.h"
Nick Lewycky13668f22012-04-03 20:26:45 +000043#include <algorithm>
44#include <iterator>
Douglas Gregor0afa7f62010-10-14 20:34:08 +000045#include <limits>
Douglas Gregor2d435302009-12-30 17:04:44 +000046#include <list>
Douglas Gregorc2fa1692011-06-28 16:20:02 +000047#include <map>
Nick Lewycky13668f22012-04-03 20:26:45 +000048#include <set>
49#include <utility>
50#include <vector>
Douglas Gregor34074322009-01-14 22:20:51 +000051
52using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000053using namespace sema;
Douglas Gregor34074322009-01-14 22:20:51 +000054
John McCallf6c8a4e2009-11-10 07:01:13 +000055namespace {
56 class UnqualUsingEntry {
57 const DeclContext *Nominated;
58 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000059
John McCallf6c8a4e2009-11-10 07:01:13 +000060 public:
61 UnqualUsingEntry(const DeclContext *Nominated,
62 const DeclContext *CommonAncestor)
63 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
64 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000065
John McCallf6c8a4e2009-11-10 07:01:13 +000066 const DeclContext *getCommonAncestor() const {
67 return CommonAncestor;
68 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000069
John McCallf6c8a4e2009-11-10 07:01:13 +000070 const DeclContext *getNominatedNamespace() const {
71 return Nominated;
72 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000073
John McCallf6c8a4e2009-11-10 07:01:13 +000074 // Sort by the pointer value of the common ancestor.
75 struct Comparator {
76 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
77 return L.getCommonAncestor() < R.getCommonAncestor();
78 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000079
John McCallf6c8a4e2009-11-10 07:01:13 +000080 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
81 return E.getCommonAncestor() < DC;
82 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000083
John McCallf6c8a4e2009-11-10 07:01:13 +000084 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
85 return DC < E.getCommonAncestor();
86 }
87 };
88 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000089
John McCallf6c8a4e2009-11-10 07:01:13 +000090 /// A collection of using directives, as used by C++ unqualified
91 /// lookup.
92 class UnqualUsingDirectiveSet {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000093 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000094
John McCallf6c8a4e2009-11-10 07:01:13 +000095 ListTy list;
96 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000097
John McCallf6c8a4e2009-11-10 07:01:13 +000098 public:
99 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +0000100
John McCallf6c8a4e2009-11-10 07:01:13 +0000101 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000102 // C++ [namespace.udir]p1:
John McCallf6c8a4e2009-11-10 07:01:13 +0000103 // During unqualified name lookup, the names appear as if they
104 // were declared in the nearest enclosing namespace which contains
105 // both the using-directive and the nominated namespace.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000106 DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
John McCallf6c8a4e2009-11-10 07:01:13 +0000107 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +0000108
John McCallf6c8a4e2009-11-10 07:01:13 +0000109 for (; S; S = S->getParent()) {
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000110 // C++ [namespace.udir]p1:
111 // A using-directive shall not appear in class scope, but may
112 // appear in namespace scope or in block scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000113 DeclContext *Ctx = S->getEntity();
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000114 if (Ctx && Ctx->isFileContext()) {
115 visit(Ctx, Ctx);
116 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
Aaron Ballman5df6aa42014-03-17 17:03:37 +0000117 for (auto *I : S->using_directives())
118 visit(I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000119 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000120 }
121 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000122
123 // Visits a context and collect all of its using directives
124 // recursively. Treats all using directives as if they were
125 // declared in the context.
126 //
127 // A given context is only every visited once, so it is important
128 // that contexts be visited from the inside out in order to get
129 // the effective DCs right.
130 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
131 if (!visited.insert(DC))
132 return;
133
134 addUsingDirectives(DC, EffectiveDC);
135 }
136
137 // Visits a using directive and collects all of its using
138 // directives recursively. Treats all using directives as if they
139 // were declared in the effective DC.
140 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
141 DeclContext *NS = UD->getNominatedNamespace();
142 if (!visited.insert(NS))
143 return;
144
145 addUsingDirective(UD, EffectiveDC);
146 addUsingDirectives(NS, EffectiveDC);
147 }
148
149 // Adds all the using directives in a context (and those nominated
150 // by its using directives, transitively) as if they appeared in
151 // the given effective context.
152 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000153 SmallVector<DeclContext*,4> queue;
John McCallf6c8a4e2009-11-10 07:01:13 +0000154 while (true) {
Aaron Ballman804a7fb2014-03-17 17:14:12 +0000155 for (auto UD : DC->using_directives()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000156 DeclContext *NS = UD->getNominatedNamespace();
157 if (visited.insert(NS)) {
158 addUsingDirective(UD, EffectiveDC);
159 queue.push_back(NS);
160 }
161 }
162
163 if (queue.empty())
164 return;
165
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000166 DC = queue.pop_back_val();
John McCallf6c8a4e2009-11-10 07:01:13 +0000167 }
168 }
169
170 // Add a using directive as if it had been declared in the given
171 // context. This helps implement C++ [namespace.udir]p3:
172 // The using-directive is transitive: if a scope contains a
173 // using-directive that nominates a second namespace that itself
174 // contains using-directives, the effect is as if the
175 // using-directives from the second namespace also appeared in
176 // the first.
177 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
178 // Find the common ancestor between the effective context and
179 // the nominated namespace.
180 DeclContext *Common = UD->getNominatedNamespace();
181 while (!Common->Encloses(EffectiveDC))
182 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000183 Common = Common->getPrimaryContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000184
John McCallf6c8a4e2009-11-10 07:01:13 +0000185 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
186 }
187
188 void done() {
189 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
190 }
191
John McCallf6c8a4e2009-11-10 07:01:13 +0000192 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000193
John McCallf6c8a4e2009-11-10 07:01:13 +0000194 const_iterator begin() const { return list.begin(); }
195 const_iterator end() const { return list.end(); }
196
197 std::pair<const_iterator,const_iterator>
198 getNamespacesFor(DeclContext *DC) const {
John McCall9757d032009-11-10 09:20:04 +0000199 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCallf6c8a4e2009-11-10 07:01:13 +0000200 UnqualUsingEntry::Comparator());
201 }
202 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000203}
204
Douglas Gregor889ceb72009-02-03 19:21:40 +0000205// Retrieve the set of identifier namespaces that correspond to a
206// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000207static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
208 bool CPlusPlus,
209 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000210 unsigned IDNS = 0;
211 switch (NameKind) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +0000212 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000213 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000214 case Sema::LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +0000215 case Sema::LookupLocalFriendName:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000216 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000217 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000218 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000219 if (Redeclaration)
220 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCallea305ed2009-12-18 10:40:03 +0000221 }
Richard Smith541b38b2013-09-20 01:15:31 +0000222 if (Redeclaration)
223 IDNS |= Decl::IDNS_LocalExtern;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000224 break;
225
John McCallb9467b62010-04-24 01:30:58 +0000226 case Sema::LookupOperatorName:
227 // Operator lookup is its own crazy thing; it is not the same
228 // as (e.g.) looking up an operator name for redeclaration.
229 assert(!Redeclaration && "cannot do redeclaration operator lookup");
230 IDNS = Decl::IDNS_NonMemberOperator;
231 break;
232
Douglas Gregor889ceb72009-02-03 19:21:40 +0000233 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000234 if (CPlusPlus) {
235 IDNS = Decl::IDNS_Type;
236
237 // When looking for a redeclaration of a tag name, we add:
238 // 1) TagFriend to find undeclared friend decls
239 // 2) Namespace because they can't "overload" with tag decls.
240 // 3) Tag because it includes class templates, which can't
241 // "overload" with tag decls.
242 if (Redeclaration)
243 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
244 } else {
245 IDNS = Decl::IDNS_Tag;
246 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000247 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000248
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000249 case Sema::LookupLabel:
250 IDNS = Decl::IDNS_Label;
251 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000252
Douglas Gregor889ceb72009-02-03 19:21:40 +0000253 case Sema::LookupMemberName:
254 IDNS = Decl::IDNS_Member;
255 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000256 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000257 break;
258
259 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000260 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
261 break;
262
Douglas Gregor889ceb72009-02-03 19:21:40 +0000263 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000264 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000265 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000266
John McCall84d87672009-12-10 09:41:52 +0000267 case Sema::LookupUsingDeclName:
Richard Smith83e78f52014-04-11 01:03:38 +0000268 assert(Redeclaration && "should only be used for redecl lookup");
269 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |
270 Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend |
271 Decl::IDNS_LocalExtern;
John McCall84d87672009-12-10 09:41:52 +0000272 break;
273
Douglas Gregor79947a22009-04-24 00:11:27 +0000274 case Sema::LookupObjCProtocolName:
275 IDNS = Decl::IDNS_ObjCProtocol;
276 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000277
Douglas Gregor39982192010-08-15 06:18:01 +0000278 case Sema::LookupAnyName:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000279 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor39982192010-08-15 06:18:01 +0000280 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
281 | Decl::IDNS_Type;
282 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000283 }
284 return IDNS;
285}
286
John McCallea305ed2009-12-18 10:40:03 +0000287void LookupResult::configure() {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000288 IDNS = getIDNS(LookupKind, SemaRef.getLangOpts().CPlusPlus,
John McCallea305ed2009-12-18 10:40:03 +0000289 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000290
Richard Smithbdd14642014-02-04 01:14:30 +0000291 // If we're looking for one of the allocation or deallocation
292 // operators, make sure that the implicitly-declared new and delete
293 // operators can be found.
294 switch (NameInfo.getName().getCXXOverloadedOperator()) {
295 case OO_New:
296 case OO_Delete:
297 case OO_Array_New:
298 case OO_Array_Delete:
299 SemaRef.DeclareGlobalNewDelete();
300 break;
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000301
Richard Smithbdd14642014-02-04 01:14:30 +0000302 default:
303 break;
304 }
Douglas Gregor15197662013-04-03 23:06:26 +0000305
Richard Smithbdd14642014-02-04 01:14:30 +0000306 // Compiler builtins are always visible, regardless of where they end
307 // up being declared.
308 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
309 if (unsigned BuiltinID = Id->getBuiltinID()) {
310 if (!SemaRef.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
311 AllowHidden = true;
Douglas Gregor15197662013-04-03 23:06:26 +0000312 }
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000313 }
John McCallea305ed2009-12-18 10:40:03 +0000314}
315
Alp Tokerc1086762013-12-07 13:51:35 +0000316bool LookupResult::sanity() const {
Richard Smithf97ad222014-04-01 18:33:50 +0000317 // This function is never called by NDEBUG builds.
John McCall19c1bfd2010-08-25 05:32:35 +0000318 assert(ResultKind != NotFound || Decls.size() == 0);
319 assert(ResultKind != Found || Decls.size() == 1);
320 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
321 (Decls.size() == 1 &&
322 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
323 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
324 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000325 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
326 Ambiguity == AmbiguousBaseSubobjectTypes)));
Craig Topperc3ec1492014-05-26 06:22:03 +0000327 assert((Paths != nullptr) == (ResultKind == Ambiguous &&
328 (Ambiguity == AmbiguousBaseSubobjectTypes ||
329 Ambiguity == AmbiguousBaseSubobjects)));
Alp Tokerc1086762013-12-07 13:51:35 +0000330 return true;
John McCall19c1bfd2010-08-25 05:32:35 +0000331}
John McCall19c1bfd2010-08-25 05:32:35 +0000332
John McCall9f3059a2009-10-09 21:13:30 +0000333// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000334void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000335 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000336}
337
Richard Smith3876cc82013-10-30 01:02:04 +0000338/// Get a representative context for a declaration such that two declarations
339/// will have the same context if they were found within the same scope.
Benjamin Kramerfc58b042013-11-01 11:50:55 +0000340static DeclContext *getContextForScopeMatching(Decl *D) {
Richard Smith3876cc82013-10-30 01:02:04 +0000341 // For function-local declarations, use that function as the context. This
342 // doesn't account for scopes within the function; the caller must deal with
343 // those.
344 DeclContext *DC = D->getLexicalDeclContext();
345 if (DC->isFunctionOrMethod())
346 return DC;
347
348 // Otherwise, look at the semantic context of the declaration. The
349 // declaration must have been found there.
350 return D->getDeclContext()->getRedeclContext();
351}
352
John McCall283b9012009-11-22 00:44:51 +0000353/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000354void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000355 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000356
John McCall9f3059a2009-10-09 21:13:30 +0000357 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000358 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000359 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000360 return;
361 }
362
John McCall283b9012009-11-22 00:44:51 +0000363 // If there's a single decl, we need to examine it to decide what
364 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000365 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000366 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
367 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000368 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000369 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000370 ResultKind = FoundUnresolvedValue;
371 return;
372 }
John McCall9f3059a2009-10-09 21:13:30 +0000373
John McCall6538c932009-10-10 05:48:19 +0000374 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000375 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000376
John McCall9f3059a2009-10-09 21:13:30 +0000377 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor13e65872010-08-11 14:45:53 +0000378 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000379
John McCall9f3059a2009-10-09 21:13:30 +0000380 bool Ambiguous = false;
381 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000382 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000383
384 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000385
John McCall9f3059a2009-10-09 21:13:30 +0000386 unsigned I = 0;
387 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000388 NamedDecl *D = Decls[I]->getUnderlyingDecl();
389 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000390
Argyrios Kyrtzidis1fcd7fd2013-02-22 06:58:37 +0000391 // Ignore an invalid declaration unless it's the only one left.
392 if (D->isInvalidDecl() && I < N-1) {
393 Decls[I] = Decls[--N];
394 continue;
395 }
396
Douglas Gregor13e65872010-08-11 14:45:53 +0000397 // Redeclarations of types via typedef can occur both within a scope
398 // and, through using declarations and directives, across scopes. There is
399 // no ambiguity if they all refer to the same type, so unique based on the
400 // canonical type.
401 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
402 if (!TD->getDeclContext()->isRecord()) {
403 QualType T = SemaRef.Context.getTypeDeclType(TD);
404 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
405 // The type is not unique; pull something off the back and continue
406 // at this index.
407 Decls[I] = Decls[--N];
408 continue;
409 }
410 }
411 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000412
John McCallf0f1cf02009-11-17 07:50:12 +0000413 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000414 // If it's not unique, pull something off the back (and
415 // continue at this index).
416 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000417 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000418 }
419
Douglas Gregor13e65872010-08-11 14:45:53 +0000420 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000421
Douglas Gregor13e65872010-08-11 14:45:53 +0000422 if (isa<UnresolvedUsingValueDecl>(D)) {
423 HasUnresolved = true;
424 } else if (isa<TagDecl>(D)) {
425 if (HasTag)
426 Ambiguous = true;
427 UniqueTagIndex = I;
428 HasTag = true;
429 } else if (isa<FunctionTemplateDecl>(D)) {
430 HasFunction = true;
431 HasFunctionTemplate = true;
432 } else if (isa<FunctionDecl>(D)) {
433 HasFunction = true;
434 } else {
435 if (HasNonFunction)
436 Ambiguous = true;
437 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000438 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000439 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000440 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000441
John McCall9f3059a2009-10-09 21:13:30 +0000442 // C++ [basic.scope.hiding]p2:
443 // A class name or enumeration name can be hidden by the name of
444 // an object, function, or enumerator declared in the same
445 // scope. If a class or enumeration name and an object, function,
446 // or enumerator are declared in the same scope (in any order)
447 // with the same name, the class or enumeration name is hidden
448 // wherever the object, function, or enumerator name is visible.
449 // But it's still an error if there are distinct tag types found,
450 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000451 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000452 (HasFunction || HasNonFunction || HasUnresolved)) {
Richard Smith3876cc82013-10-30 01:02:04 +0000453 if (getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
454 getContextForScopeMatching(Decls[UniqueTagIndex ? 0 : N - 1])))
Douglas Gregore63d0872010-10-23 16:06:17 +0000455 Decls[UniqueTagIndex] = Decls[--N];
456 else
457 Ambiguous = true;
458 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000459
John McCall9f3059a2009-10-09 21:13:30 +0000460 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000461
John McCall80053822009-12-03 00:58:24 +0000462 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000463 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000464
John McCall9f3059a2009-10-09 21:13:30 +0000465 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000466 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000467 else if (HasUnresolved)
468 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000469 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000470 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000471 else
John McCall27b18f82009-11-17 02:14:36 +0000472 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000473}
474
John McCall5cebab12009-11-18 07:57:50 +0000475void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000476 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000477 for (I = P.begin(), E = P.end(); I != E; ++I)
David Blaikieff7d47a2012-12-19 00:45:41 +0000478 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
479 DE = I->Decls.end(); DI != DE; ++DI)
John McCall9f3059a2009-10-09 21:13:30 +0000480 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000481}
482
John McCall5cebab12009-11-18 07:57:50 +0000483void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000484 Paths = new CXXBasePaths;
485 Paths->swap(P);
486 addDeclsFromBasePaths(*Paths);
487 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000488 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000489}
490
John McCall5cebab12009-11-18 07:57:50 +0000491void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000492 Paths = new CXXBasePaths;
493 Paths->swap(P);
494 addDeclsFromBasePaths(*Paths);
495 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000496 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000497}
498
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000499void LookupResult::print(raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000500 Out << Decls.size() << " result(s)";
501 if (isAmbiguous()) Out << ", ambiguous";
502 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000503
John McCall9f3059a2009-10-09 21:13:30 +0000504 for (iterator I = begin(), E = end(); I != E; ++I) {
505 Out << "\n";
506 (*I)->print(Out, 2);
507 }
508}
509
Douglas Gregord3a59182010-02-12 05:48:04 +0000510/// \brief Lookup a builtin function, when name lookup would otherwise
511/// fail.
512static bool LookupBuiltin(Sema &S, LookupResult &R) {
513 Sema::LookupNameKind NameKind = R.getLookupKind();
514
515 // If we didn't find a use of this identifier, and if the identifier
516 // corresponds to a compiler builtin, create the decl object for the builtin
517 // now, injecting it into translation unit scope, and return it.
518 if (NameKind == Sema::LookupOrdinaryName ||
519 NameKind == Sema::LookupRedeclarationWithLinkage) {
520 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
521 if (II) {
Nico Webere1687c52013-06-20 21:44:55 +0000522 if (S.getLangOpts().CPlusPlus11 && S.getLangOpts().GNUMode &&
523 II == S.getFloat128Identifier()) {
524 // libstdc++4.7's type_traits expects type __float128 to exist, so
525 // insert a dummy type to make that header build in gnu++11 mode.
526 R.addDecl(S.getASTContext().getFloat128StubType());
527 return true;
528 }
529
Douglas Gregord3a59182010-02-12 05:48:04 +0000530 // If this is a builtin on this (or all) targets, create the decl.
531 if (unsigned BuiltinID = II->getBuiltinID()) {
532 // In C++, we don't have any predefined library functions like
533 // 'malloc'. Instead, we'll just error.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000534 if (S.getLangOpts().CPlusPlus &&
Douglas Gregord3a59182010-02-12 05:48:04 +0000535 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
536 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000537
538 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
539 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000540 R.isForRedeclaration(),
541 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000542 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000543 return true;
544 }
Douglas Gregord3a59182010-02-12 05:48:04 +0000545 }
546 }
547 }
548
549 return false;
550}
551
Douglas Gregor7454c562010-07-02 20:37:36 +0000552/// \brief Determine whether we can declare a special member function within
553/// the class at this point.
Richard Smith7d125a12012-11-27 21:20:31 +0000554static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +0000555 // We need to have a definition for the class.
556 if (!Class->getDefinition() || Class->isDependentContext())
557 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000558
Douglas Gregor7454c562010-07-02 20:37:36 +0000559 // We can't be in the middle of defining the class.
Richard Smith7d125a12012-11-27 21:20:31 +0000560 return !Class->isBeingDefined();
Douglas Gregor7454c562010-07-02 20:37:36 +0000561}
562
563void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smith7d125a12012-11-27 21:20:31 +0000564 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregora6d69502010-07-02 23:41:54 +0000565 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000566
567 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000568 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000569 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000570
Douglas Gregora6d69502010-07-02 23:41:54 +0000571 // If the copy constructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000572 if (Class->needsImplicitCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +0000573 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000574
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000575 // If the copy assignment operator has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000576 if (Class->needsImplicitCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000577 DeclareImplicitCopyAssignment(Class);
578
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000579 if (getLangOpts().CPlusPlus11) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000580 // If the move constructor has not yet been declared, do so now.
581 if (Class->needsImplicitMoveConstructor())
582 DeclareImplicitMoveConstructor(Class); // might not actually do it
583
584 // If the move assignment operator has not yet been declared, do so now.
585 if (Class->needsImplicitMoveAssignment())
586 DeclareImplicitMoveAssignment(Class); // might not actually do it
587 }
588
Douglas Gregor7454c562010-07-02 20:37:36 +0000589 // If the destructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000590 if (Class->needsImplicitDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000591 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000592}
593
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000594/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000595/// special member function.
596static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
597 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000598 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000599 case DeclarationName::CXXDestructorName:
600 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000601
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000602 case DeclarationName::CXXOperatorName:
603 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000604
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000605 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000606 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000607 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000608
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000609 return false;
610}
611
612/// \brief If there are any implicit member functions with the given name
613/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000614static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000615 DeclarationName Name,
616 const DeclContext *DC) {
617 if (!DC)
618 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000619
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000620 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000621 case DeclarationName::CXXConstructorName:
622 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith7d125a12012-11-27 21:20:31 +0000623 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000624 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000625 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000626 S.DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +0000627 if (Record->needsImplicitCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000628 S.DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000629 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000630 Record->needsImplicitMoveConstructor())
631 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000632 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000633 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000634
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000635 case DeclarationName::CXXDestructorName:
636 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith2be35f52012-12-01 02:35:44 +0000637 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smith7d125a12012-11-27 21:20:31 +0000638 CanDeclareSpecialMemberFunction(Record))
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000639 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000640 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000641
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000642 case DeclarationName::CXXOperatorName:
643 if (Name.getCXXOverloadedOperator() != OO_Equal)
644 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000645
Sebastian Redl22653ba2011-08-30 19:58:05 +0000646 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smith7d125a12012-11-27 21:20:31 +0000647 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000648 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smith2be35f52012-12-01 02:35:44 +0000649 if (Record->needsImplicitCopyAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000650 S.DeclareImplicitCopyAssignment(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000651 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000652 Record->needsImplicitMoveAssignment())
653 S.DeclareImplicitMoveAssignment(Class);
654 }
655 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000656 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000657
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000658 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000659 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000660 }
661}
Douglas Gregor7454c562010-07-02 20:37:36 +0000662
John McCall9f3059a2009-10-09 21:13:30 +0000663// Adds all qualifying matches for a name within a decl context to the
664// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000665static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000666 bool Found = false;
667
Douglas Gregor7454c562010-07-02 20:37:36 +0000668 // Lazily declare C++ special member functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000669 if (S.getLangOpts().CPlusPlus)
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000670 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000671
Douglas Gregor7454c562010-07-02 20:37:36 +0000672 // Perform lookup into this declaration context.
David Blaikieff7d47a2012-12-19 00:45:41 +0000673 DeclContext::lookup_const_result DR = DC->lookup(R.getLookupName());
674 for (DeclContext::lookup_const_iterator I = DR.begin(), E = DR.end(); I != E;
675 ++I) {
John McCall401982f2010-01-20 21:53:11 +0000676 NamedDecl *D = *I;
Douglas Gregor4a814562011-12-14 16:03:29 +0000677 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000678 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000679 Found = true;
680 }
681 }
John McCall9f3059a2009-10-09 21:13:30 +0000682
Douglas Gregord3a59182010-02-12 05:48:04 +0000683 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
684 return true;
685
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000686 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000687 != DeclarationName::CXXConversionFunctionName ||
688 R.getLookupName().getCXXNameType()->isDependentType() ||
689 !isa<CXXRecordDecl>(DC))
690 return Found;
691
692 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000693 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000694 // name lookup. Instead, any conversion function templates visible in the
695 // context of the use are considered. [...]
696 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000697 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000698 return Found;
699
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +0000700 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
701 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruth3a693b72010-01-31 11:44:02 +0000702 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
703 if (!ConvTemplate)
704 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000705
Chandler Carruth3a693b72010-01-31 11:44:02 +0000706 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000707 // add the conversion function template. When we deduce template
708 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000709 // type of the new declaration with the type of the function template.
710 if (R.isForRedeclaration()) {
711 R.addDecl(ConvTemplate);
712 Found = true;
713 continue;
714 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000715
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000716 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000717 // [...] For each such operator, if argument deduction succeeds
718 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000719 // name lookup.
720 //
721 // When referencing a conversion function for any purpose other than
722 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000723 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000724 // specialization into the result set. We do this to avoid forcing all
725 // callers to perform special deduction for conversion functions.
Craig Toppere6706e42012-09-19 02:26:47 +0000726 TemplateDeductionInfo Info(R.getNameLoc());
Craig Topperc3ec1492014-05-26 06:22:03 +0000727 FunctionDecl *Specialization = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000728
729 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000730 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
731 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000732
Chandler Carruth3a693b72010-01-31 11:44:02 +0000733 // Compute the type of the function that we would expect the conversion
734 // function to have, if it were to match the name given.
735 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000736 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
Reid Kleckner78af0702013-08-27 23:08:25 +0000737 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
Richard Smith8acb4282014-07-31 21:57:55 +0000738 EPI.ExceptionSpec = EST_None;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000739 QualType ExpectedType
740 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000741 None, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000742
Chandler Carruth3a693b72010-01-31 11:44:02 +0000743 // Perform template argument deduction against the type that we would
744 // expect the function to have.
Craig Topperc3ec1492014-05-26 06:22:03 +0000745 if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
Chandler Carruth3a693b72010-01-31 11:44:02 +0000746 Specialization, Info)
747 == Sema::TDK_Success) {
748 R.addDecl(Specialization);
749 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000750 }
751 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000752
John McCall9f3059a2009-10-09 21:13:30 +0000753 return Found;
754}
755
John McCallf6c8a4e2009-11-10 07:01:13 +0000756// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000757static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000758CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000759 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000760
761 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
762
John McCallf6c8a4e2009-11-10 07:01:13 +0000763 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000764 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000765
John McCallf6c8a4e2009-11-10 07:01:13 +0000766 // Perform direct name lookup into the namespaces nominated by the
767 // using directives whose common ancestor is this namespace.
768 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000769 std::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000770
John McCallf6c8a4e2009-11-10 07:01:13 +0000771 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000772 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000773 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000774
775 R.resolveKind();
776
777 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000778}
779
780static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000781 if (DeclContext *Ctx = S->getEntity())
Douglas Gregor700792c2009-02-05 19:25:20 +0000782 return Ctx->isFileContext();
783 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000784}
Douglas Gregored8f2882009-01-30 01:04:22 +0000785
Douglas Gregor66230062010-03-15 14:33:29 +0000786// Find the next outer declaration context from this scope. This
787// routine actually returns the semantic outer context, which may
788// differ from the lexical context (encoded directly in the Scope
789// stack) when we are parsing a member of a class template. In this
790// case, the second element of the pair will be true, to indicate that
791// name lookup should continue searching in this semantic context when
792// it leaves the current template parameter scope.
793static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000794 DeclContext *DC = S->getEntity();
Craig Topperc3ec1492014-05-26 06:22:03 +0000795 DeclContext *Lexical = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000796 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000797 OuterS = OuterS->getParent()) {
798 if (OuterS->getEntity()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000799 Lexical = OuterS->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +0000800 break;
801 }
802 }
803
804 // C++ [temp.local]p8:
805 // In the definition of a member of a class template that appears
806 // outside of the namespace containing the class template
807 // definition, the name of a template-parameter hides the name of
808 // a member of this namespace.
809 //
810 // Example:
811 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000812 // namespace N {
813 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000814 //
815 // template<class T> class B {
816 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000817 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000818 // }
819 //
820 // template<class C> void N::B<C>::f(C) {
821 // C b; // C is the template parameter, not N::C
822 // }
823 //
824 // In this example, the lexical context we return is the
825 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000826 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000827 !S->getParent()->isTemplateParamScope())
828 return std::make_pair(Lexical, false);
829
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000830 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000831 // For the example, this is the scope for the template parameters of
832 // template<class C>.
833 Scope *OutermostTemplateScope = S->getParent();
834 while (OutermostTemplateScope->getParent() &&
835 OutermostTemplateScope->getParent()->isTemplateParamScope())
836 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000837
Douglas Gregor66230062010-03-15 14:33:29 +0000838 // Find the namespace context in which the original scope occurs. In
839 // the example, this is namespace N.
840 DeclContext *Semantic = DC;
841 while (!Semantic->isFileContext())
842 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000843
Douglas Gregor66230062010-03-15 14:33:29 +0000844 // Find the declaration context just outside of the template
845 // parameter scope. This is the context in which the template is
846 // being lexically declaration (a namespace context). In the
847 // example, this is the global scope.
848 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
849 Lexical->Encloses(Semantic))
850 return std::make_pair(Semantic, true);
851
852 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000853}
854
Richard Smith541b38b2013-09-20 01:15:31 +0000855namespace {
856/// An RAII object to specify that we want to find block scope extern
857/// declarations.
858struct FindLocalExternScope {
859 FindLocalExternScope(LookupResult &R)
860 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
861 Decl::IDNS_LocalExtern) {
862 R.setFindLocalExtern(R.getIdentifierNamespace() & Decl::IDNS_Ordinary);
863 }
864 void restore() {
865 R.setFindLocalExtern(OldFindLocalExtern);
866 }
867 ~FindLocalExternScope() {
868 restore();
869 }
870 LookupResult &R;
871 bool OldFindLocalExtern;
872};
873}
874
John McCall27b18f82009-11-17 02:14:36 +0000875bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000876 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000877
878 DeclarationName Name = R.getLookupName();
Richard Smith1c34fb72013-08-13 18:18:50 +0000879 Sema::LookupNameKind NameKind = R.getLookupKind();
John McCall27b18f82009-11-17 02:14:36 +0000880
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000881 // If this is the name of an implicitly-declared special member function,
882 // go through the scope stack to implicitly declare
883 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
884 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +0000885 if (DeclContext *DC = PreS->getEntity())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000886 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
887 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000888
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000889 // Implicitly declare member functions with the name we're looking for, if in
890 // fact we are in a scope where it matters.
891
Douglas Gregor889ceb72009-02-03 19:21:40 +0000892 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000893 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000894 I = IdResolver.begin(Name),
895 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000896
Douglas Gregor889ceb72009-02-03 19:21:40 +0000897 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000898 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000899 // ...During unqualified name lookup (3.4.1), the names appear as if
900 // they were declared in the nearest enclosing namespace which contains
901 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000902 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000903 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000904 //
905 // For example:
906 // namespace A { int i; }
907 // void foo() {
908 // int i;
909 // {
910 // using namespace A;
911 // ++i; // finds local 'i', A::i appears at global scope
912 // }
913 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000914 //
Douglas Gregorcc9406c2013-04-08 23:11:25 +0000915 UnqualUsingDirectiveSet UDirs;
916 bool VisitedUsingDirectives = false;
Richard Smith1c34fb72013-08-13 18:18:50 +0000917 bool LeftStartingScope = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000918 DeclContext *OutsideOfTemplateParamDC = nullptr;
Richard Smith541b38b2013-09-20 01:15:31 +0000919
920 // When performing a scope lookup, we want to find local extern decls.
921 FindLocalExternScope FindLocals(R);
922
Douglas Gregor700792c2009-02-05 19:25:20 +0000923 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000924 DeclContext *Ctx = S->getEntity();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000925
Douglas Gregor889ceb72009-02-03 19:21:40 +0000926 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000927 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000928 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000929 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Richard Smith1c34fb72013-08-13 18:18:50 +0000930 if (NameKind == LookupRedeclarationWithLinkage) {
931 // Determine whether this (or a previous) declaration is
932 // out-of-scope.
933 if (!LeftStartingScope && !Initial->isDeclScope(*I))
934 LeftStartingScope = true;
935
936 // If we found something outside of our starting scope that
Richard Smith9a00bbf2013-10-16 21:12:00 +0000937 // does not have linkage, skip it. If it's a template parameter,
938 // we still find it, so we can diagnose the invalid redeclaration.
939 if (LeftStartingScope && !((*I)->hasLinkage()) &&
940 !(*I)->isTemplateParameter()) {
Richard Smith1c34fb72013-08-13 18:18:50 +0000941 R.setShadowed();
942 continue;
943 }
944 }
945
John McCall9f3059a2009-10-09 21:13:30 +0000946 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +0000947 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000948 }
949 }
John McCall9f3059a2009-10-09 21:13:30 +0000950 if (Found) {
951 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000952 if (S->isClassScope())
953 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
954 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000955 return true;
956 }
957
Richard Smith1c34fb72013-08-13 18:18:50 +0000958 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
Richard Smith114394f2013-08-09 04:35:01 +0000959 // C++11 [class.friend]p11:
960 // If a friend declaration appears in a local class and the name
961 // specified is an unqualified name, a prior declaration is
962 // looked up without considering scopes that are outside the
963 // innermost enclosing non-class scope.
964 return false;
965 }
966
Douglas Gregor66230062010-03-15 14:33:29 +0000967 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
968 S->getParent() && !S->getParent()->isTemplateParamScope()) {
969 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000970 // found nothing, so look into the contexts between the
Douglas Gregor66230062010-03-15 14:33:29 +0000971 // lexical and semantic declaration contexts returned by
972 // findOuterContext(). This implements the name lookup behavior
973 // of C++ [temp.local]p8.
974 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +0000975 OutsideOfTemplateParamDC = nullptr;
Douglas Gregor66230062010-03-15 14:33:29 +0000976 }
977
978 if (Ctx) {
979 DeclContext *OuterCtx;
980 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000981 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregor66230062010-03-15 14:33:29 +0000982 if (SearchAfterTemplateScope)
983 OutsideOfTemplateParamDC = OuterCtx;
984
Douglas Gregorea166062010-03-15 15:26:48 +0000985 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000986 // We do not directly look into transparent contexts, since
987 // those entities will be found in the nearest enclosing
988 // non-transparent context.
989 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000990 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000991
992 // We do not look directly into function or method contexts,
993 // since all of the local variables and parameters of the
994 // function/method are present within the Scope.
995 if (Ctx->isFunctionOrMethod()) {
996 // If we have an Objective-C instance method, look for ivars
997 // in the corresponding interface.
998 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
999 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1000 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1001 ObjCInterfaceDecl *ClassDeclared;
1002 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001003 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +00001004 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001005 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1006 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +00001007 R.resolveKind();
1008 return true;
1009 }
1010 }
1011 }
1012 }
1013
1014 continue;
1015 }
1016
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001017 // If this is a file context, we need to perform unqualified name
1018 // lookup considering using directives.
1019 if (Ctx->isFileContext()) {
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001020 // If we haven't handled using directives yet, do so now.
1021 if (!VisitedUsingDirectives) {
1022 // Add using directives from this context up to the top level.
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001023 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1024 if (UCtx->isTransparentContext())
1025 continue;
1026
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001027 UDirs.visit(UCtx, UCtx);
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001028 }
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001029
1030 // Find the innermost file scope, so we can add using directives
1031 // from local scopes.
1032 Scope *InnermostFileScope = S;
1033 while (InnermostFileScope &&
1034 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1035 InnermostFileScope = InnermostFileScope->getParent();
1036 UDirs.visitScopeChain(Initial, InnermostFileScope);
1037
1038 UDirs.done();
1039
1040 VisitedUsingDirectives = true;
1041 }
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001042
1043 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1044 R.resolveKind();
1045 return true;
1046 }
1047
1048 continue;
1049 }
1050
Douglas Gregor7f737c02009-09-10 16:57:35 +00001051 // Perform qualified name lookup into this context.
1052 // FIXME: In some cases, we know that every name that could be found by
1053 // this qualified name lookup will also be on the identifier chain. For
1054 // example, inside a class without any base classes, we never need to
1055 // perform qualified lookup because all of the members are on top of the
1056 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001057 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +00001058 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +00001059 }
Douglas Gregor700792c2009-02-05 19:25:20 +00001060 }
Douglas Gregored8f2882009-01-30 01:04:22 +00001061 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001062
John McCallf6c8a4e2009-11-10 07:01:13 +00001063 // Stop if we ran out of scopes.
1064 // FIXME: This really, really shouldn't be happening.
1065 if (!S) return false;
1066
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001067 // If we are looking for members, no need to look into global/namespace scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00001068 if (NameKind == LookupMemberName)
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001069 return false;
1070
Douglas Gregor700792c2009-02-05 19:25:20 +00001071 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +00001072 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +00001073 //
Mike Stump87c57ac2009-05-16 07:39:55 +00001074 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1075 // don't build it for each lookup!
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001076 if (!VisitedUsingDirectives) {
1077 UDirs.visitScopeChain(Initial, S);
1078 UDirs.done();
1079 }
Richard Smith541b38b2013-09-20 01:15:31 +00001080
1081 // If we're not performing redeclaration lookup, do not look for local
1082 // extern declarations outside of a function scope.
1083 if (!R.isForRedeclaration())
1084 FindLocals.restore();
1085
Douglas Gregor700792c2009-02-05 19:25:20 +00001086 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +00001087 // Unqualified name lookup in C++ requires looking into scopes
1088 // that aren't strictly lexical, and therefore we walk through the
1089 // context as well as walking through the scopes.
1090 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001091 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +00001092 bool Found = false;
John McCall48871652010-08-21 09:40:31 +00001093 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001094 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001095 // We found something. Look for anything else in our scope
1096 // with this same name and in an acceptable identifier
1097 // namespace, so that we can construct an overload set if we
1098 // need to.
John McCall9f3059a2009-10-09 21:13:30 +00001099 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +00001100 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001101 }
1102 }
1103
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001104 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +00001105 R.resolveKind();
1106 return true;
1107 }
1108
Ted Kremenekc37877d2013-10-08 17:08:03 +00001109 DeclContext *Ctx = S->getEntity();
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001110 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1111 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1112 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001113 // found nothing, so look into the contexts between the
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001114 // lexical and semantic declaration contexts returned by
1115 // findOuterContext(). This implements the name lookup behavior
1116 // of C++ [temp.local]p8.
1117 Ctx = OutsideOfTemplateParamDC;
Craig Topperc3ec1492014-05-26 06:22:03 +00001118 OutsideOfTemplateParamDC = nullptr;
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001119 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001120
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001121 if (Ctx) {
1122 DeclContext *OuterCtx;
1123 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001124 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001125 if (SearchAfterTemplateScope)
1126 OutsideOfTemplateParamDC = OuterCtx;
1127
1128 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1129 // We do not directly look into transparent contexts, since
1130 // those entities will be found in the nearest enclosing
1131 // non-transparent context.
1132 if (Ctx->isTransparentContext())
1133 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001134
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001135 // If we have a context, and it's not a context stashed in the
1136 // template parameter scope for an out-of-line definition, also
1137 // look into that context.
1138 if (!(Found && S && S->isTemplateParamScope())) {
1139 assert(Ctx->isFileContext() &&
1140 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001141
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001142 // Look into context considering using-directives.
1143 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1144 Found = true;
1145 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001146
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001147 if (Found) {
1148 R.resolveKind();
1149 return true;
1150 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001151
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001152 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1153 return false;
1154 }
1155 }
1156
Douglas Gregor3ce74932010-02-05 07:07:10 +00001157 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001158 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001159 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001160
John McCall9f3059a2009-10-09 21:13:30 +00001161 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001162}
1163
Richard Smith0e5d7b82013-07-25 23:08:39 +00001164/// \brief Find the declaration that a class temploid member specialization was
1165/// instantiated from, or the member itself if it is an explicit specialization.
1166static Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) {
1167 return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom();
1168}
1169
1170/// \brief Find the module in which the given declaration was defined.
1171static Module *getDefiningModule(Decl *Entity) {
1172 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1173 // If this function was instantiated from a template, the defining module is
1174 // the module containing the pattern.
1175 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1176 Entity = Pattern;
1177 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
Reid Klecknere7367d62014-10-14 20:28:40 +00001178 if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
1179 Entity = Pattern;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001180 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1181 if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo())
1182 Entity = getInstantiatedFrom(ED, MSInfo);
1183 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1184 // FIXME: Map from variable template specializations back to the template.
1185 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo())
1186 Entity = getInstantiatedFrom(VD, MSInfo);
1187 }
1188
1189 // Walk up to the containing context. That might also have been instantiated
1190 // from a template.
1191 DeclContext *Context = Entity->getDeclContext();
1192 if (Context->isFileContext())
1193 return Entity->getOwningModule();
1194 return getDefiningModule(cast<Decl>(Context));
1195}
1196
1197llvm::DenseSet<Module*> &Sema::getLookupModules() {
1198 unsigned N = ActiveTemplateInstantiations.size();
1199 for (unsigned I = ActiveTemplateInstantiationLookupModules.size();
1200 I != N; ++I) {
1201 Module *M = getDefiningModule(ActiveTemplateInstantiations[I].Entity);
1202 if (M && !LookupModulesCache.insert(M).second)
Craig Topperc3ec1492014-05-26 06:22:03 +00001203 M = nullptr;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001204 ActiveTemplateInstantiationLookupModules.push_back(M);
1205 }
1206 return LookupModulesCache;
1207}
1208
1209/// \brief Determine whether a declaration is visible to name lookup.
1210///
1211/// This routine determines whether the declaration D is visible in the current
1212/// lookup context, taking into account the current template instantiation
1213/// stack. During template instantiation, a declaration is visible if it is
1214/// visible from a module containing any entity on the template instantiation
1215/// path (by instantiating a template, you allow it to see the declarations that
1216/// your module can see, including those later on in your module).
1217bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
1218 assert(D->isHidden() && !SemaRef.ActiveTemplateInstantiations.empty() &&
1219 "should not call this: not in slow case");
1220 Module *DeclModule = D->getOwningModule();
1221 assert(DeclModule && "hidden decl not from a module");
1222
1223 // Find the extra places where we need to look.
1224 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
1225 if (LookupModules.empty())
1226 return false;
1227
1228 // If our lookup set contains the decl's module, it's visible.
1229 if (LookupModules.count(DeclModule))
1230 return true;
1231
1232 // If the declaration isn't exported, it's not visible in any other module.
1233 if (D->isModulePrivate())
1234 return false;
1235
1236 // Check whether DeclModule is transitively exported to an import of
1237 // the lookup set.
1238 for (llvm::DenseSet<Module *>::iterator I = LookupModules.begin(),
1239 E = LookupModules.end();
1240 I != E; ++I)
1241 if ((*I)->isModuleVisible(DeclModule))
1242 return true;
1243 return false;
1244}
1245
Douglas Gregor4a814562011-12-14 16:03:29 +00001246/// \brief Retrieve the visible declaration corresponding to D, if any.
1247///
1248/// This routine determines whether the declaration D is visible in the current
1249/// module, with the current imports. If not, it checks whether any
1250/// redeclaration of D is visible, and if so, returns that declaration.
Richard Smith0e5d7b82013-07-25 23:08:39 +00001251///
Douglas Gregor4a814562011-12-14 16:03:29 +00001252/// \returns D, or a visible previous declaration of D, whichever is more recent
1253/// and visible. If no declaration of D is visible, returns null.
Richard Smithe156254d2013-08-20 20:35:18 +00001254static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
1255 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
Richard Smith0e5d7b82013-07-25 23:08:39 +00001256
Aaron Ballman86c93902014-03-06 23:45:36 +00001257 for (auto RD : D->redecls()) {
1258 if (auto ND = dyn_cast<NamedDecl>(RD)) {
Richard Smithe156254d2013-08-20 20:35:18 +00001259 if (LookupResult::isVisible(SemaRef, ND))
Douglas Gregor54079202012-01-06 22:05:37 +00001260 return ND;
1261 }
Douglas Gregor4a814562011-12-14 16:03:29 +00001262 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001263
Craig Topperc3ec1492014-05-26 06:22:03 +00001264 return nullptr;
Douglas Gregor4a814562011-12-14 16:03:29 +00001265}
1266
Richard Smithe156254d2013-08-20 20:35:18 +00001267NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
1268 return findAcceptableDecl(SemaRef, D);
1269}
1270
Douglas Gregor34074322009-01-14 22:20:51 +00001271/// @brief Perform unqualified name lookup starting from a given
1272/// scope.
1273///
1274/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1275/// used to find names within the current scope. For example, 'x' in
1276/// @code
1277/// int x;
1278/// int f() {
1279/// return x; // unqualified name look finds 'x' in the global scope
1280/// }
1281/// @endcode
1282///
1283/// Different lookup criteria can find different names. For example, a
1284/// particular scope can have both a struct and a function of the same
1285/// name, and each can be found by certain lookup criteria. For more
1286/// information about lookup criteria, see the documentation for the
1287/// class LookupCriteria.
1288///
1289/// @param S The scope from which unqualified name lookup will
1290/// begin. If the lookup criteria permits, name lookup may also search
1291/// in the parent scopes.
1292///
James Dennett91738ff2012-06-22 10:32:46 +00001293/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1294/// look up and the lookup kind), and is updated with the results of lookup
1295/// including zero or more declarations and possibly additional information
1296/// used to diagnose ambiguities.
Douglas Gregor34074322009-01-14 22:20:51 +00001297///
James Dennett91738ff2012-06-22 10:32:46 +00001298/// @returns \c true if lookup succeeded and false otherwise.
John McCall27b18f82009-11-17 02:14:36 +00001299bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1300 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001301 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001302
John McCall27b18f82009-11-17 02:14:36 +00001303 LookupNameKind NameKind = R.getLookupKind();
1304
David Blaikiebbafb8a2012-03-11 07:00:24 +00001305 if (!getLangOpts().CPlusPlus) {
Douglas Gregor34074322009-01-14 22:20:51 +00001306 // Unqualified name lookup in C/Objective-C is purely lexical, so
1307 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001308 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001309 // Find the nearest non-transparent declaration scope.
1310 while (!(S->getFlags() & Scope::DeclScope) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001311 (S->getEntity() && S->getEntity()->isTransparentContext()))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001312 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001313 }
1314
Richard Smith541b38b2013-09-20 01:15:31 +00001315 // When performing a scope lookup, we want to find local extern decls.
1316 FindLocalExternScope FindLocals(R);
1317
Douglas Gregor34074322009-01-14 22:20:51 +00001318 // Scan up the scope chain looking for a decl that matches this
1319 // identifier that is in the appropriate namespace. This search
1320 // should not take long, as shadowing of names is uncommon, and
1321 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001322 bool LeftStartingScope = false;
1323
Douglas Gregored8f2882009-01-30 01:04:22 +00001324 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001325 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001326 I != IEnd; ++I)
Richard Smith0e5d7b82013-07-25 23:08:39 +00001327 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001328 if (NameKind == LookupRedeclarationWithLinkage) {
1329 // Determine whether this (or a previous) declaration is
1330 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001331 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001332 LeftStartingScope = true;
1333
1334 // If we found something outside of our starting scope that
1335 // does not have linkage, skip it.
Richard Smith1c34fb72013-08-13 18:18:50 +00001336 if (LeftStartingScope && !((*I)->hasLinkage())) {
1337 R.setShadowed();
Douglas Gregoreddf4332009-02-24 20:03:32 +00001338 continue;
Richard Smith1c34fb72013-08-13 18:18:50 +00001339 }
Douglas Gregoreddf4332009-02-24 20:03:32 +00001340 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001341 else if (NameKind == LookupObjCImplicitSelfParam &&
1342 !isa<ImplicitParamDecl>(*I))
1343 continue;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001344
Douglas Gregor4a814562011-12-14 16:03:29 +00001345 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001346
Douglas Gregorb59643b2012-01-03 23:26:26 +00001347 // Check whether there are any other declarations with the same name
1348 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001349 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001350 // Find the scope in which this declaration was declared (if it
1351 // actually exists in a Scope).
1352 while (S && !S->isDeclScope(D))
1353 S = S->getParent();
1354
1355 // If the scope containing the declaration is the translation unit,
1356 // then we'll need to perform our checks based on the matching
1357 // DeclContexts rather than matching scopes.
1358 if (S && isNamespaceOrTranslationUnitScope(S))
Craig Topperc3ec1492014-05-26 06:22:03 +00001359 S = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001360
1361 // Compute the DeclContext, if we need it.
Craig Topperc3ec1492014-05-26 06:22:03 +00001362 DeclContext *DC = nullptr;
Douglas Gregor81bd0382012-01-13 23:06:53 +00001363 if (!S)
1364 DC = (*I)->getDeclContext()->getRedeclContext();
1365
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001366 IdentifierResolver::iterator LastI = I;
1367 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001368 if (S) {
1369 // Match based on scope.
1370 if (!S->isDeclScope(*LastI))
1371 break;
1372 } else {
1373 // Match based on DeclContext.
1374 DeclContext *LastDC
1375 = (*LastI)->getDeclContext()->getRedeclContext();
1376 if (!LastDC->Equals(DC))
1377 break;
1378 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001379
1380 // If the declaration is in the right namespace and visible, add it.
1381 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1382 R.addDecl(LastD);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001383 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001384
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001385 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001386 }
Richard Smith541b38b2013-09-20 01:15:31 +00001387
John McCall9f3059a2009-10-09 21:13:30 +00001388 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001389 }
Douglas Gregor34074322009-01-14 22:20:51 +00001390 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001391 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001392 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001393 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001394 }
1395
1396 // If we didn't find a use of this identifier, and if the identifier
1397 // corresponds to a compiler builtin, create the decl object for the builtin
1398 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001399 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1400 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001401
Axel Naumann016538a2011-02-24 16:47:47 +00001402 // If we didn't find a use of this identifier, the ExternalSource
1403 // may be able to handle the situation.
1404 // Note: some lookup failures are expected!
1405 // See e.g. R.isForRedeclaration().
1406 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001407}
1408
John McCall6538c932009-10-10 05:48:19 +00001409/// @brief Perform qualified name lookup in the namespaces nominated by
1410/// using directives by the given context.
1411///
1412/// C++98 [namespace.qual]p2:
James Dennett51a8d8b2012-06-19 21:05:49 +00001413/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6538c932009-10-10 05:48:19 +00001414/// (where X is the global namespace), let S be the set of all
1415/// declarations of m in X and in the transitive closure of all
1416/// namespaces nominated by using-directives in X and its used
1417/// namespaces, except that using-directives are ignored in any
1418/// namespace, including X, directly containing one or more
1419/// declarations of m. No namespace is searched more than once in
1420/// the lookup of a name. If S is the empty set, the program is
1421/// ill-formed. Otherwise, if S has exactly one member, or if the
1422/// context of the reference is a using-declaration
1423/// (namespace.udecl), S is the required set of declarations of
1424/// m. Otherwise if the use of m is not one that allows a unique
1425/// declaration to be chosen from S, the program is ill-formed.
James Dennett51a8d8b2012-06-19 21:05:49 +00001426///
John McCall6538c932009-10-10 05:48:19 +00001427/// C++98 [namespace.qual]p5:
1428/// During the lookup of a qualified namespace member name, if the
1429/// lookup finds more than one declaration of the member, and if one
1430/// declaration introduces a class name or enumeration name and the
1431/// other declarations either introduce the same object, the same
1432/// enumerator or a set of functions, the non-type name hides the
1433/// class or enumeration name if and only if the declarations are
1434/// from the same namespace; otherwise (the declarations are from
1435/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001436static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001437 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001438 assert(StartDC->isFileContext() && "start context is not a file context");
1439
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001440 DeclContext::udir_range UsingDirectives = StartDC->using_directives();
1441 if (UsingDirectives.begin() == UsingDirectives.end()) return false;
John McCall6538c932009-10-10 05:48:19 +00001442
1443 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001444 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001445 Visited.insert(StartDC);
1446
1447 // We have not yet looked into these namespaces, much less added
1448 // their "using-children" to the queue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001449 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001450
1451 // We have already looked into the initial namespace; seed the queue
1452 // with its using-children.
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001453 for (auto *I : UsingDirectives) {
1454 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001455 if (Visited.insert(ND))
John McCall6538c932009-10-10 05:48:19 +00001456 Queue.push_back(ND);
1457 }
1458
1459 // The easiest way to implement the restriction in [namespace.qual]p5
1460 // is to check whether any of the individual results found a tag
1461 // and, if so, to declare an ambiguity if the final result is not
1462 // a tag.
1463 bool FoundTag = false;
1464 bool FoundNonTag = false;
1465
John McCall5cebab12009-11-18 07:57:50 +00001466 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001467
1468 bool Found = false;
1469 while (!Queue.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001470 NamespaceDecl *ND = Queue.pop_back_val();
John McCall6538c932009-10-10 05:48:19 +00001471
1472 // We go through some convolutions here to avoid copying results
1473 // between LookupResults.
1474 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001475 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001476 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001477
1478 if (FoundDirect) {
1479 // First do any local hiding.
1480 DirectR.resolveKind();
1481
1482 // If the local result is a tag, remember that.
1483 if (DirectR.isSingleTagDecl())
1484 FoundTag = true;
1485 else
1486 FoundNonTag = true;
1487
1488 // Append the local results to the total results if necessary.
1489 if (UseLocal) {
1490 R.addAllDecls(LocalR);
1491 LocalR.clear();
1492 }
1493 }
1494
1495 // If we find names in this namespace, ignore its using directives.
1496 if (FoundDirect) {
1497 Found = true;
1498 continue;
1499 }
1500
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001501 for (auto I : ND->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00001502 NamespaceDecl *Nom = I->getNominatedNamespace();
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001503 if (Visited.insert(Nom))
John McCall6538c932009-10-10 05:48:19 +00001504 Queue.push_back(Nom);
1505 }
1506 }
1507
1508 if (Found) {
1509 if (FoundTag && FoundNonTag)
1510 R.setAmbiguousQualifiedTagHiding();
1511 else
1512 R.resolveKind();
1513 }
1514
1515 return Found;
1516}
1517
Douglas Gregor39982192010-08-15 06:18:01 +00001518/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001519static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor39982192010-08-15 06:18:01 +00001520 CXXBasePath &Path,
1521 void *Name) {
1522 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001523
Douglas Gregor39982192010-08-15 06:18:01 +00001524 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1525 Path.Decls = BaseRecord->lookup(N);
David Blaikieff7d47a2012-12-19 00:45:41 +00001526 return !Path.Decls.empty();
Douglas Gregor39982192010-08-15 06:18:01 +00001527}
1528
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001529/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001530/// static members, nested types, and enumerators.
1531template<typename InputIterator>
1532static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1533 Decl *D = (*First)->getUnderlyingDecl();
1534 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1535 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001536
Douglas Gregorc0d24902010-10-22 22:08:47 +00001537 if (isa<CXXMethodDecl>(D)) {
1538 // Determine whether all of the methods are static.
1539 bool AllMethodsAreStatic = true;
1540 for(; First != Last; ++First) {
1541 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001542
Douglas Gregorc0d24902010-10-22 22:08:47 +00001543 if (!isa<CXXMethodDecl>(D)) {
1544 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1545 break;
1546 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001547
Douglas Gregorc0d24902010-10-22 22:08:47 +00001548 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1549 AllMethodsAreStatic = false;
1550 break;
1551 }
1552 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001553
Douglas Gregorc0d24902010-10-22 22:08:47 +00001554 if (AllMethodsAreStatic)
1555 return true;
1556 }
1557
1558 return false;
1559}
1560
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001561/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001562///
1563/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1564/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001565/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001566///
1567/// Different lookup criteria can find different names. For example, a
1568/// particular scope can have both a struct and a function of the same
1569/// name, and each can be found by certain lookup criteria. For more
1570/// information about lookup criteria, see the documentation for the
1571/// class LookupCriteria.
1572///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001573/// \param R captures both the lookup criteria and any lookup results found.
1574///
1575/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001576/// search. If the lookup criteria permits, name lookup may also search
1577/// in the parent contexts or (for C++ classes) base classes.
1578///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001579/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001580/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001581///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001582/// \returns true if lookup succeeded, false if it failed.
1583bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1584 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001585 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001586
John McCall27b18f82009-11-17 02:14:36 +00001587 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001588 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001589
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001590 // Make sure that the declaration context is complete.
1591 assert((!isa<TagDecl>(LookupCtx) ||
1592 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00001593 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith7d137e32012-03-23 03:33:32 +00001594 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001595 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001596
Douglas Gregor34074322009-01-14 22:20:51 +00001597 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001598 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001599 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001600 if (isa<CXXRecordDecl>(LookupCtx))
1601 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001602 return true;
1603 }
Douglas Gregor34074322009-01-14 22:20:51 +00001604
John McCall6538c932009-10-10 05:48:19 +00001605 // Don't descend into implied contexts for redeclarations.
1606 // C++98 [namespace.qual]p6:
1607 // In a declaration for a namespace member in which the
1608 // declarator-id is a qualified-id, given that the qualified-id
1609 // for the namespace member has the form
1610 // nested-name-specifier unqualified-id
1611 // the unqualified-id shall name a member of the namespace
1612 // designated by the nested-name-specifier.
1613 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001614 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001615 return false;
1616
John McCall27b18f82009-11-17 02:14:36 +00001617 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001618 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001619 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001620
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001621 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001622 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001623 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001624 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001625 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001626
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001627 // If we're performing qualified name lookup into a dependent class,
1628 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001629 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001630 // template instantiation time (at which point all bases will be available)
1631 // or we have to fail.
1632 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1633 LookupRec->hasAnyDependentBases()) {
1634 R.setNotFoundInCurrentInstantiation();
1635 return false;
1636 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001637
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001638 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001639 CXXBasePaths Paths;
1640 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001641
1642 // Look for this member in our base classes
Craig Topperc3ec1492014-05-26 06:22:03 +00001643 CXXRecordDecl::BaseMatchesCallback *BaseCallback = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00001644 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001645 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001646 case LookupOrdinaryName:
1647 case LookupMemberName:
1648 case LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +00001649 case LookupLocalFriendName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001650 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1651 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001652
Douglas Gregor36d1b142009-10-06 17:59:45 +00001653 case LookupTagName:
1654 BaseCallback = &CXXRecordDecl::FindTagMember;
1655 break;
John McCall84d87672009-12-10 09:41:52 +00001656
Douglas Gregor39982192010-08-15 06:18:01 +00001657 case LookupAnyName:
1658 BaseCallback = &LookupAnyMember;
1659 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001660
John McCall84d87672009-12-10 09:41:52 +00001661 case LookupUsingDeclName:
1662 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001663
Douglas Gregor36d1b142009-10-06 17:59:45 +00001664 case LookupOperatorName:
1665 case LookupNamespaceName:
1666 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001667 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001668 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001669 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001670
Douglas Gregor36d1b142009-10-06 17:59:45 +00001671 case LookupNestedNameSpecifierName:
1672 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1673 break;
1674 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001675
John McCall27b18f82009-11-17 02:14:36 +00001676 if (!LookupRec->lookupInBases(BaseCallback,
1677 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001678 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001679
John McCall553c0792010-01-23 00:46:32 +00001680 R.setNamingClass(LookupRec);
1681
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001682 // C++ [class.member.lookup]p2:
1683 // [...] If the resulting set of declarations are not all from
1684 // sub-objects of the same type, or the set has a nonstatic member
1685 // and includes members from distinct sub-objects, there is an
1686 // ambiguity and the program is ill-formed. Otherwise that set is
1687 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001688 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001689 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001690 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001691
Douglas Gregor36d1b142009-10-06 17:59:45 +00001692 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001693 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001694 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001695
John McCall401982f2010-01-20 21:53:11 +00001696 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1697 // across all paths.
1698 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001699
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001700 // Determine whether we're looking at a distinct sub-object or not.
1701 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001702 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001703 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1704 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001705 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001706 }
1707
Douglas Gregorc0d24902010-10-22 22:08:47 +00001708 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001709 != Context.getCanonicalType(PathElement.Base->getType())) {
1710 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001711 // different types. If the declaration sets aren't the same, this
Nikola Smiljanic1c125682014-07-09 05:42:35 +00001712 // lookup is ambiguous.
David Blaikieff7d47a2012-12-19 00:45:41 +00001713 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00001714 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikieff7d47a2012-12-19 00:45:41 +00001715 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
1716 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001717
David Blaikieff7d47a2012-12-19 00:45:41 +00001718 while (FirstD != FirstPath->Decls.end() &&
1719 CurrentD != Path->Decls.end()) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00001720 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1721 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1722 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001723
Douglas Gregorc0d24902010-10-22 22:08:47 +00001724 ++FirstD;
1725 ++CurrentD;
1726 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001727
David Blaikieff7d47a2012-12-19 00:45:41 +00001728 if (FirstD == FirstPath->Decls.end() &&
1729 CurrentD == Path->Decls.end())
Douglas Gregorc0d24902010-10-22 22:08:47 +00001730 continue;
1731 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001732
John McCall9f3059a2009-10-09 21:13:30 +00001733 R.setAmbiguousBaseSubobjectTypes(Paths);
1734 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001735 }
1736
Douglas Gregorc0d24902010-10-22 22:08:47 +00001737 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001738 // We have a different subobject of the same type.
1739
1740 // C++ [class.member.lookup]p5:
1741 // A static member, a nested type or an enumerator defined in
1742 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001743 // has more than one base class subobject of type T.
David Blaikieff7d47a2012-12-19 00:45:41 +00001744 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001745 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001746
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001747 // We have found a nonstatic member name in multiple, distinct
1748 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001749 R.setAmbiguousBaseSubobjects(Paths);
1750 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001751 }
1752 }
1753
1754 // Lookup in a base class succeeded; return these results.
1755
Aaron Ballman1e606f42014-07-15 22:03:49 +00001756 for (auto *D : Paths.front().Decls) {
John McCall553c0792010-01-23 00:46:32 +00001757 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1758 D->getAccess());
1759 R.addDecl(D, AS);
1760 }
John McCall9f3059a2009-10-09 21:13:30 +00001761 R.resolveKind();
1762 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001763}
1764
1765/// @brief Performs name lookup for a name that was parsed in the
1766/// source code, and may contain a C++ scope specifier.
1767///
1768/// This routine is a convenience routine meant to be called from
1769/// contexts that receive a name and an optional C++ scope specifier
1770/// (e.g., "N::M::x"). It will then perform either qualified or
1771/// unqualified name lookup (with LookupQualifiedName or LookupName,
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00001772/// respectively) on the given name and return those results. It will
1773/// perform a special type of lookup for "__super::" scope specifier.
Douglas Gregor34074322009-01-14 22:20:51 +00001774///
1775/// @param S The scope from which unqualified name lookup will
1776/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001777///
Douglas Gregore861bac2009-08-25 22:51:20 +00001778/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001779///
Douglas Gregore861bac2009-08-25 22:51:20 +00001780/// @param EnteringContext Indicates whether we are going to enter the
1781/// context of the scope-specifier SS (if present).
1782///
John McCall9f3059a2009-10-09 21:13:30 +00001783/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001784bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001785 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001786 if (SS && SS->isInvalid()) {
1787 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001788 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001789 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001790 }
Mike Stump11289f42009-09-09 15:08:12 +00001791
Douglas Gregore861bac2009-08-25 22:51:20 +00001792 if (SS && SS->isSet()) {
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00001793 NestedNameSpecifier *NNS = SS->getScopeRep();
1794 if (NNS->getKind() == NestedNameSpecifier::Super)
1795 return LookupInSuper(R, NNS->getAsRecordDecl());
1796
Douglas Gregore861bac2009-08-25 22:51:20 +00001797 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001798 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001799 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001800 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001801 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001802
John McCall27b18f82009-11-17 02:14:36 +00001803 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00001804 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001805 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001806
Douglas Gregore861bac2009-08-25 22:51:20 +00001807 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001808 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001809 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00001810 R.setNotFoundInCurrentInstantiation();
1811 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00001812 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001813 }
1814
Mike Stump11289f42009-09-09 15:08:12 +00001815 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001816 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001817}
1818
Nikola Smiljanic67860242014-09-26 00:28:20 +00001819/// \brief Perform qualified name lookup into all base classes of the given
1820/// class.
1821///
1822/// \param R captures both the lookup criteria and any lookup results found.
1823///
1824/// \param Class The context in which qualified name lookup will
1825/// search. Name lookup will search in all base classes merging the results.
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00001826///
1827/// @returns True if any decls were found (but possibly ambiguous)
1828bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
Nikola Smiljanic67860242014-09-26 00:28:20 +00001829 for (const auto &BaseSpec : Class->bases()) {
1830 CXXRecordDecl *RD = cast<CXXRecordDecl>(
1831 BaseSpec.getType()->castAs<RecordType>()->getDecl());
1832 LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
1833 Result.setBaseObjectType(Context.getRecordType(Class));
1834 LookupQualifiedName(Result, RD);
1835 for (auto *Decl : Result)
1836 R.addDecl(Decl);
1837 }
1838
1839 R.resolveKind();
Nikola Smiljanic905bfda2014-10-04 10:17:57 +00001840
1841 return !R.empty();
Nikola Smiljanic67860242014-09-26 00:28:20 +00001842}
Douglas Gregor889ceb72009-02-03 19:21:40 +00001843
James Dennett41725122012-06-22 10:16:05 +00001844/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001845/// from name lookup.
1846///
James Dennett41725122012-06-22 10:16:05 +00001847/// \param Result The result of the ambiguous lookup to be diagnosed.
Serge Pavlov99292092013-08-29 07:23:24 +00001848void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001849 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1850
John McCall27b18f82009-11-17 02:14:36 +00001851 DeclarationName Name = Result.getLookupName();
1852 SourceLocation NameLoc = Result.getNameLoc();
1853 SourceRange LookupRange = Result.getContextRange();
1854
John McCall6538c932009-10-10 05:48:19 +00001855 switch (Result.getAmbiguityKind()) {
1856 case LookupResult::AmbiguousBaseSubobjects: {
1857 CXXBasePaths *Paths = Result.getBasePaths();
1858 QualType SubobjectType = Paths->front().back().Base->getType();
1859 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1860 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1861 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001862
David Blaikieff7d47a2012-12-19 00:45:41 +00001863 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6538c932009-10-10 05:48:19 +00001864 while (isa<CXXMethodDecl>(*Found) &&
1865 cast<CXXMethodDecl>(*Found)->isStatic())
1866 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001867
John McCall6538c932009-10-10 05:48:19 +00001868 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
Serge Pavlov99292092013-08-29 07:23:24 +00001869 break;
John McCall6538c932009-10-10 05:48:19 +00001870 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001871
John McCall6538c932009-10-10 05:48:19 +00001872 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001873 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1874 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001875
John McCall6538c932009-10-10 05:48:19 +00001876 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001877 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001878 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1879 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001880 Path != PathEnd; ++Path) {
David Blaikieff7d47a2012-12-19 00:45:41 +00001881 Decl *D = Path->Decls.front();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001882 if (DeclsPrinted.insert(D).second)
1883 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1884 }
Serge Pavlov99292092013-08-29 07:23:24 +00001885 break;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001886 }
1887
John McCall6538c932009-10-10 05:48:19 +00001888 case LookupResult::AmbiguousTagHiding: {
1889 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001890
John McCall6538c932009-10-10 05:48:19 +00001891 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1892
Aaron Ballman1e606f42014-07-15 22:03:49 +00001893 for (auto *D : Result)
1894 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
John McCall6538c932009-10-10 05:48:19 +00001895 TagDecls.insert(TD);
1896 Diag(TD->getLocation(), diag::note_hidden_tag);
1897 }
1898
Aaron Ballman1e606f42014-07-15 22:03:49 +00001899 for (auto *D : Result)
1900 if (!isa<TagDecl>(D))
1901 Diag(D->getLocation(), diag::note_hiding_object);
John McCall6538c932009-10-10 05:48:19 +00001902
1903 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001904 LookupResult::Filter F = Result.makeFilter();
1905 while (F.hasNext()) {
1906 if (TagDecls.count(F.next()))
1907 F.erase();
1908 }
1909 F.done();
Serge Pavlov99292092013-08-29 07:23:24 +00001910 break;
John McCall6538c932009-10-10 05:48:19 +00001911 }
1912
1913 case LookupResult::AmbiguousReference: {
1914 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001915
Aaron Ballman1e606f42014-07-15 22:03:49 +00001916 for (auto *D : Result)
1917 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
Serge Pavlov99292092013-08-29 07:23:24 +00001918 break;
John McCall6538c932009-10-10 05:48:19 +00001919 }
Serge Pavlov99292092013-08-29 07:23:24 +00001920 }
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001921}
Douglas Gregore254f902009-02-04 00:32:51 +00001922
John McCallf24d7bb2010-05-28 18:45:08 +00001923namespace {
1924 struct AssociatedLookup {
John McCall7d8b0412012-08-24 20:38:34 +00001925 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallf24d7bb2010-05-28 18:45:08 +00001926 Sema::AssociatedNamespaceSet &Namespaces,
1927 Sema::AssociatedClassSet &Classes)
John McCall7d8b0412012-08-24 20:38:34 +00001928 : S(S), Namespaces(Namespaces), Classes(Classes),
1929 InstantiationLoc(InstantiationLoc) {
John McCallf24d7bb2010-05-28 18:45:08 +00001930 }
1931
1932 Sema &S;
1933 Sema::AssociatedNamespaceSet &Namespaces;
1934 Sema::AssociatedClassSet &Classes;
John McCall7d8b0412012-08-24 20:38:34 +00001935 SourceLocation InstantiationLoc;
John McCallf24d7bb2010-05-28 18:45:08 +00001936 };
1937}
1938
Mike Stump11289f42009-09-09 15:08:12 +00001939static void
John McCallf24d7bb2010-05-28 18:45:08 +00001940addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001941
Douglas Gregor8b895222010-04-30 07:08:38 +00001942static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1943 DeclContext *Ctx) {
1944 // Add the associated namespace for this class.
1945
1946 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1947 // be a locally scoped record.
1948
Sebastian Redlbd595762010-08-31 20:53:31 +00001949 // We skip out of inline namespaces. The innermost non-inline namespace
1950 // contains all names of all its nested inline namespaces anyway, so we can
1951 // replace the entire inline namespace tree with its root.
1952 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1953 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00001954 Ctx = Ctx->getParent();
1955
John McCallc7e8e792009-08-07 22:18:02 +00001956 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001957 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001958}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001959
Mike Stump11289f42009-09-09 15:08:12 +00001960// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001961// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001962static void
John McCallf24d7bb2010-05-28 18:45:08 +00001963addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1964 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001965 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001966 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001967 switch (Arg.getKind()) {
1968 case TemplateArgument::Null:
1969 break;
Mike Stump11289f42009-09-09 15:08:12 +00001970
Douglas Gregor197e5f72009-07-08 07:51:57 +00001971 case TemplateArgument::Type:
1972 // [...] the namespaces and classes associated with the types of the
1973 // template arguments provided for template type parameters (excluding
1974 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001975 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001976 break;
Mike Stump11289f42009-09-09 15:08:12 +00001977
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001978 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001979 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00001980 // [...] the namespaces in which any template template arguments are
1981 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001982 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001983 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00001984 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001985 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001986 DeclContext *Ctx = ClassTemplate->getDeclContext();
1987 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001988 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001989 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001990 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001991 }
1992 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001993 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001994
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001995 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001996 case TemplateArgument::Integral:
1997 case TemplateArgument::Expression:
Eli Friedmanb826a002012-09-26 02:36:12 +00001998 case TemplateArgument::NullPtr:
Mike Stump11289f42009-09-09 15:08:12 +00001999 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00002000 // associated namespaces. ]
2001 break;
Mike Stump11289f42009-09-09 15:08:12 +00002002
Douglas Gregor197e5f72009-07-08 07:51:57 +00002003 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00002004 for (const auto &P : Arg.pack_elements())
2005 addAssociatedClassesAndNamespaces(Result, P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002006 break;
2007 }
2008}
2009
Douglas Gregore254f902009-02-04 00:32:51 +00002010// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00002011// argument-dependent lookup with an argument of class type
2012// (C++ [basic.lookup.koenig]p2).
2013static void
John McCallf24d7bb2010-05-28 18:45:08 +00002014addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2015 CXXRecordDecl *Class) {
2016
2017 // Just silently ignore anything whose name is __va_list_tag.
2018 if (Class->getDeclName() == Result.S.VAListTagName)
2019 return;
2020
Douglas Gregore254f902009-02-04 00:32:51 +00002021 // C++ [basic.lookup.koenig]p2:
2022 // [...]
2023 // -- If T is a class type (including unions), its associated
2024 // classes are: the class itself; the class of which it is a
2025 // member, if any; and its direct and indirect base
2026 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00002027 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00002028
2029 // Add the class of which it is a member, if any.
2030 DeclContext *Ctx = Class->getDeclContext();
2031 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002032 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002033 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002034 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002035
Douglas Gregore254f902009-02-04 00:32:51 +00002036 // Add the class itself. If we've already seen this class, we don't
2037 // need to visit base classes.
Richard Smith594461f2014-03-14 22:07:27 +00002038 //
2039 // FIXME: That's not correct, we may have added this class only because it
2040 // was the enclosing class of another class, and in that case we won't have
2041 // added its base classes yet.
John McCallf24d7bb2010-05-28 18:45:08 +00002042 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00002043 return;
2044
Mike Stump11289f42009-09-09 15:08:12 +00002045 // -- If T is a template-id, its associated namespaces and classes are
2046 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002047 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00002048 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00002049 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00002050 // namespaces in which any template template arguments are defined; and
2051 // the classes in which any member templates used as template template
2052 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00002053 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00002054 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00002055 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2056 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2057 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002058 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002059 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002060 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002061
Douglas Gregor197e5f72009-07-08 07:51:57 +00002062 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2063 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00002064 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002065 }
Mike Stump11289f42009-09-09 15:08:12 +00002066
John McCall67da35c2010-02-04 22:26:26 +00002067 // Only recurse into base classes for complete types.
Richard Smith594461f2014-03-14 22:07:27 +00002068 if (!Class->hasDefinition())
2069 return;
John McCall67da35c2010-02-04 22:26:26 +00002070
Douglas Gregore254f902009-02-04 00:32:51 +00002071 // Add direct and indirect base classes along with their associated
2072 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002073 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00002074 Bases.push_back(Class);
2075 while (!Bases.empty()) {
2076 // Pop this class off the stack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002077 Class = Bases.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002078
2079 // Visit the base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +00002080 for (const auto &Base : Class->bases()) {
2081 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00002082 // In dependent contexts, we do ADL twice, and the first time around,
2083 // the base type might be a dependent TemplateSpecializationType, or a
2084 // TemplateTypeParmType. If that happens, simply ignore it.
2085 // FIXME: If we want to support export, we probably need to add the
2086 // namespace of the template in a TemplateSpecializationType, or even
2087 // the classes and namespaces of known non-dependent arguments.
2088 if (!BaseType)
2089 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002090 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002091 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00002092 // Find the associated namespace for this base class.
2093 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00002094 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00002095
2096 // Make sure we visit the bases of this base class.
2097 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2098 Bases.push_back(BaseDecl);
2099 }
2100 }
2101 }
2102}
2103
2104// \brief Add the associated classes and namespaces for
2105// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00002106// (C++ [basic.lookup.koenig]p2).
2107static void
John McCallf24d7bb2010-05-28 18:45:08 +00002108addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00002109 // C++ [basic.lookup.koenig]p2:
2110 //
2111 // For each argument type T in the function call, there is a set
2112 // of zero or more associated namespaces and a set of zero or more
2113 // associated classes to be considered. The sets of namespaces and
2114 // classes is determined entirely by the types of the function
2115 // arguments (and the namespace of any template template
2116 // argument). Typedef names and using-declarations used to specify
2117 // the types do not contribute to this set. The sets of namespaces
2118 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00002119
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002120 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00002121 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2122
Douglas Gregore254f902009-02-04 00:32:51 +00002123 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00002124 switch (T->getTypeClass()) {
2125
2126#define TYPE(Class, Base)
2127#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2128#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2129#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2130#define ABSTRACT_TYPE(Class, Base)
2131#include "clang/AST/TypeNodes.def"
2132 // T is canonical. We can also ignore dependent types because
2133 // we don't need to do ADL at the definition point, but if we
2134 // wanted to implement template export (or if we find some other
2135 // use for associated classes and namespaces...) this would be
2136 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00002137 break;
Douglas Gregore254f902009-02-04 00:32:51 +00002138
John McCall0af3d3b2010-05-28 06:08:54 +00002139 // -- If T is a pointer to U or an array of U, its associated
2140 // namespaces and classes are those associated with U.
2141 case Type::Pointer:
2142 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2143 continue;
2144 case Type::ConstantArray:
2145 case Type::IncompleteArray:
2146 case Type::VariableArray:
2147 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2148 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002149
John McCall0af3d3b2010-05-28 06:08:54 +00002150 // -- If T is a fundamental type, its associated sets of
2151 // namespaces and classes are both empty.
2152 case Type::Builtin:
2153 break;
2154
2155 // -- If T is a class type (including unions), its associated
2156 // classes are: the class itself; the class of which it is a
2157 // member, if any; and its direct and indirect base
2158 // classes. Its associated namespaces are the namespaces in
2159 // which its associated classes are defined.
2160 case Type::Record: {
Richard Smith594461f2014-03-14 22:07:27 +00002161 Result.S.RequireCompleteType(Result.InstantiationLoc, QualType(T, 0),
2162 /*no diagnostic*/ 0);
John McCall0af3d3b2010-05-28 06:08:54 +00002163 CXXRecordDecl *Class
2164 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002165 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00002166 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00002167 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00002168
John McCall0af3d3b2010-05-28 06:08:54 +00002169 // -- If T is an enumeration type, its associated namespace is
2170 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002171 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00002172 // it has no associated class.
2173 case Type::Enum: {
2174 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002175
John McCall0af3d3b2010-05-28 06:08:54 +00002176 DeclContext *Ctx = Enum->getDeclContext();
2177 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002178 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002179
John McCall0af3d3b2010-05-28 06:08:54 +00002180 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002181 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00002182
John McCall0af3d3b2010-05-28 06:08:54 +00002183 break;
2184 }
2185
2186 // -- If T is a function type, its associated namespaces and
2187 // classes are those associated with the function parameter
2188 // types and those associated with the return type.
2189 case Type::FunctionProto: {
2190 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002191 for (const auto &Arg : Proto->param_types())
2192 Queue.push_back(Arg.getTypePtr());
John McCall0af3d3b2010-05-28 06:08:54 +00002193 // fallthrough
2194 }
2195 case Type::FunctionNoProto: {
2196 const FunctionType *FnType = cast<FunctionType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00002197 T = FnType->getReturnType().getTypePtr();
John McCall0af3d3b2010-05-28 06:08:54 +00002198 continue;
2199 }
2200
2201 // -- If T is a pointer to a member function of a class X, its
2202 // associated namespaces and classes are those associated
2203 // with the function parameter types and return type,
2204 // together with those associated with X.
2205 //
2206 // -- If T is a pointer to a data member of class X, its
2207 // associated namespaces and classes are those associated
2208 // with the member type together with those associated with
2209 // X.
2210 case Type::MemberPointer: {
2211 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2212
2213 // Queue up the class type into which this points.
2214 Queue.push_back(MemberPtr->getClass());
2215
2216 // And directly continue with the pointee type.
2217 T = MemberPtr->getPointeeType().getTypePtr();
2218 continue;
2219 }
2220
2221 // As an extension, treat this like a normal pointer.
2222 case Type::BlockPointer:
2223 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2224 continue;
2225
2226 // References aren't covered by the standard, but that's such an
2227 // obvious defect that we cover them anyway.
2228 case Type::LValueReference:
2229 case Type::RValueReference:
2230 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2231 continue;
2232
2233 // These are fundamental types.
2234 case Type::Vector:
2235 case Type::ExtVector:
2236 case Type::Complex:
2237 break;
2238
Richard Smith27d807c2013-04-30 13:56:41 +00002239 // Non-deduced auto types only get here for error cases.
2240 case Type::Auto:
2241 break;
2242
Douglas Gregor8e936662011-04-12 01:02:45 +00002243 // If T is an Objective-C object or interface type, or a pointer to an
2244 // object or interface type, the associated namespace is the global
2245 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002246 case Type::ObjCObject:
2247 case Type::ObjCInterface:
2248 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002249 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002250 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002251
2252 // Atomic types are just wrappers; use the associations of the
2253 // contained type.
2254 case Type::Atomic:
2255 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2256 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002257 }
2258
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002259 if (Queue.empty())
2260 break;
2261 T = Queue.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002262 }
Douglas Gregore254f902009-02-04 00:32:51 +00002263}
2264
2265/// \brief Find the associated classes and namespaces for
2266/// argument-dependent lookup for a call with the given set of
2267/// arguments.
2268///
2269/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002270/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002271/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00002272void Sema::FindAssociatedClassesAndNamespaces(
2273 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2274 AssociatedNamespaceSet &AssociatedNamespaces,
2275 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002276 AssociatedNamespaces.clear();
2277 AssociatedClasses.clear();
2278
John McCall7d8b0412012-08-24 20:38:34 +00002279 AssociatedLookup Result(*this, InstantiationLoc,
2280 AssociatedNamespaces, AssociatedClasses);
John McCallf24d7bb2010-05-28 18:45:08 +00002281
Douglas Gregore254f902009-02-04 00:32:51 +00002282 // C++ [basic.lookup.koenig]p2:
2283 // For each argument type T in the function call, there is a set
2284 // of zero or more associated namespaces and a set of zero or more
2285 // associated classes to be considered. The sets of namespaces and
2286 // classes is determined entirely by the types of the function
2287 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002288 // argument).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002289 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregore254f902009-02-04 00:32:51 +00002290 Expr *Arg = Args[ArgIdx];
2291
2292 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002293 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002294 continue;
2295 }
2296
2297 // [...] In addition, if the argument is the name or address of a
2298 // set of overloaded functions and/or function templates, its
2299 // associated classes and namespaces are the union of those
2300 // associated with each of the members of the set: the namespace
2301 // in which the function or function template is defined and the
2302 // classes and namespaces associated with its (non-dependent)
2303 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002304 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002305 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002306 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002307 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002308
John McCallf24d7bb2010-05-28 18:45:08 +00002309 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2310 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002311
Aaron Ballman1e606f42014-07-15 22:03:49 +00002312 for (const auto *D : ULE->decls()) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002313 // Look through any using declarations to find the underlying function.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002314 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
Douglas Gregore254f902009-02-04 00:32:51 +00002315
2316 // Add the classes and namespaces associated with the parameter
2317 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002318 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002319 }
2320 }
2321}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002322
John McCall5cebab12009-11-18 07:57:50 +00002323NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002324 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002325 LookupNameKind NameKind,
2326 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002327 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002328 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002329 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002330}
2331
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002332/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002333ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002334 SourceLocation IdLoc,
2335 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002336 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002337 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002338 return cast_or_null<ObjCProtocolDecl>(D);
2339}
2340
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002341void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002342 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002343 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002344 // C++ [over.match.oper]p3:
2345 // -- The set of non-member candidates is the result of the
2346 // unqualified lookup of operator@ in the context of the
2347 // expression according to the usual rules for name lookup in
2348 // unqualified function calls (3.4.2) except that all member
Richard Smith100b24a2014-04-17 01:52:14 +00002349 // functions are ignored.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002350 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002351 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2352 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002353
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002354 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
Richard Smith100b24a2014-04-17 01:52:14 +00002355 Functions.append(Operators.begin(), Operators.end());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002356}
2357
Alexis Hunt1da39282011-06-24 02:11:39 +00002358Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002359 CXXSpecialMember SM,
2360 bool ConstArg,
2361 bool VolatileArg,
2362 bool RValueThis,
2363 bool ConstThis,
2364 bool VolatileThis) {
Richard Smith7d125a12012-11-27 21:20:31 +00002365 assert(CanDeclareSpecialMemberFunction(RD) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002366 "doing special member lookup into record that isn't fully complete");
Richard Smith7d125a12012-11-27 21:20:31 +00002367 RD = RD->getDefinition();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002368 if (RValueThis || ConstThis || VolatileThis)
2369 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2370 "constructors and destructors always have unqualified lvalue this");
2371 if (ConstArg || VolatileArg)
2372 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2373 "parameter-less special members can't have qualified arguments");
2374
2375 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002376 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002377 ID.AddInteger(SM);
2378 ID.AddInteger(ConstArg);
2379 ID.AddInteger(VolatileArg);
2380 ID.AddInteger(RValueThis);
2381 ID.AddInteger(ConstThis);
2382 ID.AddInteger(VolatileThis);
2383
2384 void *InsertPoint;
2385 SpecialMemberOverloadResult *Result =
2386 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2387
2388 // This was already cached
2389 if (Result)
2390 return Result;
2391
Alexis Huntba8e18d2011-06-07 00:11:58 +00002392 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2393 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002394 SpecialMemberCache.InsertNode(Result, InsertPoint);
2395
2396 if (SM == CXXDestructor) {
Richard Smith2be35f52012-12-01 02:35:44 +00002397 if (RD->needsImplicitDestructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002398 DeclareImplicitDestructor(RD);
2399 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002400 assert(DD && "record without a destructor");
2401 Result->setMethod(DD);
Richard Smith852265f2012-03-30 20:53:28 +00002402 Result->setKind(DD->isDeleted() ?
2403 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith83c478d2012-04-20 18:46:14 +00002404 SpecialMemberOverloadResult::Success);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002405 return Result;
2406 }
2407
Alexis Hunteef8ee02011-06-10 03:50:41 +00002408 // Prepare for overload resolution. Here we construct a synthetic argument
2409 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002410 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002411 DeclarationName Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002412 Expr *Arg = nullptr;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002413 unsigned NumArgs;
2414
Richard Smith83c478d2012-04-20 18:46:14 +00002415 QualType ArgType = CanTy;
2416 ExprValueKind VK = VK_LValue;
2417
Alexis Hunteef8ee02011-06-10 03:50:41 +00002418 if (SM == CXXDefaultConstructor) {
2419 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2420 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002421 if (RD->needsImplicitDefaultConstructor())
2422 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002423 } else {
2424 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2425 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smith2be35f52012-12-01 02:35:44 +00002426 if (RD->needsImplicitCopyConstructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002427 DeclareImplicitCopyConstructor(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002428 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002429 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002430 } else {
2431 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smith2be35f52012-12-01 02:35:44 +00002432 if (RD->needsImplicitCopyAssignment())
Alexis Hunt1da39282011-06-24 02:11:39 +00002433 DeclareImplicitCopyAssignment(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002434 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002435 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002436 }
2437
Alexis Hunteef8ee02011-06-10 03:50:41 +00002438 if (ConstArg)
2439 ArgType.addConst();
2440 if (VolatileArg)
2441 ArgType.addVolatile();
2442
2443 // This isn't /really/ specified by the standard, but it's implied
2444 // we should be working from an RValue in the case of move to ensure
2445 // that we prefer to bind to rvalue references, and an LValue in the
2446 // case of copy to ensure we don't bind to rvalue references.
2447 // Possibly an XValue is actually correct in the case of move, but
2448 // there is no semantic difference for class types in this restricted
2449 // case.
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002450 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002451 VK = VK_LValue;
2452 else
2453 VK = VK_RValue;
Richard Smith83c478d2012-04-20 18:46:14 +00002454 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00002455
Richard Smith83c478d2012-04-20 18:46:14 +00002456 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2457
2458 if (SM != CXXDefaultConstructor) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002459 NumArgs = 1;
Richard Smith83c478d2012-04-20 18:46:14 +00002460 Arg = &FakeArg;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002461 }
2462
2463 // Create the object argument
2464 QualType ThisTy = CanTy;
2465 if (ConstThis)
2466 ThisTy.addConst();
2467 if (VolatileThis)
2468 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002469 Expr::Classification Classification =
Richard Smith83c478d2012-04-20 18:46:14 +00002470 OpaqueValueExpr(SourceLocation(), ThisTy,
2471 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002472
2473 // Now we perform lookup on the name we computed earlier and do overload
2474 // resolution. Lookup is only performed directly into the class since there
2475 // will always be a (possibly implicit) declaration to shadow any others.
Richard Smith100b24a2014-04-17 01:52:14 +00002476 OverloadCandidateSet OCS(RD->getLocation(), OverloadCandidateSet::CSK_Normal);
David Blaikieff7d47a2012-12-19 00:45:41 +00002477 DeclContext::lookup_result R = RD->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00002478 assert(!R.empty() &&
Alexis Hunteef8ee02011-06-10 03:50:41 +00002479 "lookup for a constructor or assignment operator was empty");
Chandler Carruth7deaae72013-08-18 07:20:52 +00002480
2481 // Copy the candidates as our processing of them may load new declarations
2482 // from an external source and invalidate lookup_result.
2483 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2484
Aaron Ballman1e606f42014-07-15 22:03:49 +00002485 for (auto *Cand : Candidates) {
Alexis Hunt1da39282011-06-24 02:11:39 +00002486 if (Cand->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002487 continue;
2488
Alexis Hunt1da39282011-06-24 02:11:39 +00002489 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2490 // FIXME: [namespace.udecl]p15 says that we should only consider a
2491 // using declaration here if it does not match a declaration in the
2492 // derived class. We do not implement this correctly in other cases
2493 // either.
2494 Cand = U->getTargetDecl();
2495
2496 if (Cand->isInvalidDecl())
2497 continue;
2498 }
2499
2500 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002501 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Alexis Hunt1da39282011-06-24 02:11:39 +00002502 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002503 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2504 OCS, true);
Alexis Hunt080709f2011-06-23 00:26:20 +00002505 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002506 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2507 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt2949f022011-06-22 02:58:46 +00002508 } else if (FunctionTemplateDecl *Tmpl =
Alexis Hunt1da39282011-06-24 02:11:39 +00002509 dyn_cast<FunctionTemplateDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002510 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2511 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Craig Topperc3ec1492014-05-26 06:22:03 +00002512 RD, nullptr, ThisTy, Classification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002513 llvm::makeArrayRef(&Arg, NumArgs),
Alexis Hunt080709f2011-06-23 00:26:20 +00002514 OCS, true);
2515 else
2516 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Craig Topperc3ec1492014-05-26 06:22:03 +00002517 nullptr, llvm::makeArrayRef(&Arg, NumArgs),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002518 OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002519 } else {
2520 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002521 }
2522 }
2523
2524 OverloadCandidateSet::iterator Best;
2525 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2526 case OR_Success:
2527 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith83c478d2012-04-20 18:46:14 +00002528 Result->setKind(SpecialMemberOverloadResult::Success);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002529 break;
2530
2531 case OR_Deleted:
2532 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith852265f2012-03-30 20:53:28 +00002533 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002534 break;
2535
2536 case OR_Ambiguous:
Craig Topperc3ec1492014-05-26 06:22:03 +00002537 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00002538 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2539 break;
2540
Alexis Hunteef8ee02011-06-10 03:50:41 +00002541 case OR_No_Viable_Function:
Craig Topperc3ec1492014-05-26 06:22:03 +00002542 Result->setMethod(nullptr);
Richard Smith852265f2012-03-30 20:53:28 +00002543 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002544 break;
2545 }
2546
2547 return Result;
2548}
2549
2550/// \brief Look up the default constructor for the given class.
2551CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002552 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002553 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2554 false, false);
2555
2556 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002557}
2558
Alexis Hunt491ec602011-06-21 23:42:56 +00002559/// \brief Look up the copying constructor for the given class.
2560CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith83c478d2012-04-20 18:46:14 +00002561 unsigned Quals) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002562 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2563 "non-const, non-volatile qualifiers for copy ctor arg");
2564 SpecialMemberOverloadResult *Result =
2565 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2566 Quals & Qualifiers::Volatile, false, false, false);
2567
Alexis Hunt899bd442011-06-10 04:44:37 +00002568 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2569}
2570
Sebastian Redl22653ba2011-08-30 19:58:05 +00002571/// \brief Look up the moving constructor for the given class.
Richard Smith1c6461e2012-07-18 03:36:00 +00002572CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2573 unsigned Quals) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002574 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002575 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2576 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002577
2578 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2579}
2580
Douglas Gregor52b72822010-07-02 23:12:18 +00002581/// \brief Look up the constructors for the given class.
2582DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002583 // If the implicit constructors have not yet been declared, do so now.
Richard Smith7d125a12012-11-27 21:20:31 +00002584 if (CanDeclareSpecialMemberFunction(Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00002585 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002586 DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +00002587 if (Class->needsImplicitCopyConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002588 DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002589 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002590 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00002591 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002592
Douglas Gregor52b72822010-07-02 23:12:18 +00002593 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2594 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2595 return Class->lookup(Name);
2596}
2597
Alexis Hunt491ec602011-06-21 23:42:56 +00002598/// \brief Look up the copying assignment operator for the given class.
2599CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2600 unsigned Quals, bool RValueThis,
Richard Smith83c478d2012-04-20 18:46:14 +00002601 unsigned ThisQuals) {
Alexis Hunt491ec602011-06-21 23:42:56 +00002602 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2603 "non-const, non-volatile qualifiers for copy assignment arg");
2604 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2605 "non-const, non-volatile qualifiers for copy assignment this");
2606 SpecialMemberOverloadResult *Result =
2607 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2608 Quals & Qualifiers::Volatile, RValueThis,
2609 ThisQuals & Qualifiers::Const,
2610 ThisQuals & Qualifiers::Volatile);
2611
Alexis Hunt491ec602011-06-21 23:42:56 +00002612 return Result->getMethod();
2613}
2614
Sebastian Redl22653ba2011-08-30 19:58:05 +00002615/// \brief Look up the moving assignment operator for the given class.
2616CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith1c6461e2012-07-18 03:36:00 +00002617 unsigned Quals,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002618 bool RValueThis,
2619 unsigned ThisQuals) {
2620 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2621 "non-const, non-volatile qualifiers for copy assignment this");
2622 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002623 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2624 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002625 ThisQuals & Qualifiers::Const,
2626 ThisQuals & Qualifiers::Volatile);
2627
2628 return Result->getMethod();
2629}
2630
Douglas Gregore71edda2010-07-01 22:47:18 +00002631/// \brief Look for the destructor of the given class.
2632///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00002633/// During semantic analysis, this routine should be used in lieu of
2634/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00002635///
2636/// \returns The destructor for this class.
2637CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002638 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2639 false, false, false,
2640 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00002641}
2642
Richard Smithbcc22fc2012-03-09 08:00:36 +00002643/// LookupLiteralOperator - Determine which literal operator should be used for
2644/// a user-defined literal, per C++11 [lex.ext].
2645///
2646/// Normal overload resolution is not used to select which literal operator to
2647/// call for a user-defined literal. Look up the provided literal operator name,
2648/// and filter the results to the appropriate set for the given argument types.
2649Sema::LiteralOperatorLookupResult
2650Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2651 ArrayRef<QualType> ArgTys,
Richard Smithb8b41d32013-10-07 19:57:58 +00002652 bool AllowRaw, bool AllowTemplate,
2653 bool AllowStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002654 LookupName(R, S);
2655 assert(R.getResultKind() != LookupResult::Ambiguous &&
2656 "literal operator lookup can't be ambiguous");
2657
2658 // Filter the lookup results appropriately.
2659 LookupResult::Filter F = R.makeFilter();
2660
Richard Smithbcc22fc2012-03-09 08:00:36 +00002661 bool FoundRaw = false;
Richard Smithb8b41d32013-10-07 19:57:58 +00002662 bool FoundTemplate = false;
2663 bool FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002664 bool FoundExactMatch = false;
2665
2666 while (F.hasNext()) {
2667 Decl *D = F.next();
2668 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2669 D = USD->getTargetDecl();
2670
Douglas Gregorc1970572013-04-10 05:18:00 +00002671 // If the declaration we found is invalid, skip it.
2672 if (D->isInvalidDecl()) {
2673 F.erase();
2674 continue;
2675 }
2676
Richard Smithb8b41d32013-10-07 19:57:58 +00002677 bool IsRaw = false;
2678 bool IsTemplate = false;
2679 bool IsStringTemplate = false;
2680 bool IsExactMatch = false;
2681
Richard Smithbcc22fc2012-03-09 08:00:36 +00002682 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2683 if (FD->getNumParams() == 1 &&
2684 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2685 IsRaw = true;
Richard Smith550de452013-01-15 07:12:59 +00002686 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002687 IsExactMatch = true;
2688 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2689 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2690 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2691 IsExactMatch = false;
2692 break;
2693 }
2694 }
2695 }
2696 }
Richard Smithb8b41d32013-10-07 19:57:58 +00002697 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
2698 TemplateParameterList *Params = FD->getTemplateParameters();
2699 if (Params->size() == 1)
2700 IsTemplate = true;
2701 else
2702 IsStringTemplate = true;
2703 }
Richard Smithbcc22fc2012-03-09 08:00:36 +00002704
2705 if (IsExactMatch) {
2706 FoundExactMatch = true;
Richard Smithb8b41d32013-10-07 19:57:58 +00002707 AllowRaw = false;
2708 AllowTemplate = false;
2709 AllowStringTemplate = false;
2710 if (FoundRaw || FoundTemplate || FoundStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002711 // Go through again and remove the raw and template decls we've
2712 // already found.
2713 F.restart();
Richard Smithb8b41d32013-10-07 19:57:58 +00002714 FoundRaw = FoundTemplate = FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002715 }
Richard Smithb8b41d32013-10-07 19:57:58 +00002716 } else if (AllowRaw && IsRaw) {
2717 FoundRaw = true;
2718 } else if (AllowTemplate && IsTemplate) {
2719 FoundTemplate = true;
2720 } else if (AllowStringTemplate && IsStringTemplate) {
2721 FoundStringTemplate = true;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002722 } else {
2723 F.erase();
2724 }
2725 }
2726
2727 F.done();
2728
2729 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2730 // parameter type, that is used in preference to a raw literal operator
2731 // or literal operator template.
2732 if (FoundExactMatch)
2733 return LOLR_Cooked;
2734
2735 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2736 // operator template, but not both.
2737 if (FoundRaw && FoundTemplate) {
2738 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
Alp Tokera2794f92014-01-22 07:29:52 +00002739 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2740 NoteOverloadCandidate((*I)->getUnderlyingDecl()->getAsFunction());
Richard Smithbcc22fc2012-03-09 08:00:36 +00002741 return LOLR_Error;
2742 }
2743
2744 if (FoundRaw)
2745 return LOLR_Raw;
2746
2747 if (FoundTemplate)
2748 return LOLR_Template;
2749
Richard Smithb8b41d32013-10-07 19:57:58 +00002750 if (FoundStringTemplate)
2751 return LOLR_StringTemplate;
2752
Richard Smithbcc22fc2012-03-09 08:00:36 +00002753 // Didn't find anything we could use.
2754 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2755 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
Richard Smithb8b41d32013-10-07 19:57:58 +00002756 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
2757 << (AllowTemplate || AllowStringTemplate);
Richard Smithbcc22fc2012-03-09 08:00:36 +00002758 return LOLR_Error;
2759}
2760
John McCall8fe68082010-01-26 07:16:45 +00002761void ADLResult::insert(NamedDecl *New) {
2762 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2763
2764 // If we haven't yet seen a decl for this key, or the last decl
2765 // was exactly this one, we're done.
Craig Topperc3ec1492014-05-26 06:22:03 +00002766 if (Old == nullptr || Old == New) {
John McCall8fe68082010-01-26 07:16:45 +00002767 Old = New;
2768 return;
2769 }
2770
2771 // Otherwise, decide which is a more recent redeclaration.
Alp Tokera2794f92014-01-22 07:29:52 +00002772 FunctionDecl *OldFD = Old->getAsFunction();
2773 FunctionDecl *NewFD = New->getAsFunction();
John McCall8fe68082010-01-26 07:16:45 +00002774
2775 FunctionDecl *Cursor = NewFD;
2776 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002777 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00002778
2779 // If we got to the end without finding OldFD, OldFD is the newer
2780 // declaration; leave things as they are.
2781 if (!Cursor) return;
2782
2783 // If we do find OldFD, then NewFD is newer.
2784 if (Cursor == OldFD) break;
2785
2786 // Otherwise, keep looking.
2787 }
2788
2789 Old = New;
2790}
2791
Richard Smith100b24a2014-04-17 01:52:14 +00002792void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
2793 ArrayRef<Expr *> Args, ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002794 // Find all of the associated namespaces and classes based on the
2795 // arguments we have.
2796 AssociatedNamespaceSet AssociatedNamespaces;
2797 AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00002798 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCallc7e8e792009-08-07 22:18:02 +00002799 AssociatedNamespaces,
2800 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002801
2802 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002803 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2804 // and let Y be the lookup set produced by argument dependent
2805 // lookup (defined as follows). If X contains [...] then Y is
2806 // empty. Otherwise Y is the set of declarations found in the
2807 // namespaces associated with the argument types as described
2808 // below. The set of declarations found by the lookup of the name
2809 // is the union of X and Y.
2810 //
2811 // Here, we compute Y and add its members to the overloaded
2812 // candidate set.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002813 for (auto *NS : AssociatedNamespaces) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002814 // When considering an associated namespace, the lookup is the
2815 // same as the lookup performed when the associated namespace is
2816 // used as a qualifier (3.4.3.2) except that:
2817 //
2818 // -- Any using-directives in the associated namespace are
2819 // ignored.
2820 //
John McCallc7e8e792009-08-07 22:18:02 +00002821 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002822 // associated classes are visible within their respective
2823 // namespaces even if they are not visible during an ordinary
2824 // lookup (11.4).
Aaron Ballman1e606f42014-07-15 22:03:49 +00002825 DeclContext::lookup_result R = NS->lookup(Name);
2826 for (auto *D : R) {
John McCallaa74a0c2009-08-28 07:59:38 +00002827 // If the only declaration here is an ordinary friend, consider
2828 // it only if it was declared in an associated classes.
Richard Smith541b38b2013-09-20 01:15:31 +00002829 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) {
2830 // If it's neither ordinarily visible nor a friend, we can't find it.
2831 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0)
2832 continue;
2833
Richard Smith64017682013-07-17 23:53:16 +00002834 bool DeclaredInAssociatedClass = false;
2835 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
2836 DeclContext *LexDC = DI->getLexicalDeclContext();
2837 if (isa<CXXRecordDecl>(LexDC) &&
2838 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) {
2839 DeclaredInAssociatedClass = true;
2840 break;
2841 }
2842 }
2843 if (!DeclaredInAssociatedClass)
John McCalld1e9d832009-08-11 06:59:38 +00002844 continue;
2845 }
Mike Stump11289f42009-09-09 15:08:12 +00002846
John McCall91f61fc2010-01-26 06:04:06 +00002847 if (isa<UsingShadowDecl>(D))
2848 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002849
Richard Smith100b24a2014-04-17 01:52:14 +00002850 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D))
John McCall8fe68082010-01-26 07:16:45 +00002851 continue;
2852
2853 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002854 }
2855 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002856}
Douglas Gregor2d435302009-12-30 17:04:44 +00002857
2858//----------------------------------------------------------------------------
2859// Search for all visible declarations.
2860//----------------------------------------------------------------------------
2861VisibleDeclConsumer::~VisibleDeclConsumer() { }
2862
Richard Smithe156254d2013-08-20 20:35:18 +00002863bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
2864
Douglas Gregor2d435302009-12-30 17:04:44 +00002865namespace {
2866
2867class ShadowContextRAII;
2868
2869class VisibleDeclsRecord {
2870public:
2871 /// \brief An entry in the shadow map, which is optimized to store a
2872 /// single declaration (the common case) but can also store a list
2873 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002874 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00002875
2876private:
2877 /// \brief A mapping from declaration names to the declarations that have
2878 /// this name within a particular scope.
2879 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2880
2881 /// \brief A list of shadow maps, which is used to model name hiding.
2882 std::list<ShadowMap> ShadowMaps;
2883
2884 /// \brief The declaration contexts we have already visited.
2885 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2886
2887 friend class ShadowContextRAII;
2888
2889public:
2890 /// \brief Determine whether we have already visited this context
2891 /// (and, if not, note that we are going to visit that context now).
2892 bool visitedContext(DeclContext *Ctx) {
2893 return !VisitedContexts.insert(Ctx);
2894 }
2895
Douglas Gregor39982192010-08-15 06:18:01 +00002896 bool alreadyVisitedContext(DeclContext *Ctx) {
2897 return VisitedContexts.count(Ctx);
2898 }
2899
Douglas Gregor2d435302009-12-30 17:04:44 +00002900 /// \brief Determine whether the given declaration is hidden in the
2901 /// current scope.
2902 ///
2903 /// \returns the declaration that hides the given declaration, or
2904 /// NULL if no such declaration exists.
2905 NamedDecl *checkHidden(NamedDecl *ND);
2906
2907 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002908 void add(NamedDecl *ND) {
2909 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2910 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002911};
2912
2913/// \brief RAII object that records when we've entered a shadow context.
2914class ShadowContextRAII {
2915 VisibleDeclsRecord &Visible;
2916
2917 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2918
2919public:
2920 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2921 Visible.ShadowMaps.push_back(ShadowMap());
2922 }
2923
2924 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00002925 Visible.ShadowMaps.pop_back();
2926 }
2927};
2928
2929} // end anonymous namespace
2930
Douglas Gregor2d435302009-12-30 17:04:44 +00002931NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002932 // Look through using declarations.
2933 ND = ND->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002934
Douglas Gregor2d435302009-12-30 17:04:44 +00002935 unsigned IDNS = ND->getIdentifierNamespace();
2936 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2937 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2938 SM != SMEnd; ++SM) {
2939 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2940 if (Pos == SM->end())
2941 continue;
2942
Aaron Ballman1e606f42014-07-15 22:03:49 +00002943 for (auto *D : Pos->second) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002944 // A tag declaration does not hide a non-tag declaration.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002945 if (D->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002946 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00002947 Decl::IDNS_ObjCProtocol)))
2948 continue;
2949
2950 // Protocols are in distinct namespaces from everything else.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002951 if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor2d435302009-12-30 17:04:44 +00002952 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Aaron Ballman1e606f42014-07-15 22:03:49 +00002953 D->getIdentifierNamespace() != IDNS)
Douglas Gregor2d435302009-12-30 17:04:44 +00002954 continue;
2955
Douglas Gregor09bbc652010-01-14 15:47:35 +00002956 // Functions and function templates in the same scope overload
2957 // rather than hide. FIXME: Look for hiding based on function
2958 // signatures!
Aaron Ballman1e606f42014-07-15 22:03:49 +00002959 if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Alp Tokera2794f92014-01-22 07:29:52 +00002960 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002961 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002962 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002963
Douglas Gregor2d435302009-12-30 17:04:44 +00002964 // We've found a declaration that hides this one.
Aaron Ballman1e606f42014-07-15 22:03:49 +00002965 return D;
Douglas Gregor2d435302009-12-30 17:04:44 +00002966 }
2967 }
2968
Craig Topperc3ec1492014-05-26 06:22:03 +00002969 return nullptr;
Douglas Gregor2d435302009-12-30 17:04:44 +00002970}
2971
2972static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2973 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002974 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002975 VisibleDeclConsumer &Consumer,
2976 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002977 if (!Ctx)
2978 return;
2979
Douglas Gregor2d435302009-12-30 17:04:44 +00002980 // Make sure we don't visit the same context twice.
2981 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2982 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002983
Douglas Gregor7454c562010-07-02 20:37:36 +00002984 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2985 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2986
Douglas Gregor2d435302009-12-30 17:04:44 +00002987 // Enumerate all of the results in this context.
Aaron Ballman576114e2014-03-14 15:28:49 +00002988 for (const auto &R : Ctx->lookups()) {
2989 for (auto *I : R) {
2990 if (NamedDecl *ND = dyn_cast<NamedDecl>(I)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00002991 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00002992 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002993 Visited.add(ND);
2994 }
Douglas Gregora3b23b02010-12-09 21:44:02 +00002995 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002996 }
2997 }
2998
2999 // Traverse using directives for qualified name lookup.
3000 if (QualifiedNameLookup) {
3001 ShadowContextRAII Shadow(Visited);
Aaron Ballman804a7fb2014-03-17 17:14:12 +00003002 for (auto I : Ctx->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00003003 LookupVisibleDecls(I->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003004 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003005 }
3006 }
3007
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003008 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00003009 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00003010 if (!Record->hasDefinition())
3011 return;
3012
Aaron Ballman574705e2014-03-13 15:41:46 +00003013 for (const auto &B : Record->bases()) {
3014 QualType BaseType = B.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003015
Douglas Gregor2d435302009-12-30 17:04:44 +00003016 // Don't look into dependent bases, because name lookup can't look
3017 // there anyway.
3018 if (BaseType->isDependentType())
3019 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003020
Douglas Gregor2d435302009-12-30 17:04:44 +00003021 const RecordType *Record = BaseType->getAs<RecordType>();
3022 if (!Record)
3023 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003024
Douglas Gregor2d435302009-12-30 17:04:44 +00003025 // FIXME: It would be nice to be able to determine whether referencing
3026 // a particular member would be ambiguous. For example, given
3027 //
3028 // struct A { int member; };
3029 // struct B { int member; };
3030 // struct C : A, B { };
3031 //
3032 // void f(C *c) { c->### }
3033 //
3034 // accessing 'member' would result in an ambiguity. However, we
3035 // could be smart enough to qualify the member with the base
3036 // class, e.g.,
3037 //
3038 // c->B::member
3039 //
3040 // or
3041 //
3042 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003043
Douglas Gregor2d435302009-12-30 17:04:44 +00003044 // Find results in this base class (and its bases).
3045 ShadowContextRAII Shadow(Visited);
3046 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003047 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003048 }
3049 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003050
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003051 // Traverse the contexts of Objective-C classes.
3052 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3053 // Traverse categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003054 for (auto *Cat : IFace->visible_categories()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003055 ShadowContextRAII Shadow(Visited);
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003056 LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003057 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003058 }
3059
3060 // Traverse protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003061 for (auto *I : IFace->all_referenced_protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003062 ShadowContextRAII Shadow(Visited);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003063 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003064 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003065 }
3066
3067 // Traverse the superclass.
3068 if (IFace->getSuperClass()) {
3069 ShadowContextRAII Shadow(Visited);
3070 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003071 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003072 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003073
Douglas Gregor0b59e802010-04-19 18:02:19 +00003074 // If there is an implementation, traverse it. We do this to find
3075 // synthesized ivars.
3076 if (IFace->getImplementation()) {
3077 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003078 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky13668f22012-04-03 20:26:45 +00003079 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor0b59e802010-04-19 18:02:19 +00003080 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003081 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003082 for (auto *I : Protocol->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003083 ShadowContextRAII Shadow(Visited);
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003084 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003085 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003086 }
3087 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003088 for (auto *I : Category->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003089 ShadowContextRAII Shadow(Visited);
Aaron Ballman19a41762014-03-14 12:55:57 +00003090 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003091 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003092 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003093
Douglas Gregor0b59e802010-04-19 18:02:19 +00003094 // If there is an implementation, traverse it.
3095 if (Category->getImplementation()) {
3096 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003097 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00003098 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003099 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003100 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003101}
3102
3103static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3104 UnqualUsingDirectiveSet &UDirs,
3105 VisibleDeclConsumer &Consumer,
3106 VisibleDeclsRecord &Visited) {
3107 if (!S)
3108 return;
3109
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003110 if (!S->getEntity() ||
3111 (!S->getParent() &&
Ted Kremenekc37877d2013-10-08 17:08:03 +00003112 !Visited.alreadyVisitedContext(S->getEntity())) ||
3113 (S->getEntity())->isFunctionOrMethod()) {
Richard Smith541b38b2013-09-20 01:15:31 +00003114 FindLocalExternScope FindLocals(Result);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003115 // Walk through the declarations in this Scope.
Aaron Ballman35c54952014-03-17 16:55:25 +00003116 for (auto *D : S->decls()) {
3117 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Douglas Gregor4a814562011-12-14 16:03:29 +00003118 if ((ND = Result.getAcceptableDecl(ND))) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003119 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003120 Visited.add(ND);
3121 }
3122 }
3123 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003124
Douglas Gregor66230062010-03-15 14:33:29 +00003125 // FIXME: C++ [temp.local]p8
Craig Topperc3ec1492014-05-26 06:22:03 +00003126 DeclContext *Entity = nullptr;
Douglas Gregor4f248632010-01-01 17:44:25 +00003127 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003128 // Look into this scope's declaration context, along with any of its
3129 // parent lookup contexts (e.g., enclosing classes), up to the point
3130 // where we hit the context stored in the next outer scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00003131 Entity = S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00003132 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003133
Douglas Gregorea166062010-03-15 15:26:48 +00003134 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00003135 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003136 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3137 if (Method->isInstanceMethod()) {
3138 // For instance methods, look for ivars in the method's interface.
3139 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3140 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003141 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003142 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Richard Smithe156254d2013-08-20 20:35:18 +00003143 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003144 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003145 }
3146
3147 // We've already performed all of the name lookup that we need
3148 // to for Objective-C methods; the next context will be the
3149 // outer scope.
3150 break;
3151 }
3152
Douglas Gregor2d435302009-12-30 17:04:44 +00003153 if (Ctx->isFunctionOrMethod())
3154 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003155
3156 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003157 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003158 }
3159 } else if (!S->getParent()) {
3160 // Look into the translation unit scope. We walk through the translation
3161 // unit's declaration context, because the Scope itself won't have all of
3162 // the declarations if we loaded a precompiled header.
3163 // FIXME: We would like the translation unit's Scope object to point to the
3164 // translation unit, so we don't need this special "if" branch. However,
3165 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003166 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00003167 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003168 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00003169 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003170 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003171 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003172 }
3173
Douglas Gregor2d435302009-12-30 17:04:44 +00003174 if (Entity) {
3175 // Lookup visible declarations in any namespaces found by using
3176 // directives.
3177 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003178 std::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
Douglas Gregor2d435302009-12-30 17:04:44 +00003179 for (; UI != UEnd; ++UI)
3180 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003181 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003182 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003183 }
3184
3185 // Lookup names in the parent scope.
3186 ShadowContextRAII Shadow(Visited);
3187 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3188}
3189
3190void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003191 VisibleDeclConsumer &Consumer,
3192 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003193 // Determine the set of using directives available during
3194 // unqualified name lookup.
3195 Scope *Initial = S;
3196 UnqualUsingDirectiveSet UDirs;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003197 if (getLangOpts().CPlusPlus) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003198 // Find the first namespace or translation-unit scope.
3199 while (S && !isNamespaceOrTranslationUnitScope(S))
3200 S = S->getParent();
3201
3202 UDirs.visitScopeChain(Initial, S);
3203 }
3204 UDirs.done();
3205
3206 // Look for visible declarations.
3207 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003208 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003209 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003210 if (!IncludeGlobalScope)
3211 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003212 ShadowContextRAII Shadow(Visited);
3213 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3214}
3215
3216void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003217 VisibleDeclConsumer &Consumer,
3218 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003219 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003220 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003221 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003222 if (!IncludeGlobalScope)
3223 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003224 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003225 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003226 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003227}
3228
Chris Lattner43e7f312011-02-18 02:08:43 +00003229/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003230/// If GnuLabelLoc is a valid source location, then this is a definition
3231/// of an __label__ label name, otherwise it is a normal label definition
3232/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003233LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003234 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003235 // Do a lookup to see if we have a label with this name already.
Craig Topperc3ec1492014-05-26 06:22:03 +00003236 NamedDecl *Res = nullptr;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003237
3238 if (GnuLabelLoc.isValid()) {
3239 // Local label definitions always shadow existing labels.
3240 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3241 Scope *S = CurScope;
3242 PushOnScopeChains(Res, S, true);
3243 return cast<LabelDecl>(Res);
3244 }
3245
3246 // Not a GNU local label.
3247 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3248 // If we found a label, check to see if it is in the same context as us.
3249 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003250 if (Res && Res->getDeclContext() != CurContext)
Craig Topperc3ec1492014-05-26 06:22:03 +00003251 Res = nullptr;
3252 if (!Res) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003253 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003254 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3255 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003256 assert(S && "Not in a function?");
3257 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003258 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003259 return cast<LabelDecl>(Res);
3260}
3261
3262//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003263// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003264//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003265
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003266static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3267 TypoCorrection &Candidate) {
3268 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3269 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3270}
3271
3272static void LookupPotentialTypoResult(Sema &SemaRef,
3273 LookupResult &Res,
3274 IdentifierInfo *Name,
3275 Scope *S, CXXScopeSpec *SS,
3276 DeclContext *MemberContext,
3277 bool EnteringContext,
3278 bool isObjCIvarLookup,
3279 bool FindHidden);
3280
3281// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3282// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3283// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3284static void getNestedNameSpecifierIdentifiers(
3285 NestedNameSpecifier *NNS,
3286 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3287 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3288 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3289 else
3290 Identifiers.clear();
3291
3292 const IdentifierInfo *II = nullptr;
3293
3294 switch (NNS->getKind()) {
3295 case NestedNameSpecifier::Identifier:
3296 II = NNS->getAsIdentifier();
3297 break;
3298
3299 case NestedNameSpecifier::Namespace:
3300 if (NNS->getAsNamespace()->isAnonymousNamespace())
3301 return;
3302 II = NNS->getAsNamespace()->getIdentifier();
3303 break;
3304
3305 case NestedNameSpecifier::NamespaceAlias:
3306 II = NNS->getAsNamespaceAlias()->getIdentifier();
3307 break;
3308
3309 case NestedNameSpecifier::TypeSpecWithTemplate:
3310 case NestedNameSpecifier::TypeSpec:
3311 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3312 break;
3313
3314 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00003315 case NestedNameSpecifier::Super:
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003316 return;
3317 }
3318
3319 if (II)
3320 Identifiers.push_back(II);
3321}
3322
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003323void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003324 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003325 // Don't consider hidden names for typo correction.
3326 if (Hiding)
3327 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003328
Douglas Gregor2d435302009-12-30 17:04:44 +00003329 // Only consider entities with identifiers for names, ignoring
3330 // special names (constructors, overloaded operators, selectors,
3331 // etc.).
3332 IdentifierInfo *Name = ND->getIdentifier();
3333 if (!Name)
3334 return;
3335
Richard Smithe156254d2013-08-20 20:35:18 +00003336 // Only consider visible declarations and declarations from modules with
3337 // names that exactly match.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003338 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo &&
Richard Smithe156254d2013-08-20 20:35:18 +00003339 !findAcceptableDecl(SemaRef, ND))
3340 return;
3341
Douglas Gregor57756ea2010-10-14 22:11:03 +00003342 FoundName(Name->getName());
3343}
3344
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003345void TypoCorrectionConsumer::FoundName(StringRef Name) {
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003346 // Compute the edit distance between the typo and the name of this
3347 // entity, and add the identifier to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003348 addName(Name, nullptr);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003349}
3350
3351void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3352 // Compute the edit distance between the typo and this keyword,
3353 // and add the keyword to the list of results.
Craig Topperc3ec1492014-05-26 06:22:03 +00003354 addName(Keyword, nullptr, nullptr, true);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003355}
3356
3357void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
3358 NestedNameSpecifier *NNS, bool isKeyword) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003359 // Use a simple length-based heuristic to determine the minimum possible
3360 // edit distance. If the minimum isn't good enough, bail out early.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003361 StringRef TypoStr = Typo->getName();
3362 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
3363 if (MinED && TypoStr.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00003364 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003365
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003366 // Compute an upper bound on the allowable edit distance, so that the
3367 // edit-distance algorithm can short-circuit.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003368 unsigned UpperBound = (TypoStr.size() + 2) / 3 + 1;
3369 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003370 if (ED >= UpperBound) return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003371
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003372 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003373 if (isKeyword) TC.makeKeyword();
3374 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003375}
3376
Kaelyn Takatad2287c32014-10-27 18:07:13 +00003377static const unsigned MaxTypoDistanceResultSets = 5;
3378
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003379void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003380 StringRef TypoStr = Typo->getName();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003381 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003382
3383 // For very short typos, ignore potential corrections that have a different
3384 // base identifier from the typo or which have a normalized edit distance
3385 // longer than the typo itself.
3386 if (TypoStr.size() < 3 &&
3387 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
3388 return;
3389
3390 // If the correction is resolved but is not viable, ignore it.
3391 if (Correction.isResolved() &&
Kaelyn Takata89c881b2014-10-27 18:07:29 +00003392 !isCandidateViable(*CorrectionValidator, Correction))
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003393 return;
3394
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003395 TypoResultList &CList =
3396 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003397
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003398 if (!CList.empty() && !CList.back().isResolved())
3399 CList.pop_back();
3400 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3401 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3402 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3403 RI != RIEnd; ++RI) {
3404 // If the Correction refers to a decl already in the result list,
3405 // replace the existing result if the string representation of Correction
3406 // comes before the current result alphabetically, then stop as there is
3407 // nothing more to be done to add Correction to the candidate set.
3408 if (RI->getCorrectionDecl() == NewND) {
3409 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3410 *RI = Correction;
3411 return;
3412 }
3413 }
3414 }
3415 if (CList.empty() || Correction.isResolved())
3416 CList.push_back(Correction);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003417
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003418 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003419 CorrectionResults.erase(std::prev(CorrectionResults.end()));
3420}
3421
3422void TypoCorrectionConsumer::addNamespaces(
3423 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
3424 SearchNamespaces = true;
3425
3426 for (auto KNPair : KnownNamespaces)
3427 Namespaces.addNameSpecifier(KNPair.first);
3428
3429 bool SSIsTemplate = false;
3430 if (NestedNameSpecifier *NNS =
3431 (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
3432 if (const Type *T = NNS->getAsType())
3433 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
3434 }
3435 for (const auto *TI : SemaRef.getASTContext().types()) {
3436 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
3437 CD = CD->getCanonicalDecl();
3438 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
3439 !CD->isUnion() && CD->getIdentifier() &&
3440 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
3441 (CD->isBeingDefined() || CD->isCompleteDefinition()))
3442 Namespaces.addNameSpecifier(CD);
3443 }
3444 }
3445}
3446
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003447const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
3448 if (++CurrentTCIndex < ValidatedCorrections.size())
3449 return ValidatedCorrections[CurrentTCIndex];
3450
3451 CurrentTCIndex = ValidatedCorrections.size();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003452 while (!CorrectionResults.empty()) {
3453 auto DI = CorrectionResults.begin();
3454 if (DI->second.empty()) {
3455 CorrectionResults.erase(DI);
3456 continue;
3457 }
3458
3459 auto RI = DI->second.begin();
3460 if (RI->second.empty()) {
3461 DI->second.erase(RI);
3462 performQualifiedLookups();
3463 continue;
3464 }
3465
3466 TypoCorrection TC = RI->second.pop_back_val();
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003467 if (TC.isResolved() || resolveCorrection(TC)) {
3468 ValidatedCorrections.push_back(TC);
3469 return ValidatedCorrections[CurrentTCIndex];
3470 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003471 }
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003472 return ValidatedCorrections[0]; // The empty correction.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003473}
3474
3475bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
3476 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
3477 DeclContext *TempMemberContext = MemberContext;
3478 CXXScopeSpec *TempSS = SS;
Kaelyn Takata0d6a3ed2014-10-27 18:07:34 +00003479 if (Candidate.getCorrectionRange().isInvalid())
3480 Candidate.setCorrectionRange(TempSS, Result.getLookupNameInfo());
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003481retry_lookup:
3482 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
3483 EnteringContext,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00003484 CorrectionValidator->IsObjCIvarLookup,
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003485 Name == Typo && !Candidate.WillReplaceSpecifier());
3486 switch (Result.getResultKind()) {
3487 case LookupResult::NotFound:
3488 case LookupResult::NotFoundInCurrentInstantiation:
3489 case LookupResult::FoundUnresolvedValue:
3490 if (TempSS) {
3491 // Immediately retry the lookup without the given CXXScopeSpec
3492 TempSS = nullptr;
3493 Candidate.WillReplaceSpecifier(true);
3494 goto retry_lookup;
3495 }
3496 if (TempMemberContext) {
3497 if (SS && !TempSS)
3498 TempSS = SS;
3499 TempMemberContext = nullptr;
3500 goto retry_lookup;
3501 }
3502 if (SearchNamespaces)
3503 QualifiedResults.push_back(Candidate);
3504 break;
3505
3506 case LookupResult::Ambiguous:
3507 // We don't deal with ambiguities.
3508 break;
3509
3510 case LookupResult::Found:
3511 case LookupResult::FoundOverloaded:
3512 // Store all of the Decls for overloaded symbols
3513 for (auto *TRD : Result)
3514 Candidate.addCorrectionDecl(TRD);
Kaelyn Takata89c881b2014-10-27 18:07:29 +00003515 if (!isCandidateViable(*CorrectionValidator, Candidate)) {
Kaelyn Takata68fdd592014-06-11 18:07:01 +00003516 if (SearchNamespaces)
3517 QualifiedResults.push_back(Candidate);
3518 break;
3519 }
3520 return true;
3521 }
3522 return false;
3523}
3524
3525void TypoCorrectionConsumer::performQualifiedLookups() {
3526 unsigned TypoLen = Typo->getName().size();
3527 for (auto QR : QualifiedResults) {
3528 for (auto NSI : Namespaces) {
3529 DeclContext *Ctx = NSI.DeclCtx;
3530 const Type *NSType = NSI.NameSpecifier->getAsType();
3531
3532 // If the current NestedNameSpecifier refers to a class and the
3533 // current correction candidate is the name of that class, then skip
3534 // it as it is unlikely a qualified version of the class' constructor
3535 // is an appropriate correction.
3536 if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() : 0) {
3537 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
3538 continue;
3539 }
3540
3541 TypoCorrection TC(QR);
3542 TC.ClearCorrectionDecls();
3543 TC.setCorrectionSpecifier(NSI.NameSpecifier);
3544 TC.setQualifierDistance(NSI.EditDistance);
3545 TC.setCallbackDistance(0); // Reset the callback distance
3546
3547 // If the current correction candidate and namespace combination are
3548 // too far away from the original typo based on the normalized edit
3549 // distance, then skip performing a qualified name lookup.
3550 unsigned TmpED = TC.getEditDistance(true);
3551 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
3552 TypoLen / TmpED < 3)
3553 continue;
3554
3555 Result.clear();
3556 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
3557 if (!SemaRef.LookupQualifiedName(Result, Ctx))
3558 continue;
3559
3560 // Any corrections added below will be validated in subsequent
3561 // iterations of the main while() loop over the Consumer's contents.
3562 switch (Result.getResultKind()) {
3563 case LookupResult::Found:
3564 case LookupResult::FoundOverloaded: {
3565 if (SS && SS->isValid()) {
3566 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
3567 std::string OldQualified;
3568 llvm::raw_string_ostream OldOStream(OldQualified);
3569 SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
3570 OldOStream << Typo->getName();
3571 // If correction candidate would be an identical written qualified
3572 // identifer, then the existing CXXScopeSpec probably included a
3573 // typedef that didn't get accounted for properly.
3574 if (OldOStream.str() == NewQualified)
3575 break;
3576 }
3577 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
3578 TRD != TRDEnd; ++TRD) {
3579 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
3580 NSType ? NSType->getAsCXXRecordDecl()
3581 : nullptr,
3582 TRD.getPair()) == Sema::AR_accessible)
3583 TC.addCorrectionDecl(*TRD);
3584 }
3585 if (TC.isResolved())
3586 addCorrection(TC);
3587 break;
3588 }
3589 case LookupResult::NotFound:
3590 case LookupResult::NotFoundInCurrentInstantiation:
3591 case LookupResult::Ambiguous:
3592 case LookupResult::FoundUnresolvedValue:
3593 break;
3594 }
3595 }
3596 }
3597 QualifiedResults.clear();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003598}
3599
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00003600TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
3601 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
3602 : Context(Context), CurContextChain(buildContextChain(CurContext)),
3603 isSorted(false) {
3604 if (NestedNameSpecifier *NNS =
3605 CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
3606 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
3607 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3608
3609 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
3610 }
3611 // Build the list of identifiers that would be used for an absolute
3612 // (from the global context) NestedNameSpecifier referring to the current
3613 // context.
3614 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3615 CEnd = CurContextChain.rend();
3616 C != CEnd; ++C) {
3617 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3618 CurContextIdentifiers.push_back(ND->getIdentifier());
3619 }
3620
3621 // Add the global context as a NestedNameSpecifier
3622 Distances.insert(1);
Hans Wennborg66010132014-06-11 21:24:13 +00003623 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
3624 NestedNameSpecifier::GlobalSpecifier(Context), 1};
3625 DistanceMap[1].push_back(SI);
Kaelyn Takatacd7c3a92014-06-11 18:33:46 +00003626}
3627
Kaelyn Takata7dcc0e62014-06-11 18:07:08 +00003628auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
3629 DeclContext *Start) -> DeclContextList {
Nick Lewycky0d9b3192013-04-08 21:55:21 +00003630 assert(Start && "Building a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003631 DeclContextList Chain;
Craig Topperc3ec1492014-05-26 06:22:03 +00003632 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003633 DC = DC->getLookupParent()) {
3634 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3635 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3636 !(ND && ND->isAnonymousNamespace()))
3637 Chain.push_back(DC->getPrimaryContext());
3638 }
3639 return Chain;
3640}
3641
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003642void TypoCorrectionConsumer::NamespaceSpecifierSet::sortNamespaces() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003643 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003644 sortedDistances.append(Distances.begin(), Distances.end());
3645
3646 if (sortedDistances.size() > 1)
3647 std::sort(sortedDistances.begin(), sortedDistances.end());
3648
3649 Specifiers.clear();
Aaron Ballman1e606f42014-07-15 22:03:49 +00003650 for (auto D : sortedDistances) {
3651 SpecifierInfoList &SpecList = DistanceMap[D];
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003652 Specifiers.append(SpecList.begin(), SpecList.end());
3653 }
3654
3655 isSorted = true;
3656}
3657
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003658unsigned
3659TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
3660 DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003661 unsigned NumSpecifiers = 0;
3662 for (DeclContextList::reverse_iterator C = DeclChain.rbegin(),
3663 CEnd = DeclChain.rend();
3664 C != CEnd; ++C) {
3665 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) {
3666 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3667 ++NumSpecifiers;
3668 } else if (RecordDecl *RD = dyn_cast_or_null<RecordDecl>(*C)) {
3669 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
3670 RD->getTypeForDecl());
3671 ++NumSpecifiers;
3672 }
3673 }
3674 return NumSpecifiers;
3675}
3676
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003677void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
3678 DeclContext *Ctx) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003679 NestedNameSpecifier *NNS = nullptr;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003680 unsigned NumSpecifiers = 0;
Kaelyn Takata0fc75192014-06-11 18:06:56 +00003681 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003682 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
3683
3684 // Eliminate common elements from the two DeclContext chains.
3685 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3686 CEnd = CurContextChain.rend();
3687 C != CEnd && !NamespaceDeclChain.empty() &&
3688 NamespaceDeclChain.back() == *C; ++C) {
3689 NamespaceDeclChain.pop_back();
3690 }
3691
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003692 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003693 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003694
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003695 // Add an explicit leading '::' specifier if needed.
3696 if (NamespaceDeclChain.empty()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003697 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003698 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003699 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003700 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003701 } else if (NamedDecl *ND =
3702 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003703 IdentifierInfo *Name = ND->getIdentifier();
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003704 bool SameNameSpecifier = false;
3705 if (std::find(CurNameSpecifierIdentifiers.begin(),
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003706 CurNameSpecifierIdentifiers.end(),
3707 Name) != CurNameSpecifierIdentifiers.end()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003708 std::string NewNameSpecifier;
3709 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
3710 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
3711 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3712 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3713 SpecifierOStream.flush();
3714 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003715 }
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003716 if (SameNameSpecifier ||
3717 std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3718 Name) != CurContextIdentifiers.end()) {
3719 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
3720 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3721 NumSpecifiers =
Kaelyn Takataa5bdbc82014-06-11 18:07:05 +00003722 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003723 }
3724 }
3725
3726 // If the built NestedNameSpecifier would be replacing an existing
3727 // NestedNameSpecifier, use the number of component identifiers that
3728 // would need to be changed as the edit distance instead of the number
3729 // of components in the built NestedNameSpecifier.
3730 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3731 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3732 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3733 NumSpecifiers = llvm::ComputeEditDistance(
Craig Topper8c2a2a02014-08-30 16:55:39 +00003734 llvm::makeArrayRef(CurNameSpecifierIdentifiers),
3735 llvm::makeArrayRef(NewNameSpecifierIdentifiers));
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003736 }
3737
3738 isSorted = false;
3739 Distances.insert(NumSpecifiers);
Hans Wennborg66010132014-06-11 21:24:13 +00003740 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
3741 DistanceMap[NumSpecifiers].push_back(SI);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003742}
3743
Douglas Gregord507d772010-10-20 03:06:34 +00003744/// \brief Perform name lookup for a possible result for typo correction.
3745static void LookupPotentialTypoResult(Sema &SemaRef,
3746 LookupResult &Res,
3747 IdentifierInfo *Name,
3748 Scope *S, CXXScopeSpec *SS,
3749 DeclContext *MemberContext,
3750 bool EnteringContext,
Richard Smithe156254d2013-08-20 20:35:18 +00003751 bool isObjCIvarLookup,
3752 bool FindHidden) {
Douglas Gregord507d772010-10-20 03:06:34 +00003753 Res.suppressDiagnostics();
3754 Res.clear();
3755 Res.setLookupName(Name);
Richard Smithe156254d2013-08-20 20:35:18 +00003756 Res.setAllowHidden(FindHidden);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003757 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00003758 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003759 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00003760 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3761 Res.addDecl(Ivar);
3762 Res.resolveKind();
3763 return;
3764 }
3765 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003766
Douglas Gregord507d772010-10-20 03:06:34 +00003767 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3768 Res.addDecl(Prop);
3769 Res.resolveKind();
3770 return;
3771 }
3772 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003773
Douglas Gregord507d772010-10-20 03:06:34 +00003774 SemaRef.LookupQualifiedName(Res, MemberContext);
3775 return;
3776 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003777
3778 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00003779 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003780
Douglas Gregord507d772010-10-20 03:06:34 +00003781 // Fake ivar lookup; this should really be part of
3782 // LookupParsedName.
3783 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3784 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003785 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00003786 (Res.isSingleResult() &&
3787 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003788 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00003789 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3790 Res.addDecl(IV);
3791 Res.resolveKind();
3792 }
3793 }
3794 }
3795}
3796
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003797/// \brief Add keywords to the consumer as possible typo corrections.
3798static void AddKeywordsToConsumer(Sema &SemaRef,
3799 TypoCorrectionConsumer &Consumer,
Richard Smithb3a1df02012-06-08 21:35:42 +00003800 Scope *S, CorrectionCandidateCallback &CCC,
3801 bool AfterNestedNameSpecifier) {
3802 if (AfterNestedNameSpecifier) {
3803 // For 'X::', we know exactly which keywords can appear next.
3804 Consumer.addKeywordResult("template");
3805 if (CCC.WantExpressionKeywords)
3806 Consumer.addKeywordResult("operator");
3807 return;
3808 }
3809
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003810 if (CCC.WantObjCSuper)
3811 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003812
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003813 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003814 // Add type-specifier keywords to the set of results.
Craig Topperd6d31ac2013-07-15 08:24:27 +00003815 static const char *const CTypeSpecs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003816 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00003817 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003818 "_Complex", "_Imaginary",
3819 // storage-specifiers as well
3820 "extern", "inline", "static", "typedef"
3821 };
3822
Craig Toppere5ce8312013-07-15 03:38:40 +00003823 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003824 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3825 Consumer.addKeywordResult(CTypeSpecs[I]);
3826
David Blaikiebbafb8a2012-03-11 07:00:24 +00003827 if (SemaRef.getLangOpts().C99)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003828 Consumer.addKeywordResult("restrict");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003829 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003830 Consumer.addKeywordResult("bool");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003831 else if (SemaRef.getLangOpts().C99)
Douglas Gregor3b22a882011-07-01 21:27:45 +00003832 Consumer.addKeywordResult("_Bool");
3833
David Blaikiebbafb8a2012-03-11 07:00:24 +00003834 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003835 Consumer.addKeywordResult("class");
3836 Consumer.addKeywordResult("typename");
3837 Consumer.addKeywordResult("wchar_t");
3838
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003839 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003840 Consumer.addKeywordResult("char16_t");
3841 Consumer.addKeywordResult("char32_t");
3842 Consumer.addKeywordResult("constexpr");
3843 Consumer.addKeywordResult("decltype");
3844 Consumer.addKeywordResult("thread_local");
3845 }
3846 }
3847
David Blaikiebbafb8a2012-03-11 07:00:24 +00003848 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003849 Consumer.addKeywordResult("typeof");
Kaelyn Takatab04846b2014-07-28 18:14:02 +00003850 } else if (CCC.WantFunctionLikeCasts) {
3851 static const char *const CastableTypeSpecs[] = {
3852 "char", "double", "float", "int", "long", "short",
3853 "signed", "unsigned", "void"
3854 };
3855 for (auto *kw : CastableTypeSpecs)
3856 Consumer.addKeywordResult(kw);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003857 }
3858
David Blaikiebbafb8a2012-03-11 07:00:24 +00003859 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003860 Consumer.addKeywordResult("const_cast");
3861 Consumer.addKeywordResult("dynamic_cast");
3862 Consumer.addKeywordResult("reinterpret_cast");
3863 Consumer.addKeywordResult("static_cast");
3864 }
3865
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003866 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003867 Consumer.addKeywordResult("sizeof");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003868 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003869 Consumer.addKeywordResult("false");
3870 Consumer.addKeywordResult("true");
3871 }
3872
David Blaikiebbafb8a2012-03-11 07:00:24 +00003873 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topperd6d31ac2013-07-15 08:24:27 +00003874 static const char *const CXXExprs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003875 "delete", "new", "operator", "throw", "typeid"
3876 };
Craig Toppere5ce8312013-07-15 03:38:40 +00003877 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003878 for (unsigned I = 0; I != NumCXXExprs; ++I)
3879 Consumer.addKeywordResult(CXXExprs[I]);
3880
3881 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3882 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3883 Consumer.addKeywordResult("this");
3884
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003885 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003886 Consumer.addKeywordResult("alignof");
3887 Consumer.addKeywordResult("nullptr");
3888 }
3889 }
Jordan Rose58d54722012-06-30 21:33:57 +00003890
3891 if (SemaRef.getLangOpts().C11) {
3892 // FIXME: We should not suggest _Alignof if the alignof macro
3893 // is present.
3894 Consumer.addKeywordResult("_Alignof");
3895 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003896 }
3897
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003898 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003899 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3900 // Statements.
Craig Topperd6d31ac2013-07-15 08:24:27 +00003901 static const char *const CStmts[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003902 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Toppere5ce8312013-07-15 03:38:40 +00003903 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003904 for (unsigned I = 0; I != NumCStmts; ++I)
3905 Consumer.addKeywordResult(CStmts[I]);
3906
David Blaikiebbafb8a2012-03-11 07:00:24 +00003907 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003908 Consumer.addKeywordResult("catch");
3909 Consumer.addKeywordResult("try");
3910 }
3911
3912 if (S && S->getBreakParent())
3913 Consumer.addKeywordResult("break");
3914
3915 if (S && S->getContinueParent())
3916 Consumer.addKeywordResult("continue");
3917
3918 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3919 Consumer.addKeywordResult("case");
3920 Consumer.addKeywordResult("default");
3921 }
3922 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003923 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003924 Consumer.addKeywordResult("namespace");
3925 Consumer.addKeywordResult("template");
3926 }
3927
3928 if (S && S->isClassScope()) {
3929 Consumer.addKeywordResult("explicit");
3930 Consumer.addKeywordResult("friend");
3931 Consumer.addKeywordResult("mutable");
3932 Consumer.addKeywordResult("private");
3933 Consumer.addKeywordResult("protected");
3934 Consumer.addKeywordResult("public");
3935 Consumer.addKeywordResult("virtual");
3936 }
3937 }
3938
David Blaikiebbafb8a2012-03-11 07:00:24 +00003939 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003940 Consumer.addKeywordResult("using");
3941
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003942 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003943 Consumer.addKeywordResult("static_assert");
3944 }
3945 }
3946}
3947
Richard Smithe156254d2013-08-20 20:35:18 +00003948/// \brief Check whether the declarations found for a typo correction are
3949/// visible, and if none of them are, convert the correction to an 'import
3950/// a module' correction.
Kaelyn Takata61df4a72014-06-17 23:41:33 +00003951static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
Richard Smithe156254d2013-08-20 20:35:18 +00003952 if (TC.begin() == TC.end())
3953 return;
3954
3955 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3956
3957 for (/**/; DI != DE; ++DI)
3958 if (!LookupResult::isVisible(SemaRef, *DI))
3959 break;
3960 // Nothing to do if all decls are visible.
3961 if (DI == DE)
3962 return;
3963
3964 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3965 bool AnyVisibleDecls = !NewDecls.empty();
3966
3967 for (/**/; DI != DE; ++DI) {
3968 NamedDecl *VisibleDecl = *DI;
3969 if (!LookupResult::isVisible(SemaRef, *DI))
3970 VisibleDecl = findAcceptableDecl(SemaRef, *DI);
3971
3972 if (VisibleDecl) {
3973 if (!AnyVisibleDecls) {
3974 // Found a visible decl, discard all hidden ones.
3975 AnyVisibleDecls = true;
3976 NewDecls.clear();
3977 }
3978 NewDecls.push_back(VisibleDecl);
3979 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
3980 NewDecls.push_back(*DI);
3981 }
3982
3983 if (NewDecls.empty())
3984 TC = TypoCorrection();
3985 else {
3986 TC.setCorrectionDecls(NewDecls);
3987 TC.setRequiresImport(!AnyVisibleDecls);
3988 }
3989}
3990
Douglas Gregor2d435302009-12-30 17:04:44 +00003991/// \brief Try to "correct" a typo in the source code by finding
3992/// visible declarations whose names are similar to the name that was
3993/// present in the source code.
3994///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003995/// \param TypoName the \c DeclarationNameInfo structure that contains
3996/// the name that was present in the source code along with its location.
3997///
3998/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00003999///
4000/// \param S the scope in which name lookup occurs.
4001///
4002/// \param SS the nested-name-specifier that precedes the name we're
4003/// looking for, if present.
4004///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004005/// \param CCC A CorrectionCandidateCallback object that provides further
4006/// validation of typo correction candidates. It also provides flags for
4007/// determining the set of keywords permitted.
4008///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00004009/// \param MemberContext if non-NULL, the context in which to look for
4010/// a member access expression.
4011///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004012/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00004013/// the nested-name-specifier SS.
4014///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004015/// \param OPT when non-NULL, the search for visible declarations will
4016/// also walk the protocols in the qualified interfaces of \p OPT.
4017///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004018/// \returns a \c TypoCorrection containing the corrected name if the typo
4019/// along with information such as the \c NamedDecl where the corrected name
4020/// was declared, and any additional \c NestedNameSpecifier needed to access
4021/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
4022TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
4023 Sema::LookupNameKind LookupKind,
4024 Scope *S, CXXScopeSpec *SS,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004025 std::unique_ptr<CorrectionCandidateCallback> CCC,
John Thompson2255f2c2014-04-23 12:57:01 +00004026 CorrectTypoKind Mode,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004027 DeclContext *MemberContext,
4028 bool EnteringContext,
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004029 const ObjCObjectPointerType *OPT,
4030 bool RecordFailure) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004031 assert(CCC && "CorrectTypo requires a CorrectionCandidateCallback");
4032
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004033 // Always let the ExternalSource have the first chance at correction, even
4034 // if we would otherwise have given up.
4035 if (ExternalSource) {
4036 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004037 TypoName, LookupKind, S, SS, *CCC, MemberContext, EnteringContext, OPT))
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004038 return Correction;
4039 }
4040
Richard Smith1fff95c2013-09-12 23:28:08 +00004041 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4042 DisableTypoCorrection)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004043 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004044
Francois Pichet9c391132011-12-03 15:55:29 +00004045 // In Microsoft mode, don't perform typo correction in a template member
4046 // function dependent context because it interferes with the "lookup into
4047 // dependent bases of class templates" feature.
Alp Tokerbfa39342014-01-14 12:51:41 +00004048 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
Francois Pichet9c391132011-12-03 15:55:29 +00004049 isa<CXXMethodDecl>(CurContext))
4050 return TypoCorrection();
4051
Douglas Gregor2d435302009-12-30 17:04:44 +00004052 // We only attempt to correct typos for identifiers.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004053 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor2d435302009-12-30 17:04:44 +00004054 if (!Typo)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004055 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00004056
4057 // If the scope specifier itself was invalid, don't try to correct
4058 // typos.
4059 if (SS && SS->isInvalid())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004060 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00004061
4062 // Never try to correct typos during template deduction or
4063 // instantiation.
4064 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004065 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004066
Argyrios Kyrtzidis3e56dd42013-03-14 22:56:43 +00004067 // Don't try to correct 'super'.
4068 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4069 return TypoCorrection();
4070
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004071 // Abort if typo correction already failed for this specific typo.
4072 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4073 if (locs != TypoCorrectionFailures.end() &&
Aaron Ballman7fc6e1b2013-10-05 19:56:07 +00004074 locs->second.count(TypoName.getLoc()))
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004075 return TypoCorrection();
4076
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004077 // Don't try to correct the identifier "vector" when in AltiVec mode.
4078 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4079 // remove this workaround.
4080 if (getLangOpts().AltiVec && Typo->isStr("vector"))
4081 return TypoCorrection();
4082
John Thompson2309b152014-05-07 22:47:08 +00004083 // If we're handling a missing symbol error, using modules, and the
4084 // special search all modules option is used, look for a missing import.
John Thompson2d94bbb2014-04-23 19:04:32 +00004085 if ((Mode == CTK_ErrorRecovery) && getLangOpts().Modules &&
4086 getLangOpts().ModulesSearchAll) {
John Thompson2309b152014-05-07 22:47:08 +00004087 // The following has the side effect of loading the missing module.
4088 getModuleLoader().lookupMissingImports(Typo->getName(),
4089 TypoName.getLocStart());
John Thompson2255f2c2014-04-23 12:57:01 +00004090 }
4091
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004092 CorrectionCandidateCallback &CCCRef = *CCC;
4093 TypoCorrectionConsumer Consumer(*this, TypoName, LookupKind, S, SS,
4094 std::move(CCC), MemberContext,
4095 EnteringContext);
John Thompson2255f2c2014-04-23 12:57:01 +00004096
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00004097 // If a callback object considers an empty typo correction candidate to be
4098 // viable, assume it does not do any actual validation of the candidates.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004099 TypoCorrection EmptyCorrection;
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004100 bool ValidatingCallback = !isCandidateViable(CCCRef, EmptyCorrection);
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004101
Douglas Gregor280e1ee2010-04-14 20:04:41 +00004102 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor87074f12010-10-20 01:32:02 +00004103 bool IsUnqualifiedLookup = false;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004104 DeclContext *QualifiedDC = MemberContext;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004105 if (MemberContext) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004106 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004107
4108 // Look in qualified interfaces.
4109 if (OPT) {
Aaron Ballman83731462014-03-17 16:14:00 +00004110 for (auto *I : OPT->quals())
4111 LookupVisibleDecls(I, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004112 }
4113 } else if (SS && SS->isSet()) {
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004114 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4115 if (!QualifiedDC)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004116 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004117
Douglas Gregor87074f12010-10-20 01:32:02 +00004118 // Provide a stop gap for files that are just seriously broken. Trying
4119 // to correct all typos can turn into a HUGE performance penalty, causing
4120 // some files to take minutes to get rejected by the parser.
4121 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004122 return TypoCorrection();
Douglas Gregor87074f12010-10-20 01:32:02 +00004123 ++TyposCorrected;
4124
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004125 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
Douglas Gregor2d435302009-12-30 17:04:44 +00004126 } else {
Douglas Gregor87074f12010-10-20 01:32:02 +00004127 IsUnqualifiedLookup = true;
4128 UnqualifiedTyposCorrectedMap::iterator Cached
4129 = UnqualifiedTyposCorrected.find(Typo);
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004130 if (Cached != UnqualifiedTyposCorrected.end()) {
4131 // Add the cached value, unless it's a keyword or fails validation. In the
4132 // keyword case, we'll end up adding the keyword below.
4133 if (Cached->second) {
4134 if (!Cached->second.isKeyword() &&
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004135 isCandidateViable(CCCRef, Cached->second)) {
Serge Pavlovc0cd80f2013-10-14 14:05:48 +00004136 // Do not use correction that is unaccessible in the given scope.
Serge Pavlove8ae13f2013-10-15 14:24:32 +00004137 NamedDecl *CorrectionDecl = Cached->second.getCorrectionDecl();
Serge Pavlovc0cd80f2013-10-14 14:05:48 +00004138 DeclarationNameInfo NameInfo(CorrectionDecl->getDeclName(),
4139 CorrectionDecl->getLocation());
4140 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4141 if (LookupName(R, S))
4142 Consumer.addCorrection(Cached->second);
4143 }
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004144 } else {
4145 // Only honor no-correction cache hits when a callback that will validate
4146 // correction candidates is not being used.
4147 if (!ValidatingCallback)
4148 return TypoCorrection();
4149 }
4150 }
4151 if (Cached == UnqualifiedTyposCorrected.end()) {
Douglas Gregor87074f12010-10-20 01:32:02 +00004152 // Provide a stop gap for files that are just seriously broken. Trying
4153 // to correct all typos can turn into a HUGE performance penalty, causing
4154 // some files to take minutes to get rejected by the parser.
4155 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004156 return TypoCorrection();
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004157 }
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004158 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004159
Douglas Gregorb11f9452012-03-26 16:54:18 +00004160 // Determine whether we are going to search in the various namespaces for
4161 // corrections.
4162 bool SearchNamespaces
Kaelyn Uhrainf4657d52012-04-03 18:20:11 +00004163 = getLangOpts().CPlusPlus &&
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00004164 (IsUnqualifiedLookup || (SS && SS->isSet()));
Richard Smithe156254d2013-08-20 20:35:18 +00004165 // In a few cases we *only* want to search for corrections based on just
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004166 // adding or changing the nested name specifier.
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004167 unsigned TypoLen = Typo->getName().size();
4168 bool AllowOnlyNNSChanges = TypoLen < 3;
4169
Douglas Gregorb11f9452012-03-26 16:54:18 +00004170 if (IsUnqualifiedLookup || SearchNamespaces) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004171 // For unqualified lookup, look through all of the names that we have
4172 // seen in this translation unit.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00004173 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Aaron Ballman1e606f42014-07-15 22:03:49 +00004174 for (const auto &I : Context.Idents)
4175 Consumer.FoundName(I.getKey());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004176
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004177 // Walk through identifiers in external identifier sources.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00004178 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004179 if (IdentifierInfoLookup *External
4180 = Context.Idents.getExternalIdentifierLookup()) {
Ahmed Charlesb8984322014-03-07 20:03:18 +00004181 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004182 do {
4183 StringRef Name = Iter->Next();
4184 if (Name.empty())
4185 break;
Douglas Gregor57756ea2010-10-14 22:11:03 +00004186
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004187 Consumer.FoundName(Name);
4188 } while (true);
Douglas Gregor57756ea2010-10-14 22:11:03 +00004189 }
Douglas Gregor2d435302009-12-30 17:04:44 +00004190 }
4191
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004192 AddKeywordsToConsumer(*this, Consumer, S, CCCRef, SS && SS->isNotEmpty());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004193
Douglas Gregor280e1ee2010-04-14 20:04:41 +00004194 // If we haven't found anything, we're done.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004195 if (Consumer.empty())
4196 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4197 IsUnqualifiedLookup);
Douglas Gregor2d435302009-12-30 17:04:44 +00004198
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004199 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4200 // is not more that about a third of the length of the typo's identifier.
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00004201 unsigned ED = Consumer.getBestEditDistance(true);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004202 if (ED > 0 && TypoLen / ED < 3)
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004203 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4204 IsUnqualifiedLookup);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004205
Douglas Gregorb11f9452012-03-26 16:54:18 +00004206 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4207 // to search those namespaces.
4208 if (SearchNamespaces) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004209 // Load any externally-known namespaces.
4210 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004211 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004212 LoadedExternalKnownNamespaces = true;
4213 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
Aaron Ballman1e606f42014-07-15 22:03:49 +00004214 for (auto *N : ExternalKnownNamespaces)
4215 KnownNamespaces[N] = true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004216 }
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004217
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004218 Consumer.addNamespaces(KnownNamespaces);
Douglas Gregor87074f12010-10-20 01:32:02 +00004219 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004220
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004221 TypoCorrection BestTC = Consumer.getNextCorrection();
4222 TypoCorrection SecondBestTC = Consumer.getNextCorrection();
4223 if (!BestTC)
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004224 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004225
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004226 ED = BestTC.getEditDistance();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004227
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004228 if (!AllowOnlyNNSChanges && ED > 0 && TypoLen / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004229 // If this was an unqualified lookup and we believe the callback
4230 // object wouldn't have filtered out possible corrections, note
4231 // that no correction was found.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004232 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4233 IsUnqualifiedLookup && !ValidatingCallback);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004234 }
4235
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004236 // If only a single name remains, return that result.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004237 if (!SecondBestTC ||
4238 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
4239 const TypoCorrection &Result = BestTC;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004240
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00004241 // Don't correct to a keyword that's the same as the typo; the keyword
4242 // wasn't actually in scope.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004243 if (ED == 0 && Result.isKeyword())
4244 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004245
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004246 // Record the correction for unqualified lookup.
4247 if (IsUnqualifiedLookup)
4248 UnqualifiedTyposCorrected[Typo] = Result;
4249
David Blaikie04ea41c2012-10-12 20:00:44 +00004250 TypoCorrection TC = Result;
4251 TC.setCorrectionRange(SS, TypoName);
Kaelyn Takataa95ebc62014-06-17 23:47:29 +00004252 checkCorrectionVisibility(*this, TC);
David Blaikie04ea41c2012-10-12 20:00:44 +00004253 return TC;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004254 }
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004255 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4256 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4257 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4258 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004259 else if (SecondBestTC && CCCRef.WantObjCSuper &&
4260 !CCCRef.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004261 // Prefer 'super' when we're completing in a message-receiver
4262 // context.
4263
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004264 if (BestTC.getCorrection().getAsString() != "super") {
4265 if (SecondBestTC.getCorrection().getAsString() == "super")
4266 BestTC = SecondBestTC;
Kaelyn Takata9e2931e2014-06-11 18:07:03 +00004267 else if (Consumer["super"].front().isKeyword())
4268 BestTC = Consumer["super"].front();
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004269 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004270 // Don't correct to a keyword that's the same as the typo; the keyword
4271 // wasn't actually in scope.
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004272 if (BestTC.getEditDistance() == 0 ||
4273 BestTC.getCorrection().getAsString() != "super")
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004274 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004275
Douglas Gregor87074f12010-10-20 01:32:02 +00004276 // Record the correction for unqualified lookup.
4277 if (IsUnqualifiedLookup)
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004278 UnqualifiedTyposCorrected[Typo] = BestTC;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004279
Kaelyn Takata68fdd592014-06-11 18:07:01 +00004280 BestTC.setCorrectionRange(SS, TypoName);
4281 return BestTC;
Douglas Gregoraf9eb592010-10-15 13:35:25 +00004282 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004283
Kaelyn Takata73429fd2014-06-10 21:03:49 +00004284 // Record the failure's location if needed and return an empty correction. If
4285 // this was an unqualified lookup and we believe the callback object did not
4286 // filter out possible corrections, also cache the failure for the typo.
4287 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4288 IsUnqualifiedLookup && !ValidatingCallback);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004289}
4290
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004291void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4292 if (!CDecl) return;
4293
4294 if (isKeyword())
4295 CorrectionDecls.clear();
4296
Kaelyn Uhrainf60b55a2012-11-19 18:49:53 +00004297 CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004298
4299 if (!CorrectionName)
4300 CorrectionName = CDecl->getDeclName();
4301}
4302
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004303std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4304 if (CorrectionNameSpec) {
4305 std::string tmpBuffer;
4306 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4307 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikied4da8722013-05-14 21:04:00 +00004308 PrefixOStream << CorrectionName;
Benjamin Kramer73faad62012-04-14 08:26:28 +00004309 return PrefixOStream.str();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004310 }
4311
4312 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00004313}
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004314
4315bool CorrectionCandidateCallback::ValidateCandidate(const TypoCorrection &candidate) {
4316 if (!candidate.isResolved())
4317 return true;
4318
4319 if (candidate.isKeyword())
4320 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4321 WantRemainingKeywords || WantObjCSuper;
4322
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004323 bool HasNonType = false;
4324 bool HasStaticMethod = false;
4325 bool HasNonStaticMethod = false;
4326 for (Decl *D : candidate) {
4327 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
4328 D = FTD->getTemplatedDecl();
4329 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4330 if (Method->isStatic())
4331 HasStaticMethod = true;
4332 else
4333 HasNonStaticMethod = true;
4334 }
4335 if (!isa<TypeDecl>(D))
4336 HasNonType = true;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004337 }
4338
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00004339 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
4340 !candidate.getCorrectionSpecifier())
4341 return false;
4342
4343 return WantTypeSpecifiers || HasNonType;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004344}
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004345
4346FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004347 bool HasExplicitTemplateArgs,
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004348 MemberExpr *ME)
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004349 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004350 CurContext(SemaRef.CurContext), MemberFn(ME) {
Kaelyn Takatab04846b2014-07-28 18:14:02 +00004351 WantTypeSpecifiers = false;
4352 WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus && NumArgs == 1;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004353 WantRemainingKeywords = false;
4354}
4355
4356bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4357 if (!candidate.getCorrectionDecl())
4358 return candidate.isKeyword();
4359
Aaron Ballman1e606f42014-07-15 22:03:49 +00004360 for (auto *C : candidate) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004361 FunctionDecl *FD = nullptr;
Aaron Ballman1e606f42014-07-15 22:03:49 +00004362 NamedDecl *ND = C->getUnderlyingDecl();
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004363 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4364 FD = FTD->getTemplatedDecl();
4365 if (!HasExplicitTemplateArgs && !FD) {
4366 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4367 // If the Decl is neither a function nor a template function,
4368 // determine if it is a pointer or reference to a function. If so,
4369 // check against the number of arguments expected for the pointee.
4370 QualType ValType = cast<ValueDecl>(ND)->getType();
4371 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4372 ValType = ValType->getPointeeType();
4373 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
Alp Toker9cacbab2014-01-20 20:26:09 +00004374 if (FPT->getNumParams() == NumArgs)
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004375 return true;
4376 }
4377 }
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004378
4379 // Skip the current candidate if it is not a FunctionDecl or does not accept
4380 // the current number of arguments.
4381 if (!FD || !(FD->getNumParams() >= NumArgs &&
4382 FD->getMinRequiredArguments() <= NumArgs))
4383 continue;
4384
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004385 // If the current candidate is a non-static C++ method, skip the candidate
4386 // unless the method being corrected--or the current DeclContext, if the
4387 // function being corrected is not a method--is a method in the same class
4388 // or a descendent class of the candidate's parent class.
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004389 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004390 if (MemberFn || !MD->isStatic()) {
4391 CXXMethodDecl *CurMD =
4392 MemberFn
4393 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
4394 : dyn_cast_or_null<CXXMethodDecl>(CurContext);
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004395 CXXRecordDecl *CurRD =
Craig Topperc3ec1492014-05-26 06:22:03 +00004396 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004397 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
4398 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
4399 continue;
4400 }
4401 }
4402 return true;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004403 }
4404 return false;
4405}
Richard Smithf9b15102013-08-17 00:46:16 +00004406
4407void Sema::diagnoseTypo(const TypoCorrection &Correction,
4408 const PartialDiagnostic &TypoDiag,
4409 bool ErrorRecovery) {
4410 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
4411 ErrorRecovery);
4412}
4413
Richard Smithe156254d2013-08-20 20:35:18 +00004414/// Find which declaration we should import to provide the definition of
4415/// the given declaration.
4416static const NamedDecl *getDefinitionToImport(const NamedDecl *D) {
4417 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4418 return VD->getDefinition();
4419 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +00004420 return FD->isDefined(FD) ? FD : nullptr;
Richard Smithe156254d2013-08-20 20:35:18 +00004421 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
4422 return TD->getDefinition();
4423 if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
4424 return ID->getDefinition();
4425 if (const ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
4426 return PD->getDefinition();
4427 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
4428 return getDefinitionToImport(TD->getTemplatedDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004429 return nullptr;
Richard Smithe156254d2013-08-20 20:35:18 +00004430}
4431
Richard Smithf9b15102013-08-17 00:46:16 +00004432/// \brief Diagnose a successfully-corrected typo. Separated from the correction
4433/// itself to allow external validation of the result, etc.
4434///
4435/// \param Correction The result of performing typo correction.
4436/// \param TypoDiag The diagnostic to produce. This will have the corrected
4437/// string added to it (and usually also a fixit).
4438/// \param PrevNote A note to use when indicating the location of the entity to
4439/// which we are correcting. Will have the correction string added to it.
4440/// \param ErrorRecovery If \c true (the default), the caller is going to
4441/// recover from the typo as if the corrected string had been typed.
4442/// In this case, \c PDiag must be an error, and we will attach a fixit
4443/// to it.
4444void Sema::diagnoseTypo(const TypoCorrection &Correction,
4445 const PartialDiagnostic &TypoDiag,
4446 const PartialDiagnostic &PrevNote,
4447 bool ErrorRecovery) {
4448 std::string CorrectedStr = Correction.getAsString(getLangOpts());
4449 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
4450 FixItHint FixTypo = FixItHint::CreateReplacement(
4451 Correction.getCorrectionRange(), CorrectedStr);
4452
Richard Smithe156254d2013-08-20 20:35:18 +00004453 // Maybe we're just missing a module import.
4454 if (Correction.requiresImport()) {
4455 NamedDecl *Decl = Correction.getCorrectionDecl();
4456 assert(Decl && "import required but no declaration to import");
4457
4458 // Suggest importing a module providing the definition of this entity, if
4459 // possible.
4460 const NamedDecl *Def = getDefinitionToImport(Decl);
4461 if (!Def)
4462 Def = Decl;
4463 Module *Owner = Def->getOwningModule();
4464 assert(Owner && "definition of hidden declaration is not in a module");
4465
4466 Diag(Correction.getCorrectionRange().getBegin(),
4467 diag::err_module_private_declaration)
4468 << Def << Owner->getFullModuleName();
4469 Diag(Def->getLocation(), diag::note_previous_declaration);
4470
4471 // Recover by implicitly importing this module.
Richard Smith3d23c422014-05-07 02:25:43 +00004472 if (ErrorRecovery)
4473 createImplicitModuleImportForErrorRecovery(
4474 Correction.getCorrectionRange().getBegin(), Owner);
Richard Smithe156254d2013-08-20 20:35:18 +00004475 return;
4476 }
4477
Richard Smithf9b15102013-08-17 00:46:16 +00004478 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
4479 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
4480
4481 NamedDecl *ChosenDecl =
Craig Topperc3ec1492014-05-26 06:22:03 +00004482 Correction.isKeyword() ? nullptr : Correction.getCorrectionDecl();
Richard Smithf9b15102013-08-17 00:46:16 +00004483 if (PrevNote.getDiagID() && ChosenDecl)
4484 Diag(ChosenDecl->getLocation(), PrevNote)
4485 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
4486}