blob: 42c9acbdd80d7f72de704096c5077ff2a032bab1 [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"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Sema/DeclSpec.h"
27#include "clang/Sema/ExternalSemaSource.h"
28#include "clang/Sema/Overload.h"
29#include "clang/Sema/Scope.h"
30#include "clang/Sema/ScopeInfo.h"
31#include "clang/Sema/Sema.h"
32#include "clang/Sema/SemaInternal.h"
33#include "clang/Sema/TemplateDeduction.h"
34#include "clang/Sema/TypoCorrection.h"
Douglas Gregor34074322009-01-14 22:20:51 +000035#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000036#include "llvm/ADT/SetVector.h"
Douglas Gregore254f902009-02-04 00:32:51 +000037#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0afa7f62010-10-14 20:34:08 +000038#include "llvm/ADT/StringMap.h"
Chris Lattner83cfc7c2011-07-18 01:54:02 +000039#include "llvm/ADT/TinyPtrVector.h"
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +000040#include "llvm/ADT/edit_distance.h"
John McCall6538c932009-10-10 05:48:19 +000041#include "llvm/Support/ErrorHandling.h"
Nick Lewycky13668f22012-04-03 20:26:45 +000042#include <algorithm>
43#include <iterator>
Douglas Gregor0afa7f62010-10-14 20:34:08 +000044#include <limits>
Douglas Gregor2d435302009-12-30 17:04:44 +000045#include <list>
Douglas Gregorc2fa1692011-06-28 16:20:02 +000046#include <map>
Nick Lewycky13668f22012-04-03 20:26:45 +000047#include <set>
48#include <utility>
49#include <vector>
Douglas Gregor34074322009-01-14 22:20:51 +000050
51using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000052using namespace sema;
Douglas Gregor34074322009-01-14 22:20:51 +000053
John McCallf6c8a4e2009-11-10 07:01:13 +000054namespace {
55 class UnqualUsingEntry {
56 const DeclContext *Nominated;
57 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000058
John McCallf6c8a4e2009-11-10 07:01:13 +000059 public:
60 UnqualUsingEntry(const DeclContext *Nominated,
61 const DeclContext *CommonAncestor)
62 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
63 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000064
John McCallf6c8a4e2009-11-10 07:01:13 +000065 const DeclContext *getCommonAncestor() const {
66 return CommonAncestor;
67 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000068
John McCallf6c8a4e2009-11-10 07:01:13 +000069 const DeclContext *getNominatedNamespace() const {
70 return Nominated;
71 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000072
John McCallf6c8a4e2009-11-10 07:01:13 +000073 // Sort by the pointer value of the common ancestor.
74 struct Comparator {
75 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
76 return L.getCommonAncestor() < R.getCommonAncestor();
77 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000078
John McCallf6c8a4e2009-11-10 07:01:13 +000079 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
80 return E.getCommonAncestor() < DC;
81 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000082
John McCallf6c8a4e2009-11-10 07:01:13 +000083 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
84 return DC < E.getCommonAncestor();
85 }
86 };
87 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000088
John McCallf6c8a4e2009-11-10 07:01:13 +000089 /// A collection of using directives, as used by C++ unqualified
90 /// lookup.
91 class UnqualUsingDirectiveSet {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000092 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000093
John McCallf6c8a4e2009-11-10 07:01:13 +000094 ListTy list;
95 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000096
John McCallf6c8a4e2009-11-10 07:01:13 +000097 public:
98 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +000099
John McCallf6c8a4e2009-11-10 07:01:13 +0000100 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000101 // C++ [namespace.udir]p1:
John McCallf6c8a4e2009-11-10 07:01:13 +0000102 // During unqualified name lookup, the names appear as if they
103 // were declared in the nearest enclosing namespace which contains
104 // both the using-directive and the nominated namespace.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000105 DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
John McCallf6c8a4e2009-11-10 07:01:13 +0000106 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +0000107
John McCallf6c8a4e2009-11-10 07:01:13 +0000108 for (; S; S = S->getParent()) {
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000109 // C++ [namespace.udir]p1:
110 // A using-directive shall not appear in class scope, but may
111 // appear in namespace scope or in block scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +0000112 DeclContext *Ctx = S->getEntity();
Nick Lewycky2bd636f2012-03-13 04:12:34 +0000113 if (Ctx && Ctx->isFileContext()) {
114 visit(Ctx, Ctx);
115 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
Aaron Ballman5df6aa42014-03-17 17:03:37 +0000116 for (auto *I : S->using_directives())
117 visit(I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000118 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000119 }
120 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000121
122 // Visits a context and collect all of its using directives
123 // recursively. Treats all using directives as if they were
124 // declared in the context.
125 //
126 // A given context is only every visited once, so it is important
127 // that contexts be visited from the inside out in order to get
128 // the effective DCs right.
129 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
130 if (!visited.insert(DC))
131 return;
132
133 addUsingDirectives(DC, EffectiveDC);
134 }
135
136 // Visits a using directive and collects all of its using
137 // directives recursively. Treats all using directives as if they
138 // were declared in the effective DC.
139 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
140 DeclContext *NS = UD->getNominatedNamespace();
141 if (!visited.insert(NS))
142 return;
143
144 addUsingDirective(UD, EffectiveDC);
145 addUsingDirectives(NS, EffectiveDC);
146 }
147
148 // Adds all the using directives in a context (and those nominated
149 // by its using directives, transitively) as if they appeared in
150 // the given effective context.
151 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000152 SmallVector<DeclContext*,4> queue;
John McCallf6c8a4e2009-11-10 07:01:13 +0000153 while (true) {
Aaron Ballman804a7fb2014-03-17 17:14:12 +0000154 for (auto UD : DC->using_directives()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000155 DeclContext *NS = UD->getNominatedNamespace();
156 if (visited.insert(NS)) {
157 addUsingDirective(UD, EffectiveDC);
158 queue.push_back(NS);
159 }
160 }
161
162 if (queue.empty())
163 return;
164
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000165 DC = queue.pop_back_val();
John McCallf6c8a4e2009-11-10 07:01:13 +0000166 }
167 }
168
169 // Add a using directive as if it had been declared in the given
170 // context. This helps implement C++ [namespace.udir]p3:
171 // The using-directive is transitive: if a scope contains a
172 // using-directive that nominates a second namespace that itself
173 // contains using-directives, the effect is as if the
174 // using-directives from the second namespace also appeared in
175 // the first.
176 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
177 // Find the common ancestor between the effective context and
178 // the nominated namespace.
179 DeclContext *Common = UD->getNominatedNamespace();
180 while (!Common->Encloses(EffectiveDC))
181 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000182 Common = Common->getPrimaryContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000183
John McCallf6c8a4e2009-11-10 07:01:13 +0000184 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
185 }
186
187 void done() {
188 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
189 }
190
John McCallf6c8a4e2009-11-10 07:01:13 +0000191 typedef ListTy::const_iterator const_iterator;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000192
John McCallf6c8a4e2009-11-10 07:01:13 +0000193 const_iterator begin() const { return list.begin(); }
194 const_iterator end() const { return list.end(); }
195
196 std::pair<const_iterator,const_iterator>
197 getNamespacesFor(DeclContext *DC) const {
John McCall9757d032009-11-10 09:20:04 +0000198 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCallf6c8a4e2009-11-10 07:01:13 +0000199 UnqualUsingEntry::Comparator());
200 }
201 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000202}
203
Douglas Gregor889ceb72009-02-03 19:21:40 +0000204// Retrieve the set of identifier namespaces that correspond to a
205// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000206static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
207 bool CPlusPlus,
208 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000209 unsigned IDNS = 0;
210 switch (NameKind) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +0000211 case Sema::LookupObjCImplicitSelfParam:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000212 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000213 case Sema::LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +0000214 case Sema::LookupLocalFriendName:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000215 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000216 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000217 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000218 if (Redeclaration)
219 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
John McCallea305ed2009-12-18 10:40:03 +0000220 }
Richard Smith541b38b2013-09-20 01:15:31 +0000221 if (Redeclaration)
222 IDNS |= Decl::IDNS_LocalExtern;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000223 break;
224
John McCallb9467b62010-04-24 01:30:58 +0000225 case Sema::LookupOperatorName:
226 // Operator lookup is its own crazy thing; it is not the same
227 // as (e.g.) looking up an operator name for redeclaration.
228 assert(!Redeclaration && "cannot do redeclaration operator lookup");
229 IDNS = Decl::IDNS_NonMemberOperator;
230 break;
231
Douglas Gregor889ceb72009-02-03 19:21:40 +0000232 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000233 if (CPlusPlus) {
234 IDNS = Decl::IDNS_Type;
235
236 // When looking for a redeclaration of a tag name, we add:
237 // 1) TagFriend to find undeclared friend decls
238 // 2) Namespace because they can't "overload" with tag decls.
239 // 3) Tag because it includes class templates, which can't
240 // "overload" with tag decls.
241 if (Redeclaration)
242 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
243 } else {
244 IDNS = Decl::IDNS_Tag;
245 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000246 break;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000247 case Sema::LookupLabel:
248 IDNS = Decl::IDNS_Label;
249 break;
250
Douglas Gregor889ceb72009-02-03 19:21:40 +0000251 case Sema::LookupMemberName:
252 IDNS = Decl::IDNS_Member;
253 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000254 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000255 break;
256
257 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000258 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
259 break;
260
Douglas Gregor889ceb72009-02-03 19:21:40 +0000261 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000262 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000263 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000264
John McCall84d87672009-12-10 09:41:52 +0000265 case Sema::LookupUsingDeclName:
266 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
267 | Decl::IDNS_Member | Decl::IDNS_Using;
268 break;
269
Douglas Gregor79947a22009-04-24 00:11:27 +0000270 case Sema::LookupObjCProtocolName:
271 IDNS = Decl::IDNS_ObjCProtocol;
272 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000273
Douglas Gregor39982192010-08-15 06:18:01 +0000274 case Sema::LookupAnyName:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000275 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor39982192010-08-15 06:18:01 +0000276 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
277 | Decl::IDNS_Type;
278 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000279 }
280 return IDNS;
281}
282
John McCallea305ed2009-12-18 10:40:03 +0000283void LookupResult::configure() {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000284 IDNS = getIDNS(LookupKind, SemaRef.getLangOpts().CPlusPlus,
John McCallea305ed2009-12-18 10:40:03 +0000285 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000286
Richard Smithbdd14642014-02-04 01:14:30 +0000287 // If we're looking for one of the allocation or deallocation
288 // operators, make sure that the implicitly-declared new and delete
289 // operators can be found.
290 switch (NameInfo.getName().getCXXOverloadedOperator()) {
291 case OO_New:
292 case OO_Delete:
293 case OO_Array_New:
294 case OO_Array_Delete:
295 SemaRef.DeclareGlobalNewDelete();
296 break;
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000297
Richard Smithbdd14642014-02-04 01:14:30 +0000298 default:
299 break;
300 }
Douglas Gregor15197662013-04-03 23:06:26 +0000301
Richard Smithbdd14642014-02-04 01:14:30 +0000302 // Compiler builtins are always visible, regardless of where they end
303 // up being declared.
304 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
305 if (unsigned BuiltinID = Id->getBuiltinID()) {
306 if (!SemaRef.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
307 AllowHidden = true;
Douglas Gregor15197662013-04-03 23:06:26 +0000308 }
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000309 }
John McCallea305ed2009-12-18 10:40:03 +0000310}
311
Alp Tokerc1086762013-12-07 13:51:35 +0000312bool LookupResult::sanity() const {
Daniel Dunbar9e19f132012-03-08 01:43:06 +0000313 // Note that this function is never called by NDEBUG builds. See
314 // LookupResult::sanity().
John McCall19c1bfd2010-08-25 05:32:35 +0000315 assert(ResultKind != NotFound || Decls.size() == 0);
316 assert(ResultKind != Found || Decls.size() == 1);
317 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
318 (Decls.size() == 1 &&
319 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
320 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
321 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000322 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
323 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall19c1bfd2010-08-25 05:32:35 +0000324 assert((Paths != NULL) == (ResultKind == Ambiguous &&
325 (Ambiguity == AmbiguousBaseSubobjectTypes ||
326 Ambiguity == AmbiguousBaseSubobjects)));
Alp Tokerc1086762013-12-07 13:51:35 +0000327 return true;
John McCall19c1bfd2010-08-25 05:32:35 +0000328}
John McCall19c1bfd2010-08-25 05:32:35 +0000329
John McCall9f3059a2009-10-09 21:13:30 +0000330// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000331void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000332 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000333}
334
Richard Smith3876cc82013-10-30 01:02:04 +0000335/// Get a representative context for a declaration such that two declarations
336/// will have the same context if they were found within the same scope.
Benjamin Kramerfc58b042013-11-01 11:50:55 +0000337static DeclContext *getContextForScopeMatching(Decl *D) {
Richard Smith3876cc82013-10-30 01:02:04 +0000338 // For function-local declarations, use that function as the context. This
339 // doesn't account for scopes within the function; the caller must deal with
340 // those.
341 DeclContext *DC = D->getLexicalDeclContext();
342 if (DC->isFunctionOrMethod())
343 return DC;
344
345 // Otherwise, look at the semantic context of the declaration. The
346 // declaration must have been found there.
347 return D->getDeclContext()->getRedeclContext();
348}
349
John McCall283b9012009-11-22 00:44:51 +0000350/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000351void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000352 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000353
John McCall9f3059a2009-10-09 21:13:30 +0000354 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000355 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000356 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000357 return;
358 }
359
John McCall283b9012009-11-22 00:44:51 +0000360 // If there's a single decl, we need to examine it to decide what
361 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000362 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000363 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
364 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000365 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000366 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000367 ResultKind = FoundUnresolvedValue;
368 return;
369 }
John McCall9f3059a2009-10-09 21:13:30 +0000370
John McCall6538c932009-10-10 05:48:19 +0000371 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000372 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000373
John McCall9f3059a2009-10-09 21:13:30 +0000374 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor13e65872010-08-11 14:45:53 +0000375 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000376
John McCall9f3059a2009-10-09 21:13:30 +0000377 bool Ambiguous = false;
378 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000379 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000380
381 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000382
John McCall9f3059a2009-10-09 21:13:30 +0000383 unsigned I = 0;
384 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000385 NamedDecl *D = Decls[I]->getUnderlyingDecl();
386 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000387
Argyrios Kyrtzidis1fcd7fd2013-02-22 06:58:37 +0000388 // Ignore an invalid declaration unless it's the only one left.
389 if (D->isInvalidDecl() && I < N-1) {
390 Decls[I] = Decls[--N];
391 continue;
392 }
393
Douglas Gregor13e65872010-08-11 14:45:53 +0000394 // Redeclarations of types via typedef can occur both within a scope
395 // and, through using declarations and directives, across scopes. There is
396 // no ambiguity if they all refer to the same type, so unique based on the
397 // canonical type.
398 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
399 if (!TD->getDeclContext()->isRecord()) {
400 QualType T = SemaRef.Context.getTypeDeclType(TD);
401 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
402 // The type is not unique; pull something off the back and continue
403 // at this index.
404 Decls[I] = Decls[--N];
405 continue;
406 }
407 }
408 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000409
John McCallf0f1cf02009-11-17 07:50:12 +0000410 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000411 // If it's not unique, pull something off the back (and
412 // continue at this index).
413 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000414 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000415 }
416
Douglas Gregor13e65872010-08-11 14:45:53 +0000417 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000418
Douglas Gregor13e65872010-08-11 14:45:53 +0000419 if (isa<UnresolvedUsingValueDecl>(D)) {
420 HasUnresolved = true;
421 } else if (isa<TagDecl>(D)) {
422 if (HasTag)
423 Ambiguous = true;
424 UniqueTagIndex = I;
425 HasTag = true;
426 } else if (isa<FunctionTemplateDecl>(D)) {
427 HasFunction = true;
428 HasFunctionTemplate = true;
429 } else if (isa<FunctionDecl>(D)) {
430 HasFunction = true;
431 } else {
432 if (HasNonFunction)
433 Ambiguous = true;
434 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000435 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000436 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000437 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000438
John McCall9f3059a2009-10-09 21:13:30 +0000439 // C++ [basic.scope.hiding]p2:
440 // A class name or enumeration name can be hidden by the name of
441 // an object, function, or enumerator declared in the same
442 // scope. If a class or enumeration name and an object, function,
443 // or enumerator are declared in the same scope (in any order)
444 // with the same name, the class or enumeration name is hidden
445 // wherever the object, function, or enumerator name is visible.
446 // But it's still an error if there are distinct tag types found,
447 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000448 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000449 (HasFunction || HasNonFunction || HasUnresolved)) {
Richard Smith3876cc82013-10-30 01:02:04 +0000450 if (getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
451 getContextForScopeMatching(Decls[UniqueTagIndex ? 0 : N - 1])))
Douglas Gregore63d0872010-10-23 16:06:17 +0000452 Decls[UniqueTagIndex] = Decls[--N];
453 else
454 Ambiguous = true;
455 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000456
John McCall9f3059a2009-10-09 21:13:30 +0000457 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000458
John McCall80053822009-12-03 00:58:24 +0000459 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000460 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000461
John McCall9f3059a2009-10-09 21:13:30 +0000462 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000463 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000464 else if (HasUnresolved)
465 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000466 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000467 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000468 else
John McCall27b18f82009-11-17 02:14:36 +0000469 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000470}
471
John McCall5cebab12009-11-18 07:57:50 +0000472void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000473 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000474 for (I = P.begin(), E = P.end(); I != E; ++I)
David Blaikieff7d47a2012-12-19 00:45:41 +0000475 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
476 DE = I->Decls.end(); DI != DE; ++DI)
John McCall9f3059a2009-10-09 21:13:30 +0000477 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000478}
479
John McCall5cebab12009-11-18 07:57:50 +0000480void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000481 Paths = new CXXBasePaths;
482 Paths->swap(P);
483 addDeclsFromBasePaths(*Paths);
484 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000485 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000486}
487
John McCall5cebab12009-11-18 07:57:50 +0000488void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000489 Paths = new CXXBasePaths;
490 Paths->swap(P);
491 addDeclsFromBasePaths(*Paths);
492 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000493 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000494}
495
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000496void LookupResult::print(raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000497 Out << Decls.size() << " result(s)";
498 if (isAmbiguous()) Out << ", ambiguous";
499 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000500
John McCall9f3059a2009-10-09 21:13:30 +0000501 for (iterator I = begin(), E = end(); I != E; ++I) {
502 Out << "\n";
503 (*I)->print(Out, 2);
504 }
505}
506
Douglas Gregord3a59182010-02-12 05:48:04 +0000507/// \brief Lookup a builtin function, when name lookup would otherwise
508/// fail.
509static bool LookupBuiltin(Sema &S, LookupResult &R) {
510 Sema::LookupNameKind NameKind = R.getLookupKind();
511
512 // If we didn't find a use of this identifier, and if the identifier
513 // corresponds to a compiler builtin, create the decl object for the builtin
514 // now, injecting it into translation unit scope, and return it.
515 if (NameKind == Sema::LookupOrdinaryName ||
516 NameKind == Sema::LookupRedeclarationWithLinkage) {
517 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
518 if (II) {
Nico Webere1687c52013-06-20 21:44:55 +0000519 if (S.getLangOpts().CPlusPlus11 && S.getLangOpts().GNUMode &&
520 II == S.getFloat128Identifier()) {
521 // libstdc++4.7's type_traits expects type __float128 to exist, so
522 // insert a dummy type to make that header build in gnu++11 mode.
523 R.addDecl(S.getASTContext().getFloat128StubType());
524 return true;
525 }
526
Douglas Gregord3a59182010-02-12 05:48:04 +0000527 // If this is a builtin on this (or all) targets, create the decl.
528 if (unsigned BuiltinID = II->getBuiltinID()) {
529 // In C++, we don't have any predefined library functions like
530 // 'malloc'. Instead, we'll just error.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000531 if (S.getLangOpts().CPlusPlus &&
Douglas Gregord3a59182010-02-12 05:48:04 +0000532 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
533 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000534
535 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
536 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000537 R.isForRedeclaration(),
538 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000539 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000540 return true;
541 }
Douglas Gregord3a59182010-02-12 05:48:04 +0000542 }
543 }
544 }
545
546 return false;
547}
548
Douglas Gregor7454c562010-07-02 20:37:36 +0000549/// \brief Determine whether we can declare a special member function within
550/// the class at this point.
Richard Smith7d125a12012-11-27 21:20:31 +0000551static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +0000552 // We need to have a definition for the class.
553 if (!Class->getDefinition() || Class->isDependentContext())
554 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000555
Douglas Gregor7454c562010-07-02 20:37:36 +0000556 // We can't be in the middle of defining the class.
Richard Smith7d125a12012-11-27 21:20:31 +0000557 return !Class->isBeingDefined();
Douglas Gregor7454c562010-07-02 20:37:36 +0000558}
559
560void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smith7d125a12012-11-27 21:20:31 +0000561 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregora6d69502010-07-02 23:41:54 +0000562 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000563
564 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000565 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000566 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000567
Douglas Gregora6d69502010-07-02 23:41:54 +0000568 // If the copy constructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000569 if (Class->needsImplicitCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +0000570 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000571
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000572 // If the copy assignment operator has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000573 if (Class->needsImplicitCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000574 DeclareImplicitCopyAssignment(Class);
575
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000576 if (getLangOpts().CPlusPlus11) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000577 // If the move constructor has not yet been declared, do so now.
578 if (Class->needsImplicitMoveConstructor())
579 DeclareImplicitMoveConstructor(Class); // might not actually do it
580
581 // If the move assignment operator has not yet been declared, do so now.
582 if (Class->needsImplicitMoveAssignment())
583 DeclareImplicitMoveAssignment(Class); // might not actually do it
584 }
585
Douglas Gregor7454c562010-07-02 20:37:36 +0000586 // If the destructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000587 if (Class->needsImplicitDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000588 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000589}
590
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000591/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000592/// special member function.
593static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
594 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000595 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000596 case DeclarationName::CXXDestructorName:
597 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000598
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000599 case DeclarationName::CXXOperatorName:
600 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000601
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000602 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000603 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000604 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000605
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000606 return false;
607}
608
609/// \brief If there are any implicit member functions with the given name
610/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000611static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000612 DeclarationName Name,
613 const DeclContext *DC) {
614 if (!DC)
615 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000616
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000617 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000618 case DeclarationName::CXXConstructorName:
619 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith7d125a12012-11-27 21:20:31 +0000620 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000621 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000622 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000623 S.DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +0000624 if (Record->needsImplicitCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000625 S.DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000626 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000627 Record->needsImplicitMoveConstructor())
628 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000629 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000630 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000631
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000632 case DeclarationName::CXXDestructorName:
633 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith2be35f52012-12-01 02:35:44 +0000634 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smith7d125a12012-11-27 21:20:31 +0000635 CanDeclareSpecialMemberFunction(Record))
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000636 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000637 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000638
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000639 case DeclarationName::CXXOperatorName:
640 if (Name.getCXXOverloadedOperator() != OO_Equal)
641 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000642
Sebastian Redl22653ba2011-08-30 19:58:05 +0000643 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smith7d125a12012-11-27 21:20:31 +0000644 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000645 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smith2be35f52012-12-01 02:35:44 +0000646 if (Record->needsImplicitCopyAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000647 S.DeclareImplicitCopyAssignment(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000648 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000649 Record->needsImplicitMoveAssignment())
650 S.DeclareImplicitMoveAssignment(Class);
651 }
652 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000653 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000654
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000655 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000656 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000657 }
658}
Douglas Gregor7454c562010-07-02 20:37:36 +0000659
John McCall9f3059a2009-10-09 21:13:30 +0000660// Adds all qualifying matches for a name within a decl context to the
661// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000662static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000663 bool Found = false;
664
Douglas Gregor7454c562010-07-02 20:37:36 +0000665 // Lazily declare C++ special member functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000666 if (S.getLangOpts().CPlusPlus)
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000667 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000668
Douglas Gregor7454c562010-07-02 20:37:36 +0000669 // Perform lookup into this declaration context.
David Blaikieff7d47a2012-12-19 00:45:41 +0000670 DeclContext::lookup_const_result DR = DC->lookup(R.getLookupName());
671 for (DeclContext::lookup_const_iterator I = DR.begin(), E = DR.end(); I != E;
672 ++I) {
John McCall401982f2010-01-20 21:53:11 +0000673 NamedDecl *D = *I;
Douglas Gregor4a814562011-12-14 16:03:29 +0000674 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000675 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000676 Found = true;
677 }
678 }
John McCall9f3059a2009-10-09 21:13:30 +0000679
Douglas Gregord3a59182010-02-12 05:48:04 +0000680 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
681 return true;
682
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000683 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000684 != DeclarationName::CXXConversionFunctionName ||
685 R.getLookupName().getCXXNameType()->isDependentType() ||
686 !isa<CXXRecordDecl>(DC))
687 return Found;
688
689 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000690 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000691 // name lookup. Instead, any conversion function templates visible in the
692 // context of the use are considered. [...]
693 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000694 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000695 return Found;
696
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +0000697 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
698 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruth3a693b72010-01-31 11:44:02 +0000699 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
700 if (!ConvTemplate)
701 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000702
Chandler Carruth3a693b72010-01-31 11:44:02 +0000703 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000704 // add the conversion function template. When we deduce template
705 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000706 // type of the new declaration with the type of the function template.
707 if (R.isForRedeclaration()) {
708 R.addDecl(ConvTemplate);
709 Found = true;
710 continue;
711 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000712
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000713 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000714 // [...] For each such operator, if argument deduction succeeds
715 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000716 // name lookup.
717 //
718 // When referencing a conversion function for any purpose other than
719 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000720 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000721 // specialization into the result set. We do this to avoid forcing all
722 // callers to perform special deduction for conversion functions.
Craig Toppere6706e42012-09-19 02:26:47 +0000723 TemplateDeductionInfo Info(R.getNameLoc());
Chandler Carruth3a693b72010-01-31 11:44:02 +0000724 FunctionDecl *Specialization = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000725
726 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000727 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
728 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000729
Chandler Carruth3a693b72010-01-31 11:44:02 +0000730 // Compute the type of the function that we would expect the conversion
731 // function to have, if it were to match the name given.
732 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000733 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
Reid Kleckner78af0702013-08-27 23:08:25 +0000734 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
Sebastian Redl7c6c9e92011-03-06 10:52:04 +0000735 EPI.ExceptionSpecType = EST_None;
John McCalldb40c7f2010-12-14 08:05:40 +0000736 EPI.NumExceptions = 0;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000737 QualType ExpectedType
738 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000739 None, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000740
Chandler Carruth3a693b72010-01-31 11:44:02 +0000741 // Perform template argument deduction against the type that we would
742 // expect the function to have.
743 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
744 Specialization, Info)
745 == Sema::TDK_Success) {
746 R.addDecl(Specialization);
747 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000748 }
749 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000750
John McCall9f3059a2009-10-09 21:13:30 +0000751 return Found;
752}
753
John McCallf6c8a4e2009-11-10 07:01:13 +0000754// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000755static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000756CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000757 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000758
759 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
760
John McCallf6c8a4e2009-11-10 07:01:13 +0000761 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000762 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000763
John McCallf6c8a4e2009-11-10 07:01:13 +0000764 // Perform direct name lookup into the namespaces nominated by the
765 // using directives whose common ancestor is this namespace.
766 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000767 std::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000768
John McCallf6c8a4e2009-11-10 07:01:13 +0000769 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000770 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000771 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000772
773 R.resolveKind();
774
775 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000776}
777
778static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000779 if (DeclContext *Ctx = S->getEntity())
Douglas Gregor700792c2009-02-05 19:25:20 +0000780 return Ctx->isFileContext();
781 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000782}
Douglas Gregored8f2882009-01-30 01:04:22 +0000783
Douglas Gregor66230062010-03-15 14:33:29 +0000784// Find the next outer declaration context from this scope. This
785// routine actually returns the semantic outer context, which may
786// differ from the lexical context (encoded directly in the Scope
787// stack) when we are parsing a member of a class template. In this
788// case, the second element of the pair will be true, to indicate that
789// name lookup should continue searching in this semantic context when
790// it leaves the current template parameter scope.
791static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000792 DeclContext *DC = S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +0000793 DeclContext *Lexical = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000794 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000795 OuterS = OuterS->getParent()) {
796 if (OuterS->getEntity()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000797 Lexical = OuterS->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +0000798 break;
799 }
800 }
801
802 // C++ [temp.local]p8:
803 // In the definition of a member of a class template that appears
804 // outside of the namespace containing the class template
805 // definition, the name of a template-parameter hides the name of
806 // a member of this namespace.
807 //
808 // Example:
809 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000810 // namespace N {
811 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000812 //
813 // template<class T> class B {
814 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000815 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000816 // }
817 //
818 // template<class C> void N::B<C>::f(C) {
819 // C b; // C is the template parameter, not N::C
820 // }
821 //
822 // In this example, the lexical context we return is the
823 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000824 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000825 !S->getParent()->isTemplateParamScope())
826 return std::make_pair(Lexical, false);
827
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000828 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000829 // For the example, this is the scope for the template parameters of
830 // template<class C>.
831 Scope *OutermostTemplateScope = S->getParent();
832 while (OutermostTemplateScope->getParent() &&
833 OutermostTemplateScope->getParent()->isTemplateParamScope())
834 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000835
Douglas Gregor66230062010-03-15 14:33:29 +0000836 // Find the namespace context in which the original scope occurs. In
837 // the example, this is namespace N.
838 DeclContext *Semantic = DC;
839 while (!Semantic->isFileContext())
840 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000841
Douglas Gregor66230062010-03-15 14:33:29 +0000842 // Find the declaration context just outside of the template
843 // parameter scope. This is the context in which the template is
844 // being lexically declaration (a namespace context). In the
845 // example, this is the global scope.
846 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
847 Lexical->Encloses(Semantic))
848 return std::make_pair(Semantic, true);
849
850 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000851}
852
Richard Smith541b38b2013-09-20 01:15:31 +0000853namespace {
854/// An RAII object to specify that we want to find block scope extern
855/// declarations.
856struct FindLocalExternScope {
857 FindLocalExternScope(LookupResult &R)
858 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
859 Decl::IDNS_LocalExtern) {
860 R.setFindLocalExtern(R.getIdentifierNamespace() & Decl::IDNS_Ordinary);
861 }
862 void restore() {
863 R.setFindLocalExtern(OldFindLocalExtern);
864 }
865 ~FindLocalExternScope() {
866 restore();
867 }
868 LookupResult &R;
869 bool OldFindLocalExtern;
870};
871}
872
John McCall27b18f82009-11-17 02:14:36 +0000873bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000874 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000875
876 DeclarationName Name = R.getLookupName();
Richard Smith1c34fb72013-08-13 18:18:50 +0000877 Sema::LookupNameKind NameKind = R.getLookupKind();
John McCall27b18f82009-11-17 02:14:36 +0000878
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000879 // If this is the name of an implicitly-declared special member function,
880 // go through the scope stack to implicitly declare
881 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
882 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +0000883 if (DeclContext *DC = PreS->getEntity())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000884 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
885 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000886
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000887 // Implicitly declare member functions with the name we're looking for, if in
888 // fact we are in a scope where it matters.
889
Douglas Gregor889ceb72009-02-03 19:21:40 +0000890 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000891 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000892 I = IdResolver.begin(Name),
893 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000894
Douglas Gregor889ceb72009-02-03 19:21:40 +0000895 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000896 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000897 // ...During unqualified name lookup (3.4.1), the names appear as if
898 // they were declared in the nearest enclosing namespace which contains
899 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000900 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000901 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000902 //
903 // For example:
904 // namespace A { int i; }
905 // void foo() {
906 // int i;
907 // {
908 // using namespace A;
909 // ++i; // finds local 'i', A::i appears at global scope
910 // }
911 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000912 //
Douglas Gregorcc9406c2013-04-08 23:11:25 +0000913 UnqualUsingDirectiveSet UDirs;
914 bool VisitedUsingDirectives = false;
Richard Smith1c34fb72013-08-13 18:18:50 +0000915 bool LeftStartingScope = false;
Douglas Gregor66230062010-03-15 14:33:29 +0000916 DeclContext *OutsideOfTemplateParamDC = 0;
Richard Smith541b38b2013-09-20 01:15:31 +0000917
918 // When performing a scope lookup, we want to find local extern decls.
919 FindLocalExternScope FindLocals(R);
920
Douglas Gregor700792c2009-02-05 19:25:20 +0000921 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000922 DeclContext *Ctx = S->getEntity();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000923
Douglas Gregor889ceb72009-02-03 19:21:40 +0000924 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000925 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000926 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000927 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Richard Smith1c34fb72013-08-13 18:18:50 +0000928 if (NameKind == LookupRedeclarationWithLinkage) {
929 // Determine whether this (or a previous) declaration is
930 // out-of-scope.
931 if (!LeftStartingScope && !Initial->isDeclScope(*I))
932 LeftStartingScope = true;
933
934 // If we found something outside of our starting scope that
Richard Smith9a00bbf2013-10-16 21:12:00 +0000935 // does not have linkage, skip it. If it's a template parameter,
936 // we still find it, so we can diagnose the invalid redeclaration.
937 if (LeftStartingScope && !((*I)->hasLinkage()) &&
938 !(*I)->isTemplateParameter()) {
Richard Smith1c34fb72013-08-13 18:18:50 +0000939 R.setShadowed();
940 continue;
941 }
942 }
943
John McCall9f3059a2009-10-09 21:13:30 +0000944 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +0000945 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000946 }
947 }
John McCall9f3059a2009-10-09 21:13:30 +0000948 if (Found) {
949 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000950 if (S->isClassScope())
951 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
952 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000953 return true;
954 }
955
Richard Smith1c34fb72013-08-13 18:18:50 +0000956 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
Richard Smith114394f2013-08-09 04:35:01 +0000957 // C++11 [class.friend]p11:
958 // If a friend declaration appears in a local class and the name
959 // specified is an unqualified name, a prior declaration is
960 // looked up without considering scopes that are outside the
961 // innermost enclosing non-class scope.
962 return false;
963 }
964
Douglas Gregor66230062010-03-15 14:33:29 +0000965 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
966 S->getParent() && !S->getParent()->isTemplateParamScope()) {
967 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000968 // found nothing, so look into the contexts between the
Douglas Gregor66230062010-03-15 14:33:29 +0000969 // lexical and semantic declaration contexts returned by
970 // findOuterContext(). This implements the name lookup behavior
971 // of C++ [temp.local]p8.
972 Ctx = OutsideOfTemplateParamDC;
973 OutsideOfTemplateParamDC = 0;
974 }
975
976 if (Ctx) {
977 DeclContext *OuterCtx;
978 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000979 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregor66230062010-03-15 14:33:29 +0000980 if (SearchAfterTemplateScope)
981 OutsideOfTemplateParamDC = OuterCtx;
982
Douglas Gregorea166062010-03-15 15:26:48 +0000983 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000984 // We do not directly look into transparent contexts, since
985 // those entities will be found in the nearest enclosing
986 // non-transparent context.
987 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000988 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000989
990 // We do not look directly into function or method contexts,
991 // since all of the local variables and parameters of the
992 // function/method are present within the Scope.
993 if (Ctx->isFunctionOrMethod()) {
994 // If we have an Objective-C instance method, look for ivars
995 // in the corresponding interface.
996 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
997 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
998 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
999 ObjCInterfaceDecl *ClassDeclared;
1000 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001001 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +00001002 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001003 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1004 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +00001005 R.resolveKind();
1006 return true;
1007 }
1008 }
1009 }
1010 }
1011
1012 continue;
1013 }
1014
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001015 // If this is a file context, we need to perform unqualified name
1016 // lookup considering using directives.
1017 if (Ctx->isFileContext()) {
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001018 // If we haven't handled using directives yet, do so now.
1019 if (!VisitedUsingDirectives) {
1020 // Add using directives from this context up to the top level.
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001021 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1022 if (UCtx->isTransparentContext())
1023 continue;
1024
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001025 UDirs.visit(UCtx, UCtx);
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001026 }
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001027
1028 // Find the innermost file scope, so we can add using directives
1029 // from local scopes.
1030 Scope *InnermostFileScope = S;
1031 while (InnermostFileScope &&
1032 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1033 InnermostFileScope = InnermostFileScope->getParent();
1034 UDirs.visitScopeChain(Initial, InnermostFileScope);
1035
1036 UDirs.done();
1037
1038 VisitedUsingDirectives = true;
1039 }
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001040
1041 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1042 R.resolveKind();
1043 return true;
1044 }
1045
1046 continue;
1047 }
1048
Douglas Gregor7f737c02009-09-10 16:57:35 +00001049 // Perform qualified name lookup into this context.
1050 // FIXME: In some cases, we know that every name that could be found by
1051 // this qualified name lookup will also be on the identifier chain. For
1052 // example, inside a class without any base classes, we never need to
1053 // perform qualified lookup because all of the members are on top of the
1054 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001055 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +00001056 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +00001057 }
Douglas Gregor700792c2009-02-05 19:25:20 +00001058 }
Douglas Gregored8f2882009-01-30 01:04:22 +00001059 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001060
John McCallf6c8a4e2009-11-10 07:01:13 +00001061 // Stop if we ran out of scopes.
1062 // FIXME: This really, really shouldn't be happening.
1063 if (!S) return false;
1064
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001065 // If we are looking for members, no need to look into global/namespace scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00001066 if (NameKind == LookupMemberName)
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001067 return false;
1068
Douglas Gregor700792c2009-02-05 19:25:20 +00001069 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +00001070 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +00001071 //
Mike Stump87c57ac2009-05-16 07:39:55 +00001072 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1073 // don't build it for each lookup!
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001074 if (!VisitedUsingDirectives) {
1075 UDirs.visitScopeChain(Initial, S);
1076 UDirs.done();
1077 }
Richard Smith541b38b2013-09-20 01:15:31 +00001078
1079 // If we're not performing redeclaration lookup, do not look for local
1080 // extern declarations outside of a function scope.
1081 if (!R.isForRedeclaration())
1082 FindLocals.restore();
1083
Douglas Gregor700792c2009-02-05 19:25:20 +00001084 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +00001085 // Unqualified name lookup in C++ requires looking into scopes
1086 // that aren't strictly lexical, and therefore we walk through the
1087 // context as well as walking through the scopes.
1088 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001089 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +00001090 bool Found = false;
John McCall48871652010-08-21 09:40:31 +00001091 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001092 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001093 // We found something. Look for anything else in our scope
1094 // with this same name and in an acceptable identifier
1095 // namespace, so that we can construct an overload set if we
1096 // need to.
John McCall9f3059a2009-10-09 21:13:30 +00001097 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +00001098 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001099 }
1100 }
1101
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001102 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +00001103 R.resolveKind();
1104 return true;
1105 }
1106
Ted Kremenekc37877d2013-10-08 17:08:03 +00001107 DeclContext *Ctx = S->getEntity();
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001108 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1109 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1110 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001111 // found nothing, so look into the contexts between the
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001112 // lexical and semantic declaration contexts returned by
1113 // findOuterContext(). This implements the name lookup behavior
1114 // of C++ [temp.local]p8.
1115 Ctx = OutsideOfTemplateParamDC;
1116 OutsideOfTemplateParamDC = 0;
1117 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001118
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001119 if (Ctx) {
1120 DeclContext *OuterCtx;
1121 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001122 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001123 if (SearchAfterTemplateScope)
1124 OutsideOfTemplateParamDC = OuterCtx;
1125
1126 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1127 // We do not directly look into transparent contexts, since
1128 // those entities will be found in the nearest enclosing
1129 // non-transparent context.
1130 if (Ctx->isTransparentContext())
1131 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001132
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001133 // If we have a context, and it's not a context stashed in the
1134 // template parameter scope for an out-of-line definition, also
1135 // look into that context.
1136 if (!(Found && S && S->isTemplateParamScope())) {
1137 assert(Ctx->isFileContext() &&
1138 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001139
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001140 // Look into context considering using-directives.
1141 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1142 Found = true;
1143 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001144
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001145 if (Found) {
1146 R.resolveKind();
1147 return true;
1148 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001149
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001150 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1151 return false;
1152 }
1153 }
1154
Douglas Gregor3ce74932010-02-05 07:07:10 +00001155 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001156 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001157 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001158
John McCall9f3059a2009-10-09 21:13:30 +00001159 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001160}
1161
Richard Smith0e5d7b82013-07-25 23:08:39 +00001162/// \brief Find the declaration that a class temploid member specialization was
1163/// instantiated from, or the member itself if it is an explicit specialization.
1164static Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) {
1165 return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom();
1166}
1167
1168/// \brief Find the module in which the given declaration was defined.
1169static Module *getDefiningModule(Decl *Entity) {
1170 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1171 // If this function was instantiated from a template, the defining module is
1172 // the module containing the pattern.
1173 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1174 Entity = Pattern;
1175 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
1176 // If it's a class template specialization, find the template or partial
1177 // specialization from which it was instantiated.
1178 if (ClassTemplateSpecializationDecl *SpecRD =
1179 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
1180 llvm::PointerUnion<ClassTemplateDecl*,
1181 ClassTemplatePartialSpecializationDecl*> From =
1182 SpecRD->getInstantiatedFrom();
1183 if (ClassTemplateDecl *FromTemplate = From.dyn_cast<ClassTemplateDecl*>())
1184 Entity = FromTemplate->getTemplatedDecl();
1185 else if (From)
1186 Entity = From.get<ClassTemplatePartialSpecializationDecl*>();
1187 // Otherwise, it's an explicit specialization.
1188 } else if (MemberSpecializationInfo *MSInfo =
1189 RD->getMemberSpecializationInfo())
1190 Entity = getInstantiatedFrom(RD, MSInfo);
1191 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1192 if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo())
1193 Entity = getInstantiatedFrom(ED, MSInfo);
1194 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1195 // FIXME: Map from variable template specializations back to the template.
1196 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo())
1197 Entity = getInstantiatedFrom(VD, MSInfo);
1198 }
1199
1200 // Walk up to the containing context. That might also have been instantiated
1201 // from a template.
1202 DeclContext *Context = Entity->getDeclContext();
1203 if (Context->isFileContext())
1204 return Entity->getOwningModule();
1205 return getDefiningModule(cast<Decl>(Context));
1206}
1207
1208llvm::DenseSet<Module*> &Sema::getLookupModules() {
1209 unsigned N = ActiveTemplateInstantiations.size();
1210 for (unsigned I = ActiveTemplateInstantiationLookupModules.size();
1211 I != N; ++I) {
1212 Module *M = getDefiningModule(ActiveTemplateInstantiations[I].Entity);
1213 if (M && !LookupModulesCache.insert(M).second)
1214 M = 0;
1215 ActiveTemplateInstantiationLookupModules.push_back(M);
1216 }
1217 return LookupModulesCache;
1218}
1219
1220/// \brief Determine whether a declaration is visible to name lookup.
1221///
1222/// This routine determines whether the declaration D is visible in the current
1223/// lookup context, taking into account the current template instantiation
1224/// stack. During template instantiation, a declaration is visible if it is
1225/// visible from a module containing any entity on the template instantiation
1226/// path (by instantiating a template, you allow it to see the declarations that
1227/// your module can see, including those later on in your module).
1228bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
1229 assert(D->isHidden() && !SemaRef.ActiveTemplateInstantiations.empty() &&
1230 "should not call this: not in slow case");
1231 Module *DeclModule = D->getOwningModule();
1232 assert(DeclModule && "hidden decl not from a module");
1233
1234 // Find the extra places where we need to look.
1235 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
1236 if (LookupModules.empty())
1237 return false;
1238
1239 // If our lookup set contains the decl's module, it's visible.
1240 if (LookupModules.count(DeclModule))
1241 return true;
1242
1243 // If the declaration isn't exported, it's not visible in any other module.
1244 if (D->isModulePrivate())
1245 return false;
1246
1247 // Check whether DeclModule is transitively exported to an import of
1248 // the lookup set.
1249 for (llvm::DenseSet<Module *>::iterator I = LookupModules.begin(),
1250 E = LookupModules.end();
1251 I != E; ++I)
1252 if ((*I)->isModuleVisible(DeclModule))
1253 return true;
1254 return false;
1255}
1256
Douglas Gregor4a814562011-12-14 16:03:29 +00001257/// \brief Retrieve the visible declaration corresponding to D, if any.
1258///
1259/// This routine determines whether the declaration D is visible in the current
1260/// module, with the current imports. If not, it checks whether any
1261/// redeclaration of D is visible, and if so, returns that declaration.
Richard Smith0e5d7b82013-07-25 23:08:39 +00001262///
Douglas Gregor4a814562011-12-14 16:03:29 +00001263/// \returns D, or a visible previous declaration of D, whichever is more recent
1264/// and visible. If no declaration of D is visible, returns null.
Richard Smithe156254d2013-08-20 20:35:18 +00001265static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
1266 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
Richard Smith0e5d7b82013-07-25 23:08:39 +00001267
Aaron Ballman86c93902014-03-06 23:45:36 +00001268 for (auto RD : D->redecls()) {
1269 if (auto ND = dyn_cast<NamedDecl>(RD)) {
Richard Smithe156254d2013-08-20 20:35:18 +00001270 if (LookupResult::isVisible(SemaRef, ND))
Douglas Gregor54079202012-01-06 22:05:37 +00001271 return ND;
1272 }
Douglas Gregor4a814562011-12-14 16:03:29 +00001273 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001274
Douglas Gregor4a814562011-12-14 16:03:29 +00001275 return 0;
1276}
1277
Richard Smithe156254d2013-08-20 20:35:18 +00001278NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
1279 return findAcceptableDecl(SemaRef, D);
1280}
1281
Douglas Gregor34074322009-01-14 22:20:51 +00001282/// @brief Perform unqualified name lookup starting from a given
1283/// scope.
1284///
1285/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1286/// used to find names within the current scope. For example, 'x' in
1287/// @code
1288/// int x;
1289/// int f() {
1290/// return x; // unqualified name look finds 'x' in the global scope
1291/// }
1292/// @endcode
1293///
1294/// Different lookup criteria can find different names. For example, a
1295/// particular scope can have both a struct and a function of the same
1296/// name, and each can be found by certain lookup criteria. For more
1297/// information about lookup criteria, see the documentation for the
1298/// class LookupCriteria.
1299///
1300/// @param S The scope from which unqualified name lookup will
1301/// begin. If the lookup criteria permits, name lookup may also search
1302/// in the parent scopes.
1303///
James Dennett91738ff2012-06-22 10:32:46 +00001304/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1305/// look up and the lookup kind), and is updated with the results of lookup
1306/// including zero or more declarations and possibly additional information
1307/// used to diagnose ambiguities.
Douglas Gregor34074322009-01-14 22:20:51 +00001308///
James Dennett91738ff2012-06-22 10:32:46 +00001309/// @returns \c true if lookup succeeded and false otherwise.
John McCall27b18f82009-11-17 02:14:36 +00001310bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1311 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001312 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001313
John McCall27b18f82009-11-17 02:14:36 +00001314 LookupNameKind NameKind = R.getLookupKind();
1315
David Blaikiebbafb8a2012-03-11 07:00:24 +00001316 if (!getLangOpts().CPlusPlus) {
Douglas Gregor34074322009-01-14 22:20:51 +00001317 // Unqualified name lookup in C/Objective-C is purely lexical, so
1318 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001319 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001320 // Find the nearest non-transparent declaration scope.
1321 while (!(S->getFlags() & Scope::DeclScope) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001322 (S->getEntity() && S->getEntity()->isTransparentContext()))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001323 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001324 }
1325
Richard Smith541b38b2013-09-20 01:15:31 +00001326 // When performing a scope lookup, we want to find local extern decls.
1327 FindLocalExternScope FindLocals(R);
1328
Douglas Gregor34074322009-01-14 22:20:51 +00001329 // Scan up the scope chain looking for a decl that matches this
1330 // identifier that is in the appropriate namespace. This search
1331 // should not take long, as shadowing of names is uncommon, and
1332 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001333 bool LeftStartingScope = false;
1334
Douglas Gregored8f2882009-01-30 01:04:22 +00001335 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001336 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001337 I != IEnd; ++I)
Richard Smith0e5d7b82013-07-25 23:08:39 +00001338 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001339 if (NameKind == LookupRedeclarationWithLinkage) {
1340 // Determine whether this (or a previous) declaration is
1341 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001342 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001343 LeftStartingScope = true;
1344
1345 // If we found something outside of our starting scope that
1346 // does not have linkage, skip it.
Richard Smith1c34fb72013-08-13 18:18:50 +00001347 if (LeftStartingScope && !((*I)->hasLinkage())) {
1348 R.setShadowed();
Douglas Gregoreddf4332009-02-24 20:03:32 +00001349 continue;
Richard Smith1c34fb72013-08-13 18:18:50 +00001350 }
Douglas Gregoreddf4332009-02-24 20:03:32 +00001351 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001352 else if (NameKind == LookupObjCImplicitSelfParam &&
1353 !isa<ImplicitParamDecl>(*I))
1354 continue;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001355
Douglas Gregor4a814562011-12-14 16:03:29 +00001356 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001357
Douglas Gregorb59643b2012-01-03 23:26:26 +00001358 // Check whether there are any other declarations with the same name
1359 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001360 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001361 // Find the scope in which this declaration was declared (if it
1362 // actually exists in a Scope).
1363 while (S && !S->isDeclScope(D))
1364 S = S->getParent();
1365
1366 // If the scope containing the declaration is the translation unit,
1367 // then we'll need to perform our checks based on the matching
1368 // DeclContexts rather than matching scopes.
1369 if (S && isNamespaceOrTranslationUnitScope(S))
1370 S = 0;
1371
1372 // Compute the DeclContext, if we need it.
1373 DeclContext *DC = 0;
1374 if (!S)
1375 DC = (*I)->getDeclContext()->getRedeclContext();
1376
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001377 IdentifierResolver::iterator LastI = I;
1378 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001379 if (S) {
1380 // Match based on scope.
1381 if (!S->isDeclScope(*LastI))
1382 break;
1383 } else {
1384 // Match based on DeclContext.
1385 DeclContext *LastDC
1386 = (*LastI)->getDeclContext()->getRedeclContext();
1387 if (!LastDC->Equals(DC))
1388 break;
1389 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001390
1391 // If the declaration is in the right namespace and visible, add it.
1392 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1393 R.addDecl(LastD);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001394 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001395
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001396 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001397 }
Richard Smith541b38b2013-09-20 01:15:31 +00001398
John McCall9f3059a2009-10-09 21:13:30 +00001399 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001400 }
Douglas Gregor34074322009-01-14 22:20:51 +00001401 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001402 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001403 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001404 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001405 }
1406
1407 // If we didn't find a use of this identifier, and if the identifier
1408 // corresponds to a compiler builtin, create the decl object for the builtin
1409 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001410 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1411 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001412
Axel Naumann016538a2011-02-24 16:47:47 +00001413 // If we didn't find a use of this identifier, the ExternalSource
1414 // may be able to handle the situation.
1415 // Note: some lookup failures are expected!
1416 // See e.g. R.isForRedeclaration().
1417 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001418}
1419
John McCall6538c932009-10-10 05:48:19 +00001420/// @brief Perform qualified name lookup in the namespaces nominated by
1421/// using directives by the given context.
1422///
1423/// C++98 [namespace.qual]p2:
James Dennett51a8d8b2012-06-19 21:05:49 +00001424/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6538c932009-10-10 05:48:19 +00001425/// (where X is the global namespace), let S be the set of all
1426/// declarations of m in X and in the transitive closure of all
1427/// namespaces nominated by using-directives in X and its used
1428/// namespaces, except that using-directives are ignored in any
1429/// namespace, including X, directly containing one or more
1430/// declarations of m. No namespace is searched more than once in
1431/// the lookup of a name. If S is the empty set, the program is
1432/// ill-formed. Otherwise, if S has exactly one member, or if the
1433/// context of the reference is a using-declaration
1434/// (namespace.udecl), S is the required set of declarations of
1435/// m. Otherwise if the use of m is not one that allows a unique
1436/// declaration to be chosen from S, the program is ill-formed.
James Dennett51a8d8b2012-06-19 21:05:49 +00001437///
John McCall6538c932009-10-10 05:48:19 +00001438/// C++98 [namespace.qual]p5:
1439/// During the lookup of a qualified namespace member name, if the
1440/// lookup finds more than one declaration of the member, and if one
1441/// declaration introduces a class name or enumeration name and the
1442/// other declarations either introduce the same object, the same
1443/// enumerator or a set of functions, the non-type name hides the
1444/// class or enumeration name if and only if the declarations are
1445/// from the same namespace; otherwise (the declarations are from
1446/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001447static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001448 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001449 assert(StartDC->isFileContext() && "start context is not a file context");
1450
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001451 DeclContext::udir_range UsingDirectives = StartDC->using_directives();
1452 if (UsingDirectives.begin() == UsingDirectives.end()) return false;
John McCall6538c932009-10-10 05:48:19 +00001453
1454 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001455 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001456 Visited.insert(StartDC);
1457
1458 // We have not yet looked into these namespaces, much less added
1459 // their "using-children" to the queue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001460 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001461
1462 // We have already looked into the initial namespace; seed the queue
1463 // with its using-children.
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001464 for (auto *I : UsingDirectives) {
1465 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001466 if (Visited.insert(ND))
John McCall6538c932009-10-10 05:48:19 +00001467 Queue.push_back(ND);
1468 }
1469
1470 // The easiest way to implement the restriction in [namespace.qual]p5
1471 // is to check whether any of the individual results found a tag
1472 // and, if so, to declare an ambiguity if the final result is not
1473 // a tag.
1474 bool FoundTag = false;
1475 bool FoundNonTag = false;
1476
John McCall5cebab12009-11-18 07:57:50 +00001477 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001478
1479 bool Found = false;
1480 while (!Queue.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001481 NamespaceDecl *ND = Queue.pop_back_val();
John McCall6538c932009-10-10 05:48:19 +00001482
1483 // We go through some convolutions here to avoid copying results
1484 // between LookupResults.
1485 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001486 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001487 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001488
1489 if (FoundDirect) {
1490 // First do any local hiding.
1491 DirectR.resolveKind();
1492
1493 // If the local result is a tag, remember that.
1494 if (DirectR.isSingleTagDecl())
1495 FoundTag = true;
1496 else
1497 FoundNonTag = true;
1498
1499 // Append the local results to the total results if necessary.
1500 if (UseLocal) {
1501 R.addAllDecls(LocalR);
1502 LocalR.clear();
1503 }
1504 }
1505
1506 // If we find names in this namespace, ignore its using directives.
1507 if (FoundDirect) {
1508 Found = true;
1509 continue;
1510 }
1511
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001512 for (auto I : ND->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00001513 NamespaceDecl *Nom = I->getNominatedNamespace();
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001514 if (Visited.insert(Nom))
John McCall6538c932009-10-10 05:48:19 +00001515 Queue.push_back(Nom);
1516 }
1517 }
1518
1519 if (Found) {
1520 if (FoundTag && FoundNonTag)
1521 R.setAmbiguousQualifiedTagHiding();
1522 else
1523 R.resolveKind();
1524 }
1525
1526 return Found;
1527}
1528
Douglas Gregor39982192010-08-15 06:18:01 +00001529/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001530static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor39982192010-08-15 06:18:01 +00001531 CXXBasePath &Path,
1532 void *Name) {
1533 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001534
Douglas Gregor39982192010-08-15 06:18:01 +00001535 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1536 Path.Decls = BaseRecord->lookup(N);
David Blaikieff7d47a2012-12-19 00:45:41 +00001537 return !Path.Decls.empty();
Douglas Gregor39982192010-08-15 06:18:01 +00001538}
1539
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001540/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001541/// static members, nested types, and enumerators.
1542template<typename InputIterator>
1543static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1544 Decl *D = (*First)->getUnderlyingDecl();
1545 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1546 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001547
Douglas Gregorc0d24902010-10-22 22:08:47 +00001548 if (isa<CXXMethodDecl>(D)) {
1549 // Determine whether all of the methods are static.
1550 bool AllMethodsAreStatic = true;
1551 for(; First != Last; ++First) {
1552 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001553
Douglas Gregorc0d24902010-10-22 22:08:47 +00001554 if (!isa<CXXMethodDecl>(D)) {
1555 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1556 break;
1557 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001558
Douglas Gregorc0d24902010-10-22 22:08:47 +00001559 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1560 AllMethodsAreStatic = false;
1561 break;
1562 }
1563 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001564
Douglas Gregorc0d24902010-10-22 22:08:47 +00001565 if (AllMethodsAreStatic)
1566 return true;
1567 }
1568
1569 return false;
1570}
1571
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001572/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001573///
1574/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1575/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001576/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001577///
1578/// Different lookup criteria can find different names. For example, a
1579/// particular scope can have both a struct and a function of the same
1580/// name, and each can be found by certain lookup criteria. For more
1581/// information about lookup criteria, see the documentation for the
1582/// class LookupCriteria.
1583///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001584/// \param R captures both the lookup criteria and any lookup results found.
1585///
1586/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001587/// search. If the lookup criteria permits, name lookup may also search
1588/// in the parent contexts or (for C++ classes) base classes.
1589///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001590/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001591/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001592///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001593/// \returns true if lookup succeeded, false if it failed.
1594bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1595 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001596 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001597
John McCall27b18f82009-11-17 02:14:36 +00001598 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001599 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001600
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001601 // Make sure that the declaration context is complete.
1602 assert((!isa<TagDecl>(LookupCtx) ||
1603 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00001604 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith7d137e32012-03-23 03:33:32 +00001605 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001606 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001607
Douglas Gregor34074322009-01-14 22:20:51 +00001608 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001609 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001610 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001611 if (isa<CXXRecordDecl>(LookupCtx))
1612 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001613 return true;
1614 }
Douglas Gregor34074322009-01-14 22:20:51 +00001615
John McCall6538c932009-10-10 05:48:19 +00001616 // Don't descend into implied contexts for redeclarations.
1617 // C++98 [namespace.qual]p6:
1618 // In a declaration for a namespace member in which the
1619 // declarator-id is a qualified-id, given that the qualified-id
1620 // for the namespace member has the form
1621 // nested-name-specifier unqualified-id
1622 // the unqualified-id shall name a member of the namespace
1623 // designated by the nested-name-specifier.
1624 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001625 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001626 return false;
1627
John McCall27b18f82009-11-17 02:14:36 +00001628 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001629 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001630 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001631
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001632 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001633 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001634 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001635 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001636 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001637
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001638 // If we're performing qualified name lookup into a dependent class,
1639 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001640 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001641 // template instantiation time (at which point all bases will be available)
1642 // or we have to fail.
1643 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1644 LookupRec->hasAnyDependentBases()) {
1645 R.setNotFoundInCurrentInstantiation();
1646 return false;
1647 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001648
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001649 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001650 CXXBasePaths Paths;
1651 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001652
1653 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001654 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001655 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001656 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001657 case LookupOrdinaryName:
1658 case LookupMemberName:
1659 case LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +00001660 case LookupLocalFriendName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001661 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1662 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001663
Douglas Gregor36d1b142009-10-06 17:59:45 +00001664 case LookupTagName:
1665 BaseCallback = &CXXRecordDecl::FindTagMember;
1666 break;
John McCall84d87672009-12-10 09:41:52 +00001667
Douglas Gregor39982192010-08-15 06:18:01 +00001668 case LookupAnyName:
1669 BaseCallback = &LookupAnyMember;
1670 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001671
John McCall84d87672009-12-10 09:41:52 +00001672 case LookupUsingDeclName:
1673 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001674
Douglas Gregor36d1b142009-10-06 17:59:45 +00001675 case LookupOperatorName:
1676 case LookupNamespaceName:
1677 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001678 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001679 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001680 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001681
Douglas Gregor36d1b142009-10-06 17:59:45 +00001682 case LookupNestedNameSpecifierName:
1683 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1684 break;
1685 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001686
John McCall27b18f82009-11-17 02:14:36 +00001687 if (!LookupRec->lookupInBases(BaseCallback,
1688 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001689 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001690
John McCall553c0792010-01-23 00:46:32 +00001691 R.setNamingClass(LookupRec);
1692
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001693 // C++ [class.member.lookup]p2:
1694 // [...] If the resulting set of declarations are not all from
1695 // sub-objects of the same type, or the set has a nonstatic member
1696 // and includes members from distinct sub-objects, there is an
1697 // ambiguity and the program is ill-formed. Otherwise that set is
1698 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001699 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001700 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001701 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001702
Douglas Gregor36d1b142009-10-06 17:59:45 +00001703 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001704 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001705 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001706
John McCall401982f2010-01-20 21:53:11 +00001707 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1708 // across all paths.
1709 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001710
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001711 // Determine whether we're looking at a distinct sub-object or not.
1712 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001713 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001714 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1715 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001716 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001717 }
1718
Douglas Gregorc0d24902010-10-22 22:08:47 +00001719 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001720 != Context.getCanonicalType(PathElement.Base->getType())) {
1721 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001722 // different types. If the declaration sets aren't the same, this
1723 // this lookup is ambiguous.
David Blaikieff7d47a2012-12-19 00:45:41 +00001724 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00001725 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikieff7d47a2012-12-19 00:45:41 +00001726 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
1727 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001728
David Blaikieff7d47a2012-12-19 00:45:41 +00001729 while (FirstD != FirstPath->Decls.end() &&
1730 CurrentD != Path->Decls.end()) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00001731 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1732 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1733 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001734
Douglas Gregorc0d24902010-10-22 22:08:47 +00001735 ++FirstD;
1736 ++CurrentD;
1737 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001738
David Blaikieff7d47a2012-12-19 00:45:41 +00001739 if (FirstD == FirstPath->Decls.end() &&
1740 CurrentD == Path->Decls.end())
Douglas Gregorc0d24902010-10-22 22:08:47 +00001741 continue;
1742 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001743
John McCall9f3059a2009-10-09 21:13:30 +00001744 R.setAmbiguousBaseSubobjectTypes(Paths);
1745 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001746 }
1747
Douglas Gregorc0d24902010-10-22 22:08:47 +00001748 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001749 // We have a different subobject of the same type.
1750
1751 // C++ [class.member.lookup]p5:
1752 // A static member, a nested type or an enumerator defined in
1753 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001754 // has more than one base class subobject of type T.
David Blaikieff7d47a2012-12-19 00:45:41 +00001755 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001756 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001757
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001758 // We have found a nonstatic member name in multiple, distinct
1759 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001760 R.setAmbiguousBaseSubobjects(Paths);
1761 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001762 }
1763 }
1764
1765 // Lookup in a base class succeeded; return these results.
1766
David Blaikieff7d47a2012-12-19 00:45:41 +00001767 DeclContext::lookup_result DR = Paths.front().Decls;
1768 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E; ++I) {
John McCall553c0792010-01-23 00:46:32 +00001769 NamedDecl *D = *I;
1770 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1771 D->getAccess());
1772 R.addDecl(D, AS);
1773 }
John McCall9f3059a2009-10-09 21:13:30 +00001774 R.resolveKind();
1775 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001776}
1777
1778/// @brief Performs name lookup for a name that was parsed in the
1779/// source code, and may contain a C++ scope specifier.
1780///
1781/// This routine is a convenience routine meant to be called from
1782/// contexts that receive a name and an optional C++ scope specifier
1783/// (e.g., "N::M::x"). It will then perform either qualified or
1784/// unqualified name lookup (with LookupQualifiedName or LookupName,
1785/// respectively) on the given name and return those results.
1786///
1787/// @param S The scope from which unqualified name lookup will
1788/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001789///
Douglas Gregore861bac2009-08-25 22:51:20 +00001790/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001791///
Douglas Gregore861bac2009-08-25 22:51:20 +00001792/// @param EnteringContext Indicates whether we are going to enter the
1793/// context of the scope-specifier SS (if present).
1794///
John McCall9f3059a2009-10-09 21:13:30 +00001795/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001796bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001797 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001798 if (SS && SS->isInvalid()) {
1799 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001800 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001801 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001802 }
Mike Stump11289f42009-09-09 15:08:12 +00001803
Douglas Gregore861bac2009-08-25 22:51:20 +00001804 if (SS && SS->isSet()) {
1805 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001806 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001807 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001808 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001809 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001810
John McCall27b18f82009-11-17 02:14:36 +00001811 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00001812 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001813 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001814
Douglas Gregore861bac2009-08-25 22:51:20 +00001815 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001816 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001817 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00001818 R.setNotFoundInCurrentInstantiation();
1819 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00001820 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001821 }
1822
Mike Stump11289f42009-09-09 15:08:12 +00001823 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001824 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001825}
1826
Douglas Gregor889ceb72009-02-03 19:21:40 +00001827
James Dennett41725122012-06-22 10:16:05 +00001828/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001829/// from name lookup.
1830///
James Dennett41725122012-06-22 10:16:05 +00001831/// \param Result The result of the ambiguous lookup to be diagnosed.
Serge Pavlov99292092013-08-29 07:23:24 +00001832void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001833 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1834
John McCall27b18f82009-11-17 02:14:36 +00001835 DeclarationName Name = Result.getLookupName();
1836 SourceLocation NameLoc = Result.getNameLoc();
1837 SourceRange LookupRange = Result.getContextRange();
1838
John McCall6538c932009-10-10 05:48:19 +00001839 switch (Result.getAmbiguityKind()) {
1840 case LookupResult::AmbiguousBaseSubobjects: {
1841 CXXBasePaths *Paths = Result.getBasePaths();
1842 QualType SubobjectType = Paths->front().back().Base->getType();
1843 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1844 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1845 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001846
David Blaikieff7d47a2012-12-19 00:45:41 +00001847 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6538c932009-10-10 05:48:19 +00001848 while (isa<CXXMethodDecl>(*Found) &&
1849 cast<CXXMethodDecl>(*Found)->isStatic())
1850 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001851
John McCall6538c932009-10-10 05:48:19 +00001852 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
Serge Pavlov99292092013-08-29 07:23:24 +00001853 break;
John McCall6538c932009-10-10 05:48:19 +00001854 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001855
John McCall6538c932009-10-10 05:48:19 +00001856 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001857 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1858 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001859
John McCall6538c932009-10-10 05:48:19 +00001860 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001861 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001862 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1863 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001864 Path != PathEnd; ++Path) {
David Blaikieff7d47a2012-12-19 00:45:41 +00001865 Decl *D = Path->Decls.front();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001866 if (DeclsPrinted.insert(D).second)
1867 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1868 }
Serge Pavlov99292092013-08-29 07:23:24 +00001869 break;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001870 }
1871
John McCall6538c932009-10-10 05:48:19 +00001872 case LookupResult::AmbiguousTagHiding: {
1873 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001874
John McCall6538c932009-10-10 05:48:19 +00001875 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1876
1877 LookupResult::iterator DI, DE = Result.end();
1878 for (DI = Result.begin(); DI != DE; ++DI)
1879 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1880 TagDecls.insert(TD);
1881 Diag(TD->getLocation(), diag::note_hidden_tag);
1882 }
1883
1884 for (DI = Result.begin(); DI != DE; ++DI)
1885 if (!isa<TagDecl>(*DI))
1886 Diag((*DI)->getLocation(), diag::note_hiding_object);
1887
1888 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001889 LookupResult::Filter F = Result.makeFilter();
1890 while (F.hasNext()) {
1891 if (TagDecls.count(F.next()))
1892 F.erase();
1893 }
1894 F.done();
Serge Pavlov99292092013-08-29 07:23:24 +00001895 break;
John McCall6538c932009-10-10 05:48:19 +00001896 }
1897
1898 case LookupResult::AmbiguousReference: {
1899 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001900
John McCall6538c932009-10-10 05:48:19 +00001901 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1902 for (; DI != DE; ++DI)
1903 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
Serge Pavlov99292092013-08-29 07:23:24 +00001904 break;
John McCall6538c932009-10-10 05:48:19 +00001905 }
Serge Pavlov99292092013-08-29 07:23:24 +00001906 }
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001907}
Douglas Gregore254f902009-02-04 00:32:51 +00001908
John McCallf24d7bb2010-05-28 18:45:08 +00001909namespace {
1910 struct AssociatedLookup {
John McCall7d8b0412012-08-24 20:38:34 +00001911 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallf24d7bb2010-05-28 18:45:08 +00001912 Sema::AssociatedNamespaceSet &Namespaces,
1913 Sema::AssociatedClassSet &Classes)
John McCall7d8b0412012-08-24 20:38:34 +00001914 : S(S), Namespaces(Namespaces), Classes(Classes),
1915 InstantiationLoc(InstantiationLoc) {
John McCallf24d7bb2010-05-28 18:45:08 +00001916 }
1917
1918 Sema &S;
1919 Sema::AssociatedNamespaceSet &Namespaces;
1920 Sema::AssociatedClassSet &Classes;
John McCall7d8b0412012-08-24 20:38:34 +00001921 SourceLocation InstantiationLoc;
John McCallf24d7bb2010-05-28 18:45:08 +00001922 };
1923}
1924
Mike Stump11289f42009-09-09 15:08:12 +00001925static void
John McCallf24d7bb2010-05-28 18:45:08 +00001926addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001927
Douglas Gregor8b895222010-04-30 07:08:38 +00001928static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1929 DeclContext *Ctx) {
1930 // Add the associated namespace for this class.
1931
1932 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1933 // be a locally scoped record.
1934
Sebastian Redlbd595762010-08-31 20:53:31 +00001935 // We skip out of inline namespaces. The innermost non-inline namespace
1936 // contains all names of all its nested inline namespaces anyway, so we can
1937 // replace the entire inline namespace tree with its root.
1938 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1939 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00001940 Ctx = Ctx->getParent();
1941
John McCallc7e8e792009-08-07 22:18:02 +00001942 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001943 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001944}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001945
Mike Stump11289f42009-09-09 15:08:12 +00001946// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001947// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001948static void
John McCallf24d7bb2010-05-28 18:45:08 +00001949addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1950 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001951 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001952 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001953 switch (Arg.getKind()) {
1954 case TemplateArgument::Null:
1955 break;
Mike Stump11289f42009-09-09 15:08:12 +00001956
Douglas Gregor197e5f72009-07-08 07:51:57 +00001957 case TemplateArgument::Type:
1958 // [...] the namespaces and classes associated with the types of the
1959 // template arguments provided for template type parameters (excluding
1960 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001961 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001962 break;
Mike Stump11289f42009-09-09 15:08:12 +00001963
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001964 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001965 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00001966 // [...] the namespaces in which any template template arguments are
1967 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001968 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001969 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00001970 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001971 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001972 DeclContext *Ctx = ClassTemplate->getDeclContext();
1973 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001974 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001975 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001976 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001977 }
1978 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001979 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001980
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001981 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001982 case TemplateArgument::Integral:
1983 case TemplateArgument::Expression:
Eli Friedmanb826a002012-09-26 02:36:12 +00001984 case TemplateArgument::NullPtr:
Mike Stump11289f42009-09-09 15:08:12 +00001985 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001986 // associated namespaces. ]
1987 break;
Mike Stump11289f42009-09-09 15:08:12 +00001988
Douglas Gregor197e5f72009-07-08 07:51:57 +00001989 case TemplateArgument::Pack:
1990 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1991 PEnd = Arg.pack_end();
1992 P != PEnd; ++P)
John McCallf24d7bb2010-05-28 18:45:08 +00001993 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001994 break;
1995 }
1996}
1997
Douglas Gregore254f902009-02-04 00:32:51 +00001998// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001999// argument-dependent lookup with an argument of class type
2000// (C++ [basic.lookup.koenig]p2).
2001static void
John McCallf24d7bb2010-05-28 18:45:08 +00002002addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2003 CXXRecordDecl *Class) {
2004
2005 // Just silently ignore anything whose name is __va_list_tag.
2006 if (Class->getDeclName() == Result.S.VAListTagName)
2007 return;
2008
Douglas Gregore254f902009-02-04 00:32:51 +00002009 // C++ [basic.lookup.koenig]p2:
2010 // [...]
2011 // -- If T is a class type (including unions), its associated
2012 // classes are: the class itself; the class of which it is a
2013 // member, if any; and its direct and indirect base
2014 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00002015 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00002016
2017 // Add the class of which it is a member, if any.
2018 DeclContext *Ctx = Class->getDeclContext();
2019 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002020 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002021 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002022 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002023
Douglas Gregore254f902009-02-04 00:32:51 +00002024 // Add the class itself. If we've already seen this class, we don't
2025 // need to visit base classes.
Richard Smith594461f2014-03-14 22:07:27 +00002026 //
2027 // FIXME: That's not correct, we may have added this class only because it
2028 // was the enclosing class of another class, and in that case we won't have
2029 // added its base classes yet.
John McCallf24d7bb2010-05-28 18:45:08 +00002030 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00002031 return;
2032
Mike Stump11289f42009-09-09 15:08:12 +00002033 // -- If T is a template-id, its associated namespaces and classes are
2034 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002035 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00002036 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00002037 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00002038 // namespaces in which any template template arguments are defined; and
2039 // the classes in which any member templates used as template template
2040 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00002041 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00002042 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00002043 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2044 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2045 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002046 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002047 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002048 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002049
Douglas Gregor197e5f72009-07-08 07:51:57 +00002050 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2051 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00002052 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002053 }
Mike Stump11289f42009-09-09 15:08:12 +00002054
John McCall67da35c2010-02-04 22:26:26 +00002055 // Only recurse into base classes for complete types.
Richard Smith594461f2014-03-14 22:07:27 +00002056 if (!Class->hasDefinition())
2057 return;
John McCall67da35c2010-02-04 22:26:26 +00002058
Douglas Gregore254f902009-02-04 00:32:51 +00002059 // Add direct and indirect base classes along with their associated
2060 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002061 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00002062 Bases.push_back(Class);
2063 while (!Bases.empty()) {
2064 // Pop this class off the stack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002065 Class = Bases.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002066
2067 // Visit the base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +00002068 for (const auto &Base : Class->bases()) {
2069 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00002070 // In dependent contexts, we do ADL twice, and the first time around,
2071 // the base type might be a dependent TemplateSpecializationType, or a
2072 // TemplateTypeParmType. If that happens, simply ignore it.
2073 // FIXME: If we want to support export, we probably need to add the
2074 // namespace of the template in a TemplateSpecializationType, or even
2075 // the classes and namespaces of known non-dependent arguments.
2076 if (!BaseType)
2077 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002078 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002079 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00002080 // Find the associated namespace for this base class.
2081 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00002082 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00002083
2084 // Make sure we visit the bases of this base class.
2085 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2086 Bases.push_back(BaseDecl);
2087 }
2088 }
2089 }
2090}
2091
2092// \brief Add the associated classes and namespaces for
2093// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00002094// (C++ [basic.lookup.koenig]p2).
2095static void
John McCallf24d7bb2010-05-28 18:45:08 +00002096addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00002097 // C++ [basic.lookup.koenig]p2:
2098 //
2099 // For each argument type T in the function call, there is a set
2100 // of zero or more associated namespaces and a set of zero or more
2101 // associated classes to be considered. The sets of namespaces and
2102 // classes is determined entirely by the types of the function
2103 // arguments (and the namespace of any template template
2104 // argument). Typedef names and using-declarations used to specify
2105 // the types do not contribute to this set. The sets of namespaces
2106 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00002107
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002108 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00002109 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2110
Douglas Gregore254f902009-02-04 00:32:51 +00002111 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00002112 switch (T->getTypeClass()) {
2113
2114#define TYPE(Class, Base)
2115#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2116#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2117#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2118#define ABSTRACT_TYPE(Class, Base)
2119#include "clang/AST/TypeNodes.def"
2120 // T is canonical. We can also ignore dependent types because
2121 // we don't need to do ADL at the definition point, but if we
2122 // wanted to implement template export (or if we find some other
2123 // use for associated classes and namespaces...) this would be
2124 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00002125 break;
Douglas Gregore254f902009-02-04 00:32:51 +00002126
John McCall0af3d3b2010-05-28 06:08:54 +00002127 // -- If T is a pointer to U or an array of U, its associated
2128 // namespaces and classes are those associated with U.
2129 case Type::Pointer:
2130 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2131 continue;
2132 case Type::ConstantArray:
2133 case Type::IncompleteArray:
2134 case Type::VariableArray:
2135 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2136 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002137
John McCall0af3d3b2010-05-28 06:08:54 +00002138 // -- If T is a fundamental type, its associated sets of
2139 // namespaces and classes are both empty.
2140 case Type::Builtin:
2141 break;
2142
2143 // -- If T is a class type (including unions), its associated
2144 // classes are: the class itself; the class of which it is a
2145 // member, if any; and its direct and indirect base
2146 // classes. Its associated namespaces are the namespaces in
2147 // which its associated classes are defined.
2148 case Type::Record: {
Richard Smith594461f2014-03-14 22:07:27 +00002149 Result.S.RequireCompleteType(Result.InstantiationLoc, QualType(T, 0),
2150 /*no diagnostic*/ 0);
John McCall0af3d3b2010-05-28 06:08:54 +00002151 CXXRecordDecl *Class
2152 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002153 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00002154 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00002155 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00002156
John McCall0af3d3b2010-05-28 06:08:54 +00002157 // -- If T is an enumeration type, its associated namespace is
2158 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002159 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00002160 // it has no associated class.
2161 case Type::Enum: {
2162 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002163
John McCall0af3d3b2010-05-28 06:08:54 +00002164 DeclContext *Ctx = Enum->getDeclContext();
2165 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002166 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002167
John McCall0af3d3b2010-05-28 06:08:54 +00002168 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002169 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00002170
John McCall0af3d3b2010-05-28 06:08:54 +00002171 break;
2172 }
2173
2174 // -- If T is a function type, its associated namespaces and
2175 // classes are those associated with the function parameter
2176 // types and those associated with the return type.
2177 case Type::FunctionProto: {
2178 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002179 for (const auto &Arg : Proto->param_types())
2180 Queue.push_back(Arg.getTypePtr());
John McCall0af3d3b2010-05-28 06:08:54 +00002181 // fallthrough
2182 }
2183 case Type::FunctionNoProto: {
2184 const FunctionType *FnType = cast<FunctionType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00002185 T = FnType->getReturnType().getTypePtr();
John McCall0af3d3b2010-05-28 06:08:54 +00002186 continue;
2187 }
2188
2189 // -- If T is a pointer to a member function of a class X, its
2190 // associated namespaces and classes are those associated
2191 // with the function parameter types and return type,
2192 // together with those associated with X.
2193 //
2194 // -- If T is a pointer to a data member of class X, its
2195 // associated namespaces and classes are those associated
2196 // with the member type together with those associated with
2197 // X.
2198 case Type::MemberPointer: {
2199 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2200
2201 // Queue up the class type into which this points.
2202 Queue.push_back(MemberPtr->getClass());
2203
2204 // And directly continue with the pointee type.
2205 T = MemberPtr->getPointeeType().getTypePtr();
2206 continue;
2207 }
2208
2209 // As an extension, treat this like a normal pointer.
2210 case Type::BlockPointer:
2211 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2212 continue;
2213
2214 // References aren't covered by the standard, but that's such an
2215 // obvious defect that we cover them anyway.
2216 case Type::LValueReference:
2217 case Type::RValueReference:
2218 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2219 continue;
2220
2221 // These are fundamental types.
2222 case Type::Vector:
2223 case Type::ExtVector:
2224 case Type::Complex:
2225 break;
2226
Richard Smith27d807c2013-04-30 13:56:41 +00002227 // Non-deduced auto types only get here for error cases.
2228 case Type::Auto:
2229 break;
2230
Douglas Gregor8e936662011-04-12 01:02:45 +00002231 // If T is an Objective-C object or interface type, or a pointer to an
2232 // object or interface type, the associated namespace is the global
2233 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002234 case Type::ObjCObject:
2235 case Type::ObjCInterface:
2236 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002237 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002238 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002239
2240 // Atomic types are just wrappers; use the associations of the
2241 // contained type.
2242 case Type::Atomic:
2243 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2244 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002245 }
2246
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002247 if (Queue.empty())
2248 break;
2249 T = Queue.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002250 }
Douglas Gregore254f902009-02-04 00:32:51 +00002251}
2252
2253/// \brief Find the associated classes and namespaces for
2254/// argument-dependent lookup for a call with the given set of
2255/// arguments.
2256///
2257/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002258/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002259/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00002260void Sema::FindAssociatedClassesAndNamespaces(
2261 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2262 AssociatedNamespaceSet &AssociatedNamespaces,
2263 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002264 AssociatedNamespaces.clear();
2265 AssociatedClasses.clear();
2266
John McCall7d8b0412012-08-24 20:38:34 +00002267 AssociatedLookup Result(*this, InstantiationLoc,
2268 AssociatedNamespaces, AssociatedClasses);
John McCallf24d7bb2010-05-28 18:45:08 +00002269
Douglas Gregore254f902009-02-04 00:32:51 +00002270 // C++ [basic.lookup.koenig]p2:
2271 // For each argument type T in the function call, there is a set
2272 // of zero or more associated namespaces and a set of zero or more
2273 // associated classes to be considered. The sets of namespaces and
2274 // classes is determined entirely by the types of the function
2275 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002276 // argument).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002277 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregore254f902009-02-04 00:32:51 +00002278 Expr *Arg = Args[ArgIdx];
2279
2280 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002281 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002282 continue;
2283 }
2284
2285 // [...] In addition, if the argument is the name or address of a
2286 // set of overloaded functions and/or function templates, its
2287 // associated classes and namespaces are the union of those
2288 // associated with each of the members of the set: the namespace
2289 // in which the function or function template is defined and the
2290 // classes and namespaces associated with its (non-dependent)
2291 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002292 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002293 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002294 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002295 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002296
John McCallf24d7bb2010-05-28 18:45:08 +00002297 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2298 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002299
John McCallf24d7bb2010-05-28 18:45:08 +00002300 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2301 I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002302 // Look through any using declarations to find the underlying function.
Alp Tokera2794f92014-01-22 07:29:52 +00002303 FunctionDecl *FDecl = (*I)->getUnderlyingDecl()->getAsFunction();
Douglas Gregore254f902009-02-04 00:32:51 +00002304
2305 // Add the classes and namespaces associated with the parameter
2306 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002307 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002308 }
2309 }
2310}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002311
2312/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2313/// an acceptable non-member overloaded operator for a call whose
2314/// arguments have types T1 (and, if non-empty, T2). This routine
2315/// implements the check in C++ [over.match.oper]p3b2 concerning
2316/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00002317static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002318IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2319 QualType T1, QualType T2,
2320 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00002321 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2322 return true;
2323
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002324 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2325 return true;
2326
John McCall9dd450b2009-09-21 23:43:11 +00002327 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002328 if (Proto->getNumParams() < 1)
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002329 return false;
2330
2331 if (T1->isEnumeralType()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002332 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002333 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002334 return true;
2335 }
2336
Alp Toker9cacbab2014-01-20 20:26:09 +00002337 if (Proto->getNumParams() < 2)
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002338 return false;
2339
2340 if (!T2.isNull() && T2->isEnumeralType()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002341 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002342 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002343 return true;
2344 }
2345
2346 return false;
2347}
2348
John McCall5cebab12009-11-18 07:57:50 +00002349NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002350 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002351 LookupNameKind NameKind,
2352 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002353 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002354 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002355 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002356}
2357
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002358/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002359ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002360 SourceLocation IdLoc,
2361 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002362 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002363 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002364 return cast_or_null<ObjCProtocolDecl>(D);
2365}
2366
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002367void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002368 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002369 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002370 // C++ [over.match.oper]p3:
2371 // -- The set of non-member candidates is the result of the
2372 // unqualified lookup of operator@ in the context of the
2373 // expression according to the usual rules for name lookup in
2374 // unqualified function calls (3.4.2) except that all member
2375 // functions are ignored. However, if no operand has a class
2376 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00002377 // that have a first parameter of type T1 or "reference to
2378 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002379 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00002380 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002381 // when T2 is an enumeration type, are candidate functions.
2382 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002383 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2384 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002385
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002386 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2387
John McCall9f3059a2009-10-09 21:13:30 +00002388 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002389 return;
2390
2391 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2392 Op != OpEnd; ++Op) {
Douglas Gregor645d76f2010-04-25 20:25:43 +00002393 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2394 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002395 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor645d76f2010-04-25 20:25:43 +00002396 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00002397 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor645d76f2010-04-25 20:25:43 +00002398 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor15448f82009-06-27 21:05:07 +00002399 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00002400 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00002401 // later?
2402 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor645d76f2010-04-25 20:25:43 +00002403 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor15448f82009-06-27 21:05:07 +00002404 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002405 }
2406}
2407
Alexis Hunt1da39282011-06-24 02:11:39 +00002408Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002409 CXXSpecialMember SM,
2410 bool ConstArg,
2411 bool VolatileArg,
2412 bool RValueThis,
2413 bool ConstThis,
2414 bool VolatileThis) {
Richard Smith7d125a12012-11-27 21:20:31 +00002415 assert(CanDeclareSpecialMemberFunction(RD) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002416 "doing special member lookup into record that isn't fully complete");
Richard Smith7d125a12012-11-27 21:20:31 +00002417 RD = RD->getDefinition();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002418 if (RValueThis || ConstThis || VolatileThis)
2419 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2420 "constructors and destructors always have unqualified lvalue this");
2421 if (ConstArg || VolatileArg)
2422 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2423 "parameter-less special members can't have qualified arguments");
2424
2425 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002426 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002427 ID.AddInteger(SM);
2428 ID.AddInteger(ConstArg);
2429 ID.AddInteger(VolatileArg);
2430 ID.AddInteger(RValueThis);
2431 ID.AddInteger(ConstThis);
2432 ID.AddInteger(VolatileThis);
2433
2434 void *InsertPoint;
2435 SpecialMemberOverloadResult *Result =
2436 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2437
2438 // This was already cached
2439 if (Result)
2440 return Result;
2441
Alexis Huntba8e18d2011-06-07 00:11:58 +00002442 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2443 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002444 SpecialMemberCache.InsertNode(Result, InsertPoint);
2445
2446 if (SM == CXXDestructor) {
Richard Smith2be35f52012-12-01 02:35:44 +00002447 if (RD->needsImplicitDestructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002448 DeclareImplicitDestructor(RD);
2449 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002450 assert(DD && "record without a destructor");
2451 Result->setMethod(DD);
Richard Smith852265f2012-03-30 20:53:28 +00002452 Result->setKind(DD->isDeleted() ?
2453 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith83c478d2012-04-20 18:46:14 +00002454 SpecialMemberOverloadResult::Success);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002455 return Result;
2456 }
2457
Alexis Hunteef8ee02011-06-10 03:50:41 +00002458 // Prepare for overload resolution. Here we construct a synthetic argument
2459 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002460 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002461 DeclarationName Name;
2462 Expr *Arg = 0;
2463 unsigned NumArgs;
2464
Richard Smith83c478d2012-04-20 18:46:14 +00002465 QualType ArgType = CanTy;
2466 ExprValueKind VK = VK_LValue;
2467
Alexis Hunteef8ee02011-06-10 03:50:41 +00002468 if (SM == CXXDefaultConstructor) {
2469 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2470 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002471 if (RD->needsImplicitDefaultConstructor())
2472 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002473 } else {
2474 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2475 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smith2be35f52012-12-01 02:35:44 +00002476 if (RD->needsImplicitCopyConstructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002477 DeclareImplicitCopyConstructor(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002478 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002479 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002480 } else {
2481 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smith2be35f52012-12-01 02:35:44 +00002482 if (RD->needsImplicitCopyAssignment())
Alexis Hunt1da39282011-06-24 02:11:39 +00002483 DeclareImplicitCopyAssignment(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002484 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002485 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002486 }
2487
Alexis Hunteef8ee02011-06-10 03:50:41 +00002488 if (ConstArg)
2489 ArgType.addConst();
2490 if (VolatileArg)
2491 ArgType.addVolatile();
2492
2493 // This isn't /really/ specified by the standard, but it's implied
2494 // we should be working from an RValue in the case of move to ensure
2495 // that we prefer to bind to rvalue references, and an LValue in the
2496 // case of copy to ensure we don't bind to rvalue references.
2497 // Possibly an XValue is actually correct in the case of move, but
2498 // there is no semantic difference for class types in this restricted
2499 // case.
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002500 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002501 VK = VK_LValue;
2502 else
2503 VK = VK_RValue;
Richard Smith83c478d2012-04-20 18:46:14 +00002504 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00002505
Richard Smith83c478d2012-04-20 18:46:14 +00002506 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2507
2508 if (SM != CXXDefaultConstructor) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002509 NumArgs = 1;
Richard Smith83c478d2012-04-20 18:46:14 +00002510 Arg = &FakeArg;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002511 }
2512
2513 // Create the object argument
2514 QualType ThisTy = CanTy;
2515 if (ConstThis)
2516 ThisTy.addConst();
2517 if (VolatileThis)
2518 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002519 Expr::Classification Classification =
Richard Smith83c478d2012-04-20 18:46:14 +00002520 OpaqueValueExpr(SourceLocation(), ThisTy,
2521 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002522
2523 // Now we perform lookup on the name we computed earlier and do overload
2524 // resolution. Lookup is only performed directly into the class since there
2525 // will always be a (possibly implicit) declaration to shadow any others.
Nick Lewycky56412332014-01-11 02:37:12 +00002526 OverloadCandidateSet OCS(RD->getLocation());
David Blaikieff7d47a2012-12-19 00:45:41 +00002527 DeclContext::lookup_result R = RD->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00002528 assert(!R.empty() &&
Alexis Hunteef8ee02011-06-10 03:50:41 +00002529 "lookup for a constructor or assignment operator was empty");
Chandler Carruth7deaae72013-08-18 07:20:52 +00002530
2531 // Copy the candidates as our processing of them may load new declarations
2532 // from an external source and invalidate lookup_result.
2533 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2534
2535 for (SmallVectorImpl<NamedDecl *>::iterator I = Candidates.begin(),
Richard Smithd55889a2013-09-09 16:55:27 +00002536 E = Candidates.end();
Chandler Carruth7deaae72013-08-18 07:20:52 +00002537 I != E; ++I) {
2538 NamedDecl *Cand = *I;
Alexis Hunt080709f2011-06-23 00:26:20 +00002539
Alexis Hunt1da39282011-06-24 02:11:39 +00002540 if (Cand->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002541 continue;
2542
Alexis Hunt1da39282011-06-24 02:11:39 +00002543 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2544 // FIXME: [namespace.udecl]p15 says that we should only consider a
2545 // using declaration here if it does not match a declaration in the
2546 // derived class. We do not implement this correctly in other cases
2547 // either.
2548 Cand = U->getTargetDecl();
2549
2550 if (Cand->isInvalidDecl())
2551 continue;
2552 }
2553
2554 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002555 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Alexis Hunt1da39282011-06-24 02:11:39 +00002556 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002557 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2558 OCS, true);
Alexis Hunt080709f2011-06-23 00:26:20 +00002559 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002560 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2561 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt2949f022011-06-22 02:58:46 +00002562 } else if (FunctionTemplateDecl *Tmpl =
Alexis Hunt1da39282011-06-24 02:11:39 +00002563 dyn_cast<FunctionTemplateDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002564 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2565 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002566 RD, 0, ThisTy, Classification,
2567 llvm::makeArrayRef(&Arg, NumArgs),
Alexis Hunt080709f2011-06-23 00:26:20 +00002568 OCS, true);
2569 else
2570 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002571 0, llvm::makeArrayRef(&Arg, NumArgs),
2572 OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002573 } else {
2574 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002575 }
2576 }
2577
2578 OverloadCandidateSet::iterator Best;
2579 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2580 case OR_Success:
2581 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith83c478d2012-04-20 18:46:14 +00002582 Result->setKind(SpecialMemberOverloadResult::Success);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002583 break;
2584
2585 case OR_Deleted:
2586 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith852265f2012-03-30 20:53:28 +00002587 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002588 break;
2589
2590 case OR_Ambiguous:
Richard Smith852265f2012-03-30 20:53:28 +00002591 Result->setMethod(0);
2592 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2593 break;
2594
Alexis Hunteef8ee02011-06-10 03:50:41 +00002595 case OR_No_Viable_Function:
2596 Result->setMethod(0);
Richard Smith852265f2012-03-30 20:53:28 +00002597 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002598 break;
2599 }
2600
2601 return Result;
2602}
2603
2604/// \brief Look up the default constructor for the given class.
2605CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002606 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002607 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2608 false, false);
2609
2610 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002611}
2612
Alexis Hunt491ec602011-06-21 23:42:56 +00002613/// \brief Look up the copying constructor for the given class.
2614CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith83c478d2012-04-20 18:46:14 +00002615 unsigned Quals) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002616 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2617 "non-const, non-volatile qualifiers for copy ctor arg");
2618 SpecialMemberOverloadResult *Result =
2619 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2620 Quals & Qualifiers::Volatile, false, false, false);
2621
Alexis Hunt899bd442011-06-10 04:44:37 +00002622 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2623}
2624
Sebastian Redl22653ba2011-08-30 19:58:05 +00002625/// \brief Look up the moving constructor for the given class.
Richard Smith1c6461e2012-07-18 03:36:00 +00002626CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2627 unsigned Quals) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002628 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002629 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2630 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002631
2632 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2633}
2634
Douglas Gregor52b72822010-07-02 23:12:18 +00002635/// \brief Look up the constructors for the given class.
2636DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002637 // If the implicit constructors have not yet been declared, do so now.
Richard Smith7d125a12012-11-27 21:20:31 +00002638 if (CanDeclareSpecialMemberFunction(Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00002639 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002640 DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +00002641 if (Class->needsImplicitCopyConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002642 DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002643 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002644 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00002645 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002646
Douglas Gregor52b72822010-07-02 23:12:18 +00002647 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2648 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2649 return Class->lookup(Name);
2650}
2651
Alexis Hunt491ec602011-06-21 23:42:56 +00002652/// \brief Look up the copying assignment operator for the given class.
2653CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2654 unsigned Quals, bool RValueThis,
Richard Smith83c478d2012-04-20 18:46:14 +00002655 unsigned ThisQuals) {
Alexis Hunt491ec602011-06-21 23:42:56 +00002656 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2657 "non-const, non-volatile qualifiers for copy assignment arg");
2658 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2659 "non-const, non-volatile qualifiers for copy assignment this");
2660 SpecialMemberOverloadResult *Result =
2661 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2662 Quals & Qualifiers::Volatile, RValueThis,
2663 ThisQuals & Qualifiers::Const,
2664 ThisQuals & Qualifiers::Volatile);
2665
Alexis Hunt491ec602011-06-21 23:42:56 +00002666 return Result->getMethod();
2667}
2668
Sebastian Redl22653ba2011-08-30 19:58:05 +00002669/// \brief Look up the moving assignment operator for the given class.
2670CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith1c6461e2012-07-18 03:36:00 +00002671 unsigned Quals,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002672 bool RValueThis,
2673 unsigned ThisQuals) {
2674 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2675 "non-const, non-volatile qualifiers for copy assignment this");
2676 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002677 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2678 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002679 ThisQuals & Qualifiers::Const,
2680 ThisQuals & Qualifiers::Volatile);
2681
2682 return Result->getMethod();
2683}
2684
Douglas Gregore71edda2010-07-01 22:47:18 +00002685/// \brief Look for the destructor of the given class.
2686///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00002687/// During semantic analysis, this routine should be used in lieu of
2688/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00002689///
2690/// \returns The destructor for this class.
2691CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002692 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2693 false, false, false,
2694 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00002695}
2696
Richard Smithbcc22fc2012-03-09 08:00:36 +00002697/// LookupLiteralOperator - Determine which literal operator should be used for
2698/// a user-defined literal, per C++11 [lex.ext].
2699///
2700/// Normal overload resolution is not used to select which literal operator to
2701/// call for a user-defined literal. Look up the provided literal operator name,
2702/// and filter the results to the appropriate set for the given argument types.
2703Sema::LiteralOperatorLookupResult
2704Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2705 ArrayRef<QualType> ArgTys,
Richard Smithb8b41d32013-10-07 19:57:58 +00002706 bool AllowRaw, bool AllowTemplate,
2707 bool AllowStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002708 LookupName(R, S);
2709 assert(R.getResultKind() != LookupResult::Ambiguous &&
2710 "literal operator lookup can't be ambiguous");
2711
2712 // Filter the lookup results appropriately.
2713 LookupResult::Filter F = R.makeFilter();
2714
Richard Smithbcc22fc2012-03-09 08:00:36 +00002715 bool FoundRaw = false;
Richard Smithb8b41d32013-10-07 19:57:58 +00002716 bool FoundTemplate = false;
2717 bool FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002718 bool FoundExactMatch = false;
2719
2720 while (F.hasNext()) {
2721 Decl *D = F.next();
2722 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2723 D = USD->getTargetDecl();
2724
Douglas Gregorc1970572013-04-10 05:18:00 +00002725 // If the declaration we found is invalid, skip it.
2726 if (D->isInvalidDecl()) {
2727 F.erase();
2728 continue;
2729 }
2730
Richard Smithb8b41d32013-10-07 19:57:58 +00002731 bool IsRaw = false;
2732 bool IsTemplate = false;
2733 bool IsStringTemplate = false;
2734 bool IsExactMatch = false;
2735
Richard Smithbcc22fc2012-03-09 08:00:36 +00002736 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2737 if (FD->getNumParams() == 1 &&
2738 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2739 IsRaw = true;
Richard Smith550de452013-01-15 07:12:59 +00002740 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002741 IsExactMatch = true;
2742 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2743 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2744 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2745 IsExactMatch = false;
2746 break;
2747 }
2748 }
2749 }
2750 }
Richard Smithb8b41d32013-10-07 19:57:58 +00002751 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
2752 TemplateParameterList *Params = FD->getTemplateParameters();
2753 if (Params->size() == 1)
2754 IsTemplate = true;
2755 else
2756 IsStringTemplate = true;
2757 }
Richard Smithbcc22fc2012-03-09 08:00:36 +00002758
2759 if (IsExactMatch) {
2760 FoundExactMatch = true;
Richard Smithb8b41d32013-10-07 19:57:58 +00002761 AllowRaw = false;
2762 AllowTemplate = false;
2763 AllowStringTemplate = false;
2764 if (FoundRaw || FoundTemplate || FoundStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002765 // Go through again and remove the raw and template decls we've
2766 // already found.
2767 F.restart();
Richard Smithb8b41d32013-10-07 19:57:58 +00002768 FoundRaw = FoundTemplate = FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002769 }
Richard Smithb8b41d32013-10-07 19:57:58 +00002770 } else if (AllowRaw && IsRaw) {
2771 FoundRaw = true;
2772 } else if (AllowTemplate && IsTemplate) {
2773 FoundTemplate = true;
2774 } else if (AllowStringTemplate && IsStringTemplate) {
2775 FoundStringTemplate = true;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002776 } else {
2777 F.erase();
2778 }
2779 }
2780
2781 F.done();
2782
2783 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2784 // parameter type, that is used in preference to a raw literal operator
2785 // or literal operator template.
2786 if (FoundExactMatch)
2787 return LOLR_Cooked;
2788
2789 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2790 // operator template, but not both.
2791 if (FoundRaw && FoundTemplate) {
2792 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
Alp Tokera2794f92014-01-22 07:29:52 +00002793 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2794 NoteOverloadCandidate((*I)->getUnderlyingDecl()->getAsFunction());
Richard Smithbcc22fc2012-03-09 08:00:36 +00002795 return LOLR_Error;
2796 }
2797
2798 if (FoundRaw)
2799 return LOLR_Raw;
2800
2801 if (FoundTemplate)
2802 return LOLR_Template;
2803
Richard Smithb8b41d32013-10-07 19:57:58 +00002804 if (FoundStringTemplate)
2805 return LOLR_StringTemplate;
2806
Richard Smithbcc22fc2012-03-09 08:00:36 +00002807 // Didn't find anything we could use.
2808 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2809 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
Richard Smithb8b41d32013-10-07 19:57:58 +00002810 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
2811 << (AllowTemplate || AllowStringTemplate);
Richard Smithbcc22fc2012-03-09 08:00:36 +00002812 return LOLR_Error;
2813}
2814
John McCall8fe68082010-01-26 07:16:45 +00002815void ADLResult::insert(NamedDecl *New) {
2816 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2817
2818 // If we haven't yet seen a decl for this key, or the last decl
2819 // was exactly this one, we're done.
2820 if (Old == 0 || Old == New) {
2821 Old = New;
2822 return;
2823 }
2824
2825 // Otherwise, decide which is a more recent redeclaration.
Alp Tokera2794f92014-01-22 07:29:52 +00002826 FunctionDecl *OldFD = Old->getAsFunction();
2827 FunctionDecl *NewFD = New->getAsFunction();
John McCall8fe68082010-01-26 07:16:45 +00002828
2829 FunctionDecl *Cursor = NewFD;
2830 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002831 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00002832
2833 // If we got to the end without finding OldFD, OldFD is the newer
2834 // declaration; leave things as they are.
2835 if (!Cursor) return;
2836
2837 // If we do find OldFD, then NewFD is newer.
2838 if (Cursor == OldFD) break;
2839
2840 // Otherwise, keep looking.
2841 }
2842
2843 Old = New;
2844}
2845
Sebastian Redlc057f422009-10-23 19:23:15 +00002846void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Robert Wilhelm16e94b92013-08-09 18:02:13 +00002847 SourceLocation Loc, ArrayRef<Expr *> Args,
Richard Smithb6626742012-10-18 17:56:02 +00002848 ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002849 // Find all of the associated namespaces and classes based on the
2850 // arguments we have.
2851 AssociatedNamespaceSet AssociatedNamespaces;
2852 AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00002853 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCallc7e8e792009-08-07 22:18:02 +00002854 AssociatedNamespaces,
2855 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002856
Sebastian Redlc057f422009-10-23 19:23:15 +00002857 QualType T1, T2;
2858 if (Operator) {
2859 T1 = Args[0]->getType();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002860 if (Args.size() >= 2)
Sebastian Redlc057f422009-10-23 19:23:15 +00002861 T2 = Args[1]->getType();
2862 }
2863
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002864 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002865 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2866 // and let Y be the lookup set produced by argument dependent
2867 // lookup (defined as follows). If X contains [...] then Y is
2868 // empty. Otherwise Y is the set of declarations found in the
2869 // namespaces associated with the argument types as described
2870 // below. The set of declarations found by the lookup of the name
2871 // is the union of X and Y.
2872 //
2873 // Here, we compute Y and add its members to the overloaded
2874 // candidate set.
2875 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00002876 NSEnd = AssociatedNamespaces.end();
2877 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002878 // When considering an associated namespace, the lookup is the
2879 // same as the lookup performed when the associated namespace is
2880 // used as a qualifier (3.4.3.2) except that:
2881 //
2882 // -- Any using-directives in the associated namespace are
2883 // ignored.
2884 //
John McCallc7e8e792009-08-07 22:18:02 +00002885 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002886 // associated classes are visible within their respective
2887 // namespaces even if they are not visible during an ordinary
2888 // lookup (11.4).
David Blaikieff7d47a2012-12-19 00:45:41 +00002889 DeclContext::lookup_result R = (*NS)->lookup(Name);
2890 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
2891 ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00002892 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00002893 // If the only declaration here is an ordinary friend, consider
2894 // it only if it was declared in an associated classes.
Richard Smith541b38b2013-09-20 01:15:31 +00002895 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) {
2896 // If it's neither ordinarily visible nor a friend, we can't find it.
2897 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0)
2898 continue;
2899
Richard Smith64017682013-07-17 23:53:16 +00002900 bool DeclaredInAssociatedClass = false;
2901 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
2902 DeclContext *LexDC = DI->getLexicalDeclContext();
2903 if (isa<CXXRecordDecl>(LexDC) &&
2904 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) {
2905 DeclaredInAssociatedClass = true;
2906 break;
2907 }
2908 }
2909 if (!DeclaredInAssociatedClass)
John McCalld1e9d832009-08-11 06:59:38 +00002910 continue;
2911 }
Mike Stump11289f42009-09-09 15:08:12 +00002912
John McCall91f61fc2010-01-26 06:04:06 +00002913 if (isa<UsingShadowDecl>(D))
2914 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002915
John McCall91f61fc2010-01-26 06:04:06 +00002916 if (isa<FunctionDecl>(D)) {
2917 if (Operator &&
2918 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2919 T1, T2, Context))
2920 continue;
John McCall8fe68082010-01-26 07:16:45 +00002921 } else if (!isa<FunctionTemplateDecl>(D))
2922 continue;
2923
2924 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002925 }
2926 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002927}
Douglas Gregor2d435302009-12-30 17:04:44 +00002928
2929//----------------------------------------------------------------------------
2930// Search for all visible declarations.
2931//----------------------------------------------------------------------------
2932VisibleDeclConsumer::~VisibleDeclConsumer() { }
2933
Richard Smithe156254d2013-08-20 20:35:18 +00002934bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
2935
Douglas Gregor2d435302009-12-30 17:04:44 +00002936namespace {
2937
2938class ShadowContextRAII;
2939
2940class VisibleDeclsRecord {
2941public:
2942 /// \brief An entry in the shadow map, which is optimized to store a
2943 /// single declaration (the common case) but can also store a list
2944 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002945 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00002946
2947private:
2948 /// \brief A mapping from declaration names to the declarations that have
2949 /// this name within a particular scope.
2950 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2951
2952 /// \brief A list of shadow maps, which is used to model name hiding.
2953 std::list<ShadowMap> ShadowMaps;
2954
2955 /// \brief The declaration contexts we have already visited.
2956 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2957
2958 friend class ShadowContextRAII;
2959
2960public:
2961 /// \brief Determine whether we have already visited this context
2962 /// (and, if not, note that we are going to visit that context now).
2963 bool visitedContext(DeclContext *Ctx) {
2964 return !VisitedContexts.insert(Ctx);
2965 }
2966
Douglas Gregor39982192010-08-15 06:18:01 +00002967 bool alreadyVisitedContext(DeclContext *Ctx) {
2968 return VisitedContexts.count(Ctx);
2969 }
2970
Douglas Gregor2d435302009-12-30 17:04:44 +00002971 /// \brief Determine whether the given declaration is hidden in the
2972 /// current scope.
2973 ///
2974 /// \returns the declaration that hides the given declaration, or
2975 /// NULL if no such declaration exists.
2976 NamedDecl *checkHidden(NamedDecl *ND);
2977
2978 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002979 void add(NamedDecl *ND) {
2980 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2981 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002982};
2983
2984/// \brief RAII object that records when we've entered a shadow context.
2985class ShadowContextRAII {
2986 VisibleDeclsRecord &Visible;
2987
2988 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2989
2990public:
2991 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2992 Visible.ShadowMaps.push_back(ShadowMap());
2993 }
2994
2995 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00002996 Visible.ShadowMaps.pop_back();
2997 }
2998};
2999
3000} // end anonymous namespace
3001
Douglas Gregor2d435302009-12-30 17:04:44 +00003002NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00003003 // Look through using declarations.
3004 ND = ND->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003005
Douglas Gregor2d435302009-12-30 17:04:44 +00003006 unsigned IDNS = ND->getIdentifierNamespace();
3007 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
3008 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3009 SM != SMEnd; ++SM) {
3010 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
3011 if (Pos == SM->end())
3012 continue;
3013
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003014 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor2d435302009-12-30 17:04:44 +00003015 IEnd = Pos->second.end();
3016 I != IEnd; ++I) {
3017 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +00003018 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003019 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00003020 Decl::IDNS_ObjCProtocol)))
3021 continue;
3022
3023 // Protocols are in distinct namespaces from everything else.
3024 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
3025 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
3026 (*I)->getIdentifierNamespace() != IDNS)
3027 continue;
3028
Douglas Gregor09bbc652010-01-14 15:47:35 +00003029 // Functions and function templates in the same scope overload
3030 // rather than hide. FIXME: Look for hiding based on function
3031 // signatures!
Alp Tokera2794f92014-01-22 07:29:52 +00003032 if ((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
3033 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00003034 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00003035 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003036
Douglas Gregor2d435302009-12-30 17:04:44 +00003037 // We've found a declaration that hides this one.
3038 return *I;
3039 }
3040 }
3041
3042 return 0;
3043}
3044
3045static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
3046 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003047 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00003048 VisibleDeclConsumer &Consumer,
3049 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00003050 if (!Ctx)
3051 return;
3052
Douglas Gregor2d435302009-12-30 17:04:44 +00003053 // Make sure we don't visit the same context twice.
3054 if (Visited.visitedContext(Ctx->getPrimaryContext()))
3055 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003056
Douglas Gregor7454c562010-07-02 20:37:36 +00003057 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3058 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3059
Douglas Gregor2d435302009-12-30 17:04:44 +00003060 // Enumerate all of the results in this context.
Aaron Ballman576114e2014-03-14 15:28:49 +00003061 for (const auto &R : Ctx->lookups()) {
3062 for (auto *I : R) {
3063 if (NamedDecl *ND = dyn_cast<NamedDecl>(I)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00003064 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003065 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00003066 Visited.add(ND);
3067 }
Douglas Gregora3b23b02010-12-09 21:44:02 +00003068 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003069 }
3070 }
3071
3072 // Traverse using directives for qualified name lookup.
3073 if (QualifiedNameLookup) {
3074 ShadowContextRAII Shadow(Visited);
Aaron Ballman804a7fb2014-03-17 17:14:12 +00003075 for (auto I : Ctx->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00003076 LookupVisibleDecls(I->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003077 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003078 }
3079 }
3080
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003081 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00003082 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00003083 if (!Record->hasDefinition())
3084 return;
3085
Aaron Ballman574705e2014-03-13 15:41:46 +00003086 for (const auto &B : Record->bases()) {
3087 QualType BaseType = B.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003088
Douglas Gregor2d435302009-12-30 17:04:44 +00003089 // Don't look into dependent bases, because name lookup can't look
3090 // there anyway.
3091 if (BaseType->isDependentType())
3092 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003093
Douglas Gregor2d435302009-12-30 17:04:44 +00003094 const RecordType *Record = BaseType->getAs<RecordType>();
3095 if (!Record)
3096 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003097
Douglas Gregor2d435302009-12-30 17:04:44 +00003098 // FIXME: It would be nice to be able to determine whether referencing
3099 // a particular member would be ambiguous. For example, given
3100 //
3101 // struct A { int member; };
3102 // struct B { int member; };
3103 // struct C : A, B { };
3104 //
3105 // void f(C *c) { c->### }
3106 //
3107 // accessing 'member' would result in an ambiguity. However, we
3108 // could be smart enough to qualify the member with the base
3109 // class, e.g.,
3110 //
3111 // c->B::member
3112 //
3113 // or
3114 //
3115 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003116
Douglas Gregor2d435302009-12-30 17:04:44 +00003117 // Find results in this base class (and its bases).
3118 ShadowContextRAII Shadow(Visited);
3119 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003120 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003121 }
3122 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003123
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003124 // Traverse the contexts of Objective-C classes.
3125 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3126 // Traverse categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003127 for (auto *Cat : IFace->visible_categories()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003128 ShadowContextRAII Shadow(Visited);
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003129 LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003130 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003131 }
3132
3133 // Traverse protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003134 for (auto *I : IFace->all_referenced_protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003135 ShadowContextRAII Shadow(Visited);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003136 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003137 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003138 }
3139
3140 // Traverse the superclass.
3141 if (IFace->getSuperClass()) {
3142 ShadowContextRAII Shadow(Visited);
3143 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003144 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003145 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003146
Douglas Gregor0b59e802010-04-19 18:02:19 +00003147 // If there is an implementation, traverse it. We do this to find
3148 // synthesized ivars.
3149 if (IFace->getImplementation()) {
3150 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003151 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky13668f22012-04-03 20:26:45 +00003152 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor0b59e802010-04-19 18:02:19 +00003153 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003154 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003155 for (auto *I : Protocol->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003156 ShadowContextRAII Shadow(Visited);
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003157 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003158 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003159 }
3160 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003161 for (auto *I : Category->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003162 ShadowContextRAII Shadow(Visited);
Aaron Ballman19a41762014-03-14 12:55:57 +00003163 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003164 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003165 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003166
Douglas Gregor0b59e802010-04-19 18:02:19 +00003167 // If there is an implementation, traverse it.
3168 if (Category->getImplementation()) {
3169 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003170 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00003171 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003172 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003173 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003174}
3175
3176static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3177 UnqualUsingDirectiveSet &UDirs,
3178 VisibleDeclConsumer &Consumer,
3179 VisibleDeclsRecord &Visited) {
3180 if (!S)
3181 return;
3182
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003183 if (!S->getEntity() ||
3184 (!S->getParent() &&
Ted Kremenekc37877d2013-10-08 17:08:03 +00003185 !Visited.alreadyVisitedContext(S->getEntity())) ||
3186 (S->getEntity())->isFunctionOrMethod()) {
Richard Smith541b38b2013-09-20 01:15:31 +00003187 FindLocalExternScope FindLocals(Result);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003188 // Walk through the declarations in this Scope.
Aaron Ballman35c54952014-03-17 16:55:25 +00003189 for (auto *D : S->decls()) {
3190 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Douglas Gregor4a814562011-12-14 16:03:29 +00003191 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003192 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003193 Visited.add(ND);
3194 }
3195 }
3196 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003197
Douglas Gregor66230062010-03-15 14:33:29 +00003198 // FIXME: C++ [temp.local]p8
Douglas Gregor2d435302009-12-30 17:04:44 +00003199 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00003200 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003201 // Look into this scope's declaration context, along with any of its
3202 // parent lookup contexts (e.g., enclosing classes), up to the point
3203 // where we hit the context stored in the next outer scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00003204 Entity = S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00003205 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003206
Douglas Gregorea166062010-03-15 15:26:48 +00003207 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00003208 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003209 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3210 if (Method->isInstanceMethod()) {
3211 // For instance methods, look for ivars in the method's interface.
3212 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3213 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003214 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003215 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Richard Smithe156254d2013-08-20 20:35:18 +00003216 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003217 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003218 }
3219
3220 // We've already performed all of the name lookup that we need
3221 // to for Objective-C methods; the next context will be the
3222 // outer scope.
3223 break;
3224 }
3225
Douglas Gregor2d435302009-12-30 17:04:44 +00003226 if (Ctx->isFunctionOrMethod())
3227 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003228
3229 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003230 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003231 }
3232 } else if (!S->getParent()) {
3233 // Look into the translation unit scope. We walk through the translation
3234 // unit's declaration context, because the Scope itself won't have all of
3235 // the declarations if we loaded a precompiled header.
3236 // FIXME: We would like the translation unit's Scope object to point to the
3237 // translation unit, so we don't need this special "if" branch. However,
3238 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003239 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00003240 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003241 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00003242 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003243 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003244 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003245 }
3246
Douglas Gregor2d435302009-12-30 17:04:44 +00003247 if (Entity) {
3248 // Lookup visible declarations in any namespaces found by using
3249 // directives.
3250 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003251 std::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
Douglas Gregor2d435302009-12-30 17:04:44 +00003252 for (; UI != UEnd; ++UI)
3253 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003254 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003255 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003256 }
3257
3258 // Lookup names in the parent scope.
3259 ShadowContextRAII Shadow(Visited);
3260 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3261}
3262
3263void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003264 VisibleDeclConsumer &Consumer,
3265 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003266 // Determine the set of using directives available during
3267 // unqualified name lookup.
3268 Scope *Initial = S;
3269 UnqualUsingDirectiveSet UDirs;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003270 if (getLangOpts().CPlusPlus) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003271 // Find the first namespace or translation-unit scope.
3272 while (S && !isNamespaceOrTranslationUnitScope(S))
3273 S = S->getParent();
3274
3275 UDirs.visitScopeChain(Initial, S);
3276 }
3277 UDirs.done();
3278
3279 // Look for visible declarations.
3280 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003281 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003282 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003283 if (!IncludeGlobalScope)
3284 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003285 ShadowContextRAII Shadow(Visited);
3286 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3287}
3288
3289void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003290 VisibleDeclConsumer &Consumer,
3291 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003292 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003293 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003294 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003295 if (!IncludeGlobalScope)
3296 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003297 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003298 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003299 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003300}
3301
Chris Lattner43e7f312011-02-18 02:08:43 +00003302/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003303/// If GnuLabelLoc is a valid source location, then this is a definition
3304/// of an __label__ label name, otherwise it is a normal label definition
3305/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003306LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003307 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003308 // Do a lookup to see if we have a label with this name already.
Chris Lattner43e7f312011-02-18 02:08:43 +00003309 NamedDecl *Res = 0;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003310
3311 if (GnuLabelLoc.isValid()) {
3312 // Local label definitions always shadow existing labels.
3313 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3314 Scope *S = CurScope;
3315 PushOnScopeChains(Res, S, true);
3316 return cast<LabelDecl>(Res);
3317 }
3318
3319 // Not a GNU local label.
3320 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3321 // If we found a label, check to see if it is in the same context as us.
3322 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003323 if (Res && Res->getDeclContext() != CurContext)
3324 Res = 0;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003325 if (Res == 0) {
3326 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003327 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3328 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003329 assert(S && "Not in a function?");
3330 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003331 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003332 return cast<LabelDecl>(Res);
3333}
3334
3335//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003336// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003337//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003338
3339namespace {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003340
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003341typedef SmallVector<TypoCorrection, 1> TypoResultList;
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003342typedef llvm::StringMap<TypoResultList, llvm::BumpPtrAllocator> TypoResultsMap;
Benjamin Kramer73faad62012-04-14 08:26:28 +00003343typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003344
3345static const unsigned MaxTypoDistanceResultSets = 5;
3346
Douglas Gregor2d435302009-12-30 17:04:44 +00003347class TypoCorrectionConsumer : public VisibleDeclConsumer {
3348 /// \brief The name written that is a typo in the source.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003349 StringRef Typo;
Douglas Gregor2d435302009-12-30 17:04:44 +00003350
3351 /// \brief The results found that have the smallest edit distance
3352 /// found (so far) with the typo name.
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003353 ///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003354 /// The pointer value being set to the current DeclContext indicates
3355 /// whether there is a keyword with this name.
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003356 TypoEditDistanceMap CorrectionResults;
Douglas Gregor2d435302009-12-30 17:04:44 +00003357
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003358 Sema &SemaRef;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003359
Douglas Gregor2d435302009-12-30 17:04:44 +00003360public:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003361 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003362 : Typo(Typo->getName()),
Richard Smithe156254d2013-08-20 20:35:18 +00003363 SemaRef(SemaRef) {}
3364
Craig Toppere14c0f82014-03-12 04:55:44 +00003365 bool includeHiddenDecls() const override { return true; }
Douglas Gregor2d435302009-12-30 17:04:44 +00003366
Craig Toppere14c0f82014-03-12 04:55:44 +00003367 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3368 bool InBaseClass) override;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003369 void FoundName(StringRef Name);
3370 void addKeywordResult(StringRef Keyword);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003371 void addName(StringRef Name, NamedDecl *ND, NestedNameSpecifier *NNS = NULL,
3372 bool isKeyword = false);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003373 void addCorrection(TypoCorrection Correction);
Douglas Gregor2d435302009-12-30 17:04:44 +00003374
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003375 typedef TypoResultsMap::iterator result_iterator;
3376 typedef TypoEditDistanceMap::iterator distance_iterator;
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003377 distance_iterator begin() { return CorrectionResults.begin(); }
3378 distance_iterator end() { return CorrectionResults.end(); }
3379 void erase(distance_iterator I) { CorrectionResults.erase(I); }
3380 unsigned size() const { return CorrectionResults.size(); }
3381 bool empty() const { return CorrectionResults.empty(); }
Douglas Gregor2d435302009-12-30 17:04:44 +00003382
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003383 TypoResultList &operator[](StringRef Name) {
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003384 return CorrectionResults.begin()->second[Name];
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003385 }
3386
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003387 unsigned getBestEditDistance(bool Normalized) {
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003388 if (CorrectionResults.empty())
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003389 return (std::numeric_limits<unsigned>::max)();
3390
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003391 unsigned BestED = CorrectionResults.begin()->first;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003392 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003393 }
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003394
3395 TypoResultsMap &getBestResults() {
3396 return CorrectionResults.begin()->second;
3397 }
3398
Douglas Gregor2d435302009-12-30 17:04:44 +00003399};
3400
3401}
3402
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003403void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003404 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003405 // Don't consider hidden names for typo correction.
3406 if (Hiding)
3407 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003408
Douglas Gregor2d435302009-12-30 17:04:44 +00003409 // Only consider entities with identifiers for names, ignoring
3410 // special names (constructors, overloaded operators, selectors,
3411 // etc.).
3412 IdentifierInfo *Name = ND->getIdentifier();
3413 if (!Name)
3414 return;
3415
Richard Smithe156254d2013-08-20 20:35:18 +00003416 // Only consider visible declarations and declarations from modules with
3417 // names that exactly match.
3418 if (!LookupResult::isVisible(SemaRef, ND) && Name->getName() != Typo &&
3419 !findAcceptableDecl(SemaRef, ND))
3420 return;
3421
Douglas Gregor57756ea2010-10-14 22:11:03 +00003422 FoundName(Name->getName());
3423}
3424
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003425void TypoCorrectionConsumer::FoundName(StringRef Name) {
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003426 // Compute the edit distance between the typo and the name of this
3427 // entity, and add the identifier to the list of results.
3428 addName(Name, NULL);
3429}
3430
3431void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3432 // Compute the edit distance between the typo and this keyword,
3433 // and add the keyword to the list of results.
3434 addName(Keyword, NULL, NULL, true);
3435}
3436
3437void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
3438 NestedNameSpecifier *NNS, bool isKeyword) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003439 // Use a simple length-based heuristic to determine the minimum possible
3440 // edit distance. If the minimum isn't good enough, bail out early.
3441 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003442 if (MinED && Typo.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00003443 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003444
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003445 // Compute an upper bound on the allowable edit distance, so that the
3446 // edit-distance algorithm can short-circuit.
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003447 unsigned UpperBound = (Typo.size() + 2) / 3 + 1;
3448 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
3449 if (ED >= UpperBound) return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003450
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003451 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003452 if (isKeyword) TC.makeKeyword();
3453 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003454}
3455
3456void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003457 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003458 TypoResultList &CList =
3459 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003460
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003461 if (!CList.empty() && !CList.back().isResolved())
3462 CList.pop_back();
3463 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3464 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3465 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3466 RI != RIEnd; ++RI) {
3467 // If the Correction refers to a decl already in the result list,
3468 // replace the existing result if the string representation of Correction
3469 // comes before the current result alphabetically, then stop as there is
3470 // nothing more to be done to add Correction to the candidate set.
3471 if (RI->getCorrectionDecl() == NewND) {
3472 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3473 *RI = Correction;
3474 return;
3475 }
3476 }
3477 }
3478 if (CList.empty() || Correction.isResolved())
3479 CList.push_back(Correction);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003480
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003481 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
Benjamin Kramer167e9992014-03-02 12:20:24 +00003482 erase(std::prev(CorrectionResults.end()));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003483}
3484
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003485// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3486// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3487// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3488static void getNestedNameSpecifierIdentifiers(
3489 NestedNameSpecifier *NNS,
3490 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3491 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3492 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3493 else
3494 Identifiers.clear();
3495
3496 const IdentifierInfo *II = NULL;
3497
3498 switch (NNS->getKind()) {
3499 case NestedNameSpecifier::Identifier:
3500 II = NNS->getAsIdentifier();
3501 break;
3502
3503 case NestedNameSpecifier::Namespace:
3504 if (NNS->getAsNamespace()->isAnonymousNamespace())
3505 return;
3506 II = NNS->getAsNamespace()->getIdentifier();
3507 break;
3508
3509 case NestedNameSpecifier::NamespaceAlias:
3510 II = NNS->getAsNamespaceAlias()->getIdentifier();
3511 break;
3512
3513 case NestedNameSpecifier::TypeSpecWithTemplate:
3514 case NestedNameSpecifier::TypeSpec:
3515 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3516 break;
3517
3518 case NestedNameSpecifier::Global:
3519 return;
3520 }
3521
3522 if (II)
3523 Identifiers.push_back(II);
3524}
3525
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003526namespace {
3527
3528class SpecifierInfo {
3529 public:
3530 DeclContext* DeclCtx;
3531 NestedNameSpecifier* NameSpecifier;
3532 unsigned EditDistance;
3533
3534 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3535 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3536};
3537
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003538typedef SmallVector<DeclContext*, 4> DeclContextList;
3539typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003540
3541class NamespaceSpecifierSet {
3542 ASTContext &Context;
3543 DeclContextList CurContextChain;
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003544 std::string CurNameSpecifier;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003545 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3546 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003547 bool isSorted;
3548
3549 SpecifierInfoList Specifiers;
3550 llvm::SmallSetVector<unsigned, 4> Distances;
3551 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3552
3553 /// \brief Helper for building the list of DeclContexts between the current
3554 /// context and the top of the translation unit
3555 static DeclContextList BuildContextChain(DeclContext *Start);
3556
3557 void SortNamespaces();
3558
3559 public:
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003560 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3561 CXXScopeSpec *CurScopeSpec)
Benjamin Kramerde1d6232011-07-05 09:46:31 +00003562 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
Kaelyn Uhrain52dd02d2013-06-24 17:49:03 +00003563 isSorted(false) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003564 if (NestedNameSpecifier *NNS =
3565 CurScopeSpec ? CurScopeSpec->getScopeRep() : 0) {
3566 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
3567 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3568
3569 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
3570 }
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003571 // Build the list of identifiers that would be used for an absolute
Benjamin Kramer474261a2012-06-02 10:20:41 +00003572 // (from the global context) NestedNameSpecifier referring to the current
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003573 // context.
3574 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3575 CEnd = CurContextChain.rend();
3576 C != CEnd; ++C) {
3577 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3578 CurContextIdentifiers.push_back(ND->getIdentifier());
3579 }
Kaelyn Uhrain52dd02d2013-06-24 17:49:03 +00003580
3581 // Add the global context as a NestedNameSpecifier
3582 Distances.insert(1);
3583 DistanceMap[1].push_back(
3584 SpecifierInfo(cast<DeclContext>(Context.getTranslationUnitDecl()),
3585 NestedNameSpecifier::GlobalSpecifier(Context), 1));
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003586 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003587
Kaelyn Uhrain5315a462013-10-19 00:04:49 +00003588 /// \brief Add the DeclContext (a namespace or record) to the set, computing
3589 /// the corresponding NestedNameSpecifier and its distance in the process.
3590 void AddNameSpecifier(DeclContext *Ctx);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003591
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003592 typedef SpecifierInfoList::iterator iterator;
3593 iterator begin() {
3594 if (!isSorted) SortNamespaces();
3595 return Specifiers.begin();
3596 }
3597 iterator end() { return Specifiers.end(); }
3598};
3599
3600}
3601
3602DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Nick Lewycky0d9b3192013-04-08 21:55:21 +00003603 assert(Start && "Building a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003604 DeclContextList Chain;
3605 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3606 DC = DC->getLookupParent()) {
3607 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3608 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3609 !(ND && ND->isAnonymousNamespace()))
3610 Chain.push_back(DC->getPrimaryContext());
3611 }
3612 return Chain;
3613}
3614
3615void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003616 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003617 sortedDistances.append(Distances.begin(), Distances.end());
3618
3619 if (sortedDistances.size() > 1)
3620 std::sort(sortedDistances.begin(), sortedDistances.end());
3621
3622 Specifiers.clear();
Craig Topper2341c0d2013-07-04 03:08:24 +00003623 for (SmallVectorImpl<unsigned>::iterator DI = sortedDistances.begin(),
3624 DIEnd = sortedDistances.end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003625 DI != DIEnd; ++DI) {
3626 SpecifierInfoList &SpecList = DistanceMap[*DI];
3627 Specifiers.append(SpecList.begin(), SpecList.end());
3628 }
3629
3630 isSorted = true;
3631}
3632
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003633static unsigned BuildNestedNameSpecifier(ASTContext &Context,
3634 DeclContextList &DeclChain,
3635 NestedNameSpecifier *&NNS) {
3636 unsigned NumSpecifiers = 0;
3637 for (DeclContextList::reverse_iterator C = DeclChain.rbegin(),
3638 CEnd = DeclChain.rend();
3639 C != CEnd; ++C) {
3640 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) {
3641 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3642 ++NumSpecifiers;
3643 } else if (RecordDecl *RD = dyn_cast_or_null<RecordDecl>(*C)) {
3644 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
3645 RD->getTypeForDecl());
3646 ++NumSpecifiers;
3647 }
3648 }
3649 return NumSpecifiers;
3650}
3651
Kaelyn Uhrain5315a462013-10-19 00:04:49 +00003652void NamespaceSpecifierSet::AddNameSpecifier(DeclContext *Ctx) {
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003653 NestedNameSpecifier *NNS = NULL;
3654 unsigned NumSpecifiers = 0;
3655 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
3656 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
3657
3658 // Eliminate common elements from the two DeclContext chains.
3659 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3660 CEnd = CurContextChain.rend();
3661 C != CEnd && !NamespaceDeclChain.empty() &&
3662 NamespaceDeclChain.back() == *C; ++C) {
3663 NamespaceDeclChain.pop_back();
3664 }
3665
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003666 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3667 NumSpecifiers = BuildNestedNameSpecifier(Context, NamespaceDeclChain, NNS);
3668
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003669 // Add an explicit leading '::' specifier if needed.
3670 if (NamespaceDeclChain.empty()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003671 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003672 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003673 NumSpecifiers =
3674 BuildNestedNameSpecifier(Context, FullNamespaceDeclChain, NNS);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003675 } else if (NamedDecl *ND =
3676 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003677 IdentifierInfo *Name = ND->getIdentifier();
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003678 bool SameNameSpecifier = false;
3679 if (std::find(CurNameSpecifierIdentifiers.begin(),
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003680 CurNameSpecifierIdentifiers.end(),
3681 Name) != CurNameSpecifierIdentifiers.end()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003682 std::string NewNameSpecifier;
3683 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
3684 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
3685 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3686 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3687 SpecifierOStream.flush();
3688 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003689 }
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003690 if (SameNameSpecifier ||
3691 std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3692 Name) != CurContextIdentifiers.end()) {
3693 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
3694 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3695 NumSpecifiers =
3696 BuildNestedNameSpecifier(Context, FullNamespaceDeclChain, NNS);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003697 }
3698 }
3699
3700 // If the built NestedNameSpecifier would be replacing an existing
3701 // NestedNameSpecifier, use the number of component identifiers that
3702 // would need to be changed as the edit distance instead of the number
3703 // of components in the built NestedNameSpecifier.
3704 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3705 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3706 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3707 NumSpecifiers = llvm::ComputeEditDistance(
3708 ArrayRef<const IdentifierInfo *>(CurNameSpecifierIdentifiers),
3709 ArrayRef<const IdentifierInfo *>(NewNameSpecifierIdentifiers));
3710 }
3711
3712 isSorted = false;
3713 Distances.insert(NumSpecifiers);
3714 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
3715}
3716
Douglas Gregord507d772010-10-20 03:06:34 +00003717/// \brief Perform name lookup for a possible result for typo correction.
3718static void LookupPotentialTypoResult(Sema &SemaRef,
3719 LookupResult &Res,
3720 IdentifierInfo *Name,
3721 Scope *S, CXXScopeSpec *SS,
3722 DeclContext *MemberContext,
3723 bool EnteringContext,
Richard Smithe156254d2013-08-20 20:35:18 +00003724 bool isObjCIvarLookup,
3725 bool FindHidden) {
Douglas Gregord507d772010-10-20 03:06:34 +00003726 Res.suppressDiagnostics();
3727 Res.clear();
3728 Res.setLookupName(Name);
Richard Smithe156254d2013-08-20 20:35:18 +00003729 Res.setAllowHidden(FindHidden);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003730 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00003731 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003732 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00003733 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3734 Res.addDecl(Ivar);
3735 Res.resolveKind();
3736 return;
3737 }
3738 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003739
Douglas Gregord507d772010-10-20 03:06:34 +00003740 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3741 Res.addDecl(Prop);
3742 Res.resolveKind();
3743 return;
3744 }
3745 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003746
Douglas Gregord507d772010-10-20 03:06:34 +00003747 SemaRef.LookupQualifiedName(Res, MemberContext);
3748 return;
3749 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003750
3751 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00003752 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003753
Douglas Gregord507d772010-10-20 03:06:34 +00003754 // Fake ivar lookup; this should really be part of
3755 // LookupParsedName.
3756 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3757 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003758 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00003759 (Res.isSingleResult() &&
3760 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003761 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00003762 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3763 Res.addDecl(IV);
3764 Res.resolveKind();
3765 }
3766 }
3767 }
3768}
3769
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003770/// \brief Add keywords to the consumer as possible typo corrections.
3771static void AddKeywordsToConsumer(Sema &SemaRef,
3772 TypoCorrectionConsumer &Consumer,
Richard Smithb3a1df02012-06-08 21:35:42 +00003773 Scope *S, CorrectionCandidateCallback &CCC,
3774 bool AfterNestedNameSpecifier) {
3775 if (AfterNestedNameSpecifier) {
3776 // For 'X::', we know exactly which keywords can appear next.
3777 Consumer.addKeywordResult("template");
3778 if (CCC.WantExpressionKeywords)
3779 Consumer.addKeywordResult("operator");
3780 return;
3781 }
3782
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003783 if (CCC.WantObjCSuper)
3784 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003785
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003786 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003787 // Add type-specifier keywords to the set of results.
Craig Topperd6d31ac2013-07-15 08:24:27 +00003788 static const char *const CTypeSpecs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003789 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00003790 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003791 "_Complex", "_Imaginary",
3792 // storage-specifiers as well
3793 "extern", "inline", "static", "typedef"
3794 };
3795
Craig Toppere5ce8312013-07-15 03:38:40 +00003796 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003797 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3798 Consumer.addKeywordResult(CTypeSpecs[I]);
3799
David Blaikiebbafb8a2012-03-11 07:00:24 +00003800 if (SemaRef.getLangOpts().C99)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003801 Consumer.addKeywordResult("restrict");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003802 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003803 Consumer.addKeywordResult("bool");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003804 else if (SemaRef.getLangOpts().C99)
Douglas Gregor3b22a882011-07-01 21:27:45 +00003805 Consumer.addKeywordResult("_Bool");
3806
David Blaikiebbafb8a2012-03-11 07:00:24 +00003807 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003808 Consumer.addKeywordResult("class");
3809 Consumer.addKeywordResult("typename");
3810 Consumer.addKeywordResult("wchar_t");
3811
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003812 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003813 Consumer.addKeywordResult("char16_t");
3814 Consumer.addKeywordResult("char32_t");
3815 Consumer.addKeywordResult("constexpr");
3816 Consumer.addKeywordResult("decltype");
3817 Consumer.addKeywordResult("thread_local");
3818 }
3819 }
3820
David Blaikiebbafb8a2012-03-11 07:00:24 +00003821 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003822 Consumer.addKeywordResult("typeof");
3823 }
3824
David Blaikiebbafb8a2012-03-11 07:00:24 +00003825 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003826 Consumer.addKeywordResult("const_cast");
3827 Consumer.addKeywordResult("dynamic_cast");
3828 Consumer.addKeywordResult("reinterpret_cast");
3829 Consumer.addKeywordResult("static_cast");
3830 }
3831
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003832 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003833 Consumer.addKeywordResult("sizeof");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003834 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003835 Consumer.addKeywordResult("false");
3836 Consumer.addKeywordResult("true");
3837 }
3838
David Blaikiebbafb8a2012-03-11 07:00:24 +00003839 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topperd6d31ac2013-07-15 08:24:27 +00003840 static const char *const CXXExprs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003841 "delete", "new", "operator", "throw", "typeid"
3842 };
Craig Toppere5ce8312013-07-15 03:38:40 +00003843 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003844 for (unsigned I = 0; I != NumCXXExprs; ++I)
3845 Consumer.addKeywordResult(CXXExprs[I]);
3846
3847 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3848 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3849 Consumer.addKeywordResult("this");
3850
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003851 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003852 Consumer.addKeywordResult("alignof");
3853 Consumer.addKeywordResult("nullptr");
3854 }
3855 }
Jordan Rose58d54722012-06-30 21:33:57 +00003856
3857 if (SemaRef.getLangOpts().C11) {
3858 // FIXME: We should not suggest _Alignof if the alignof macro
3859 // is present.
3860 Consumer.addKeywordResult("_Alignof");
3861 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003862 }
3863
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003864 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003865 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3866 // Statements.
Craig Topperd6d31ac2013-07-15 08:24:27 +00003867 static const char *const CStmts[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003868 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Toppere5ce8312013-07-15 03:38:40 +00003869 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003870 for (unsigned I = 0; I != NumCStmts; ++I)
3871 Consumer.addKeywordResult(CStmts[I]);
3872
David Blaikiebbafb8a2012-03-11 07:00:24 +00003873 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003874 Consumer.addKeywordResult("catch");
3875 Consumer.addKeywordResult("try");
3876 }
3877
3878 if (S && S->getBreakParent())
3879 Consumer.addKeywordResult("break");
3880
3881 if (S && S->getContinueParent())
3882 Consumer.addKeywordResult("continue");
3883
3884 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3885 Consumer.addKeywordResult("case");
3886 Consumer.addKeywordResult("default");
3887 }
3888 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003889 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003890 Consumer.addKeywordResult("namespace");
3891 Consumer.addKeywordResult("template");
3892 }
3893
3894 if (S && S->isClassScope()) {
3895 Consumer.addKeywordResult("explicit");
3896 Consumer.addKeywordResult("friend");
3897 Consumer.addKeywordResult("mutable");
3898 Consumer.addKeywordResult("private");
3899 Consumer.addKeywordResult("protected");
3900 Consumer.addKeywordResult("public");
3901 Consumer.addKeywordResult("virtual");
3902 }
3903 }
3904
David Blaikiebbafb8a2012-03-11 07:00:24 +00003905 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003906 Consumer.addKeywordResult("using");
3907
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003908 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003909 Consumer.addKeywordResult("static_assert");
3910 }
3911 }
3912}
3913
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003914static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3915 TypoCorrection &Candidate) {
3916 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3917 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3918}
3919
Richard Smithe156254d2013-08-20 20:35:18 +00003920/// \brief Check whether the declarations found for a typo correction are
3921/// visible, and if none of them are, convert the correction to an 'import
3922/// a module' correction.
3923static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC,
3924 DeclarationName TypoName) {
3925 if (TC.begin() == TC.end())
3926 return;
3927
3928 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3929
3930 for (/**/; DI != DE; ++DI)
3931 if (!LookupResult::isVisible(SemaRef, *DI))
3932 break;
3933 // Nothing to do if all decls are visible.
3934 if (DI == DE)
3935 return;
3936
3937 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3938 bool AnyVisibleDecls = !NewDecls.empty();
3939
3940 for (/**/; DI != DE; ++DI) {
3941 NamedDecl *VisibleDecl = *DI;
3942 if (!LookupResult::isVisible(SemaRef, *DI))
3943 VisibleDecl = findAcceptableDecl(SemaRef, *DI);
3944
3945 if (VisibleDecl) {
3946 if (!AnyVisibleDecls) {
3947 // Found a visible decl, discard all hidden ones.
3948 AnyVisibleDecls = true;
3949 NewDecls.clear();
3950 }
3951 NewDecls.push_back(VisibleDecl);
3952 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
3953 NewDecls.push_back(*DI);
3954 }
3955
3956 if (NewDecls.empty())
3957 TC = TypoCorrection();
3958 else {
3959 TC.setCorrectionDecls(NewDecls);
3960 TC.setRequiresImport(!AnyVisibleDecls);
3961 }
3962}
3963
Douglas Gregor2d435302009-12-30 17:04:44 +00003964/// \brief Try to "correct" a typo in the source code by finding
3965/// visible declarations whose names are similar to the name that was
3966/// present in the source code.
3967///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003968/// \param TypoName the \c DeclarationNameInfo structure that contains
3969/// the name that was present in the source code along with its location.
3970///
3971/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00003972///
3973/// \param S the scope in which name lookup occurs.
3974///
3975/// \param SS the nested-name-specifier that precedes the name we're
3976/// looking for, if present.
3977///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003978/// \param CCC A CorrectionCandidateCallback object that provides further
3979/// validation of typo correction candidates. It also provides flags for
3980/// determining the set of keywords permitted.
3981///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003982/// \param MemberContext if non-NULL, the context in which to look for
3983/// a member access expression.
3984///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003985/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00003986/// the nested-name-specifier SS.
3987///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003988/// \param OPT when non-NULL, the search for visible declarations will
3989/// also walk the protocols in the qualified interfaces of \p OPT.
3990///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003991/// \returns a \c TypoCorrection containing the corrected name if the typo
3992/// along with information such as the \c NamedDecl where the corrected name
3993/// was declared, and any additional \c NestedNameSpecifier needed to access
3994/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3995TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3996 Sema::LookupNameKind LookupKind,
3997 Scope *S, CXXScopeSpec *SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00003998 CorrectionCandidateCallback &CCC,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003999 DeclContext *MemberContext,
4000 bool EnteringContext,
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004001 const ObjCObjectPointerType *OPT,
4002 bool RecordFailure) {
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00004003 // Always let the ExternalSource have the first chance at correction, even
4004 // if we would otherwise have given up.
4005 if (ExternalSource) {
4006 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
4007 TypoName, LookupKind, S, SS, CCC, MemberContext, EnteringContext, OPT))
4008 return Correction;
4009 }
4010
Richard Smith1fff95c2013-09-12 23:28:08 +00004011 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4012 DisableTypoCorrection)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004013 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004014
Francois Pichet9c391132011-12-03 15:55:29 +00004015 // In Microsoft mode, don't perform typo correction in a template member
4016 // function dependent context because it interferes with the "lookup into
4017 // dependent bases of class templates" feature.
Alp Tokerbfa39342014-01-14 12:51:41 +00004018 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
Francois Pichet9c391132011-12-03 15:55:29 +00004019 isa<CXXMethodDecl>(CurContext))
4020 return TypoCorrection();
4021
Douglas Gregor2d435302009-12-30 17:04:44 +00004022 // We only attempt to correct typos for identifiers.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004023 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor2d435302009-12-30 17:04:44 +00004024 if (!Typo)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004025 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00004026
4027 // If the scope specifier itself was invalid, don't try to correct
4028 // typos.
4029 if (SS && SS->isInvalid())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004030 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00004031
4032 // Never try to correct typos during template deduction or
4033 // instantiation.
4034 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004035 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004036
Argyrios Kyrtzidis3e56dd42013-03-14 22:56:43 +00004037 // Don't try to correct 'super'.
4038 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4039 return TypoCorrection();
4040
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004041 // Abort if typo correction already failed for this specific typo.
4042 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4043 if (locs != TypoCorrectionFailures.end() &&
Aaron Ballman7fc6e1b2013-10-05 19:56:07 +00004044 locs->second.count(TypoName.getLoc()))
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004045 return TypoCorrection();
4046
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004047 // Don't try to correct the identifier "vector" when in AltiVec mode.
4048 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4049 // remove this workaround.
4050 if (getLangOpts().AltiVec && Typo->isStr("vector"))
4051 return TypoCorrection();
4052
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004053 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004054
4055 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004056
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00004057 // If a callback object considers an empty typo correction candidate to be
4058 // viable, assume it does not do any actual validation of the candidates.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004059 TypoCorrection EmptyCorrection;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00004060 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004061
Douglas Gregor280e1ee2010-04-14 20:04:41 +00004062 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor87074f12010-10-20 01:32:02 +00004063 bool IsUnqualifiedLookup = false;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004064 DeclContext *QualifiedDC = MemberContext;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004065 if (MemberContext) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004066 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004067
4068 // Look in qualified interfaces.
4069 if (OPT) {
Aaron Ballman83731462014-03-17 16:14:00 +00004070 for (auto *I : OPT->quals())
4071 LookupVisibleDecls(I, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004072 }
4073 } else if (SS && SS->isSet()) {
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004074 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4075 if (!QualifiedDC)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004076 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004077
Douglas Gregor87074f12010-10-20 01:32:02 +00004078 // Provide a stop gap for files that are just seriously broken. Trying
4079 // to correct all typos can turn into a HUGE performance penalty, causing
4080 // some files to take minutes to get rejected by the parser.
4081 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004082 return TypoCorrection();
Douglas Gregor87074f12010-10-20 01:32:02 +00004083 ++TyposCorrected;
4084
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004085 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
Douglas Gregor2d435302009-12-30 17:04:44 +00004086 } else {
Douglas Gregor87074f12010-10-20 01:32:02 +00004087 IsUnqualifiedLookup = true;
4088 UnqualifiedTyposCorrectedMap::iterator Cached
4089 = UnqualifiedTyposCorrected.find(Typo);
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004090 if (Cached != UnqualifiedTyposCorrected.end()) {
4091 // Add the cached value, unless it's a keyword or fails validation. In the
4092 // keyword case, we'll end up adding the keyword below.
4093 if (Cached->second) {
4094 if (!Cached->second.isKeyword() &&
Serge Pavlovc0cd80f2013-10-14 14:05:48 +00004095 isCandidateViable(CCC, Cached->second)) {
4096 // Do not use correction that is unaccessible in the given scope.
Serge Pavlove8ae13f2013-10-15 14:24:32 +00004097 NamedDecl *CorrectionDecl = Cached->second.getCorrectionDecl();
Serge Pavlovc0cd80f2013-10-14 14:05:48 +00004098 DeclarationNameInfo NameInfo(CorrectionDecl->getDeclName(),
4099 CorrectionDecl->getLocation());
4100 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4101 if (LookupName(R, S))
4102 Consumer.addCorrection(Cached->second);
4103 }
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004104 } else {
4105 // Only honor no-correction cache hits when a callback that will validate
4106 // correction candidates is not being used.
4107 if (!ValidatingCallback)
4108 return TypoCorrection();
4109 }
4110 }
4111 if (Cached == UnqualifiedTyposCorrected.end()) {
Douglas Gregor87074f12010-10-20 01:32:02 +00004112 // Provide a stop gap for files that are just seriously broken. Trying
4113 // to correct all typos can turn into a HUGE performance penalty, causing
4114 // some files to take minutes to get rejected by the parser.
4115 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004116 return TypoCorrection();
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004117 }
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004118 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004119
Douglas Gregorb11f9452012-03-26 16:54:18 +00004120 // Determine whether we are going to search in the various namespaces for
4121 // corrections.
4122 bool SearchNamespaces
Kaelyn Uhrainf4657d52012-04-03 18:20:11 +00004123 = getLangOpts().CPlusPlus &&
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00004124 (IsUnqualifiedLookup || (SS && SS->isSet()));
Richard Smithe156254d2013-08-20 20:35:18 +00004125 // In a few cases we *only* want to search for corrections based on just
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004126 // adding or changing the nested name specifier.
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004127 unsigned TypoLen = Typo->getName().size();
4128 bool AllowOnlyNNSChanges = TypoLen < 3;
4129
Douglas Gregorb11f9452012-03-26 16:54:18 +00004130 if (IsUnqualifiedLookup || SearchNamespaces) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004131 // For unqualified lookup, look through all of the names that we have
4132 // seen in this translation unit.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00004133 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004134 for (IdentifierTable::iterator I = Context.Idents.begin(),
4135 IEnd = Context.Idents.end();
4136 I != IEnd; ++I)
4137 Consumer.FoundName(I->getKey());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004138
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004139 // Walk through identifiers in external identifier sources.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00004140 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004141 if (IdentifierInfoLookup *External
4142 = Context.Idents.getExternalIdentifierLookup()) {
Ahmed Charlesb8984322014-03-07 20:03:18 +00004143 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004144 do {
4145 StringRef Name = Iter->Next();
4146 if (Name.empty())
4147 break;
Douglas Gregor57756ea2010-10-14 22:11:03 +00004148
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004149 Consumer.FoundName(Name);
4150 } while (true);
Douglas Gregor57756ea2010-10-14 22:11:03 +00004151 }
Douglas Gregor2d435302009-12-30 17:04:44 +00004152 }
4153
Richard Smithb3a1df02012-06-08 21:35:42 +00004154 AddKeywordsToConsumer(*this, Consumer, S, CCC, SS && SS->isNotEmpty());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004155
Douglas Gregor280e1ee2010-04-14 20:04:41 +00004156 // If we haven't found anything, we're done.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004157 if (Consumer.empty())
4158 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4159 IsUnqualifiedLookup);
Douglas Gregor2d435302009-12-30 17:04:44 +00004160
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004161 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4162 // is not more that about a third of the length of the typo's identifier.
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00004163 unsigned ED = Consumer.getBestEditDistance(true);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004164 if (ED > 0 && TypoLen / ED < 3)
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004165 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4166 IsUnqualifiedLookup);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004167
Douglas Gregorb11f9452012-03-26 16:54:18 +00004168 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4169 // to search those namespaces.
4170 if (SearchNamespaces) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004171 // Load any externally-known namespaces.
4172 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004173 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004174 LoadedExternalKnownNamespaces = true;
4175 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4176 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
4177 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
4178 }
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004179
4180 for (llvm::MapVector<NamespaceDecl*, bool>::iterator
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004181 KNI = KnownNamespaces.begin(),
4182 KNIEnd = KnownNamespaces.end();
4183 KNI != KNIEnd; ++KNI)
Kaelyn Uhrain5315a462013-10-19 00:04:49 +00004184 Namespaces.AddNameSpecifier(KNI->first);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004185
Kaelyn Uhrain0e353552014-02-09 21:47:04 +00004186 bool SSIsTemplate = false;
4187 if (NestedNameSpecifier *NNS =
4188 (SS && SS->isValid()) ? SS->getScopeRep() : 0) {
4189 if (const Type *T = NNS->getAsType())
4190 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
4191 }
Aaron Ballmane42430e2014-03-14 21:11:14 +00004192 for (const auto *TI : Context.types()) {
4193 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
Kaelyn Uhrain5315a462013-10-19 00:04:49 +00004194 CD = CD->getCanonicalDecl();
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004195 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
Kaelyn Uhrain21a66172014-02-05 18:57:51 +00004196 !CD->isUnion() && CD->getIdentifier() &&
Kaelyn Uhrain0e353552014-02-09 21:47:04 +00004197 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
Kaelyn Uhrain5315a462013-10-19 00:04:49 +00004198 (CD->isBeingDefined() || CD->isCompleteDefinition()))
4199 Namespaces.AddNameSpecifier(CD);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004200 }
4201 }
Douglas Gregor87074f12010-10-20 01:32:02 +00004202 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004203
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004204 // Weed out any names that could not be found by name lookup or, if a
4205 // CorrectionCandidateCallback object was provided, failed validation.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004206 SmallVector<TypoCorrection, 16> QualifiedResults;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004207 LookupResult TmpRes(*this, TypoName, LookupKind);
4208 TmpRes.suppressDiagnostics();
4209 while (!Consumer.empty()) {
4210 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
Benjamin Kramer73faad62012-04-14 08:26:28 +00004211 for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(),
4212 IEnd = DI->second.end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004213 I != IEnd; /* Increment in loop. */) {
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004214 // If we only want nested name specifier corrections, ignore potential
4215 // corrections that have a different base identifier from the typo.
4216 if (AllowOnlyNNSChanges &&
4217 I->second.front().getCorrectionAsIdentifierInfo() != Typo) {
4218 TypoCorrectionConsumer::result_iterator Prev = I;
4219 ++I;
4220 DI->second.erase(Prev);
4221 continue;
4222 }
4223
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004224 // If the item already has been looked up or is a keyword, keep it.
4225 // If a validator callback object was given, drop the correction
4226 // unless it passes validation.
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004227 bool Viable = false;
Benjamin Kramera2dcac12012-07-27 10:21:08 +00004228 for (TypoResultList::iterator RI = I->second.begin();
4229 RI != I->second.end(); /* Increment in loop. */) {
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004230 TypoResultList::iterator Prev = RI;
4231 ++RI;
4232 if (Prev->isResolved()) {
4233 if (!isCandidateViable(CCC, *Prev))
Benjamin Kramera2dcac12012-07-27 10:21:08 +00004234 RI = I->second.erase(Prev);
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004235 else
4236 Viable = true;
4237 }
4238 }
4239 if (Viable || I->second.empty()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004240 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004241 ++I;
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004242 if (!Viable)
Benjamin Kramer73faad62012-04-14 08:26:28 +00004243 DI->second.erase(Prev);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004244 continue;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004245 }
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004246 assert(I->second.size() == 1 && "Expected a single unresolved candidate");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004247
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004248 // Perform name lookup on this name.
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004249 TypoCorrection &Candidate = I->second.front();
4250 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00004251 DeclContext *TempMemberContext = MemberContext;
4252 CXXScopeSpec *TempSS = SS;
4253retry_lookup:
4254 LookupPotentialTypoResult(*this, TmpRes, Name, S, TempSS,
4255 TempMemberContext, EnteringContext,
Richard Smithe156254d2013-08-20 20:35:18 +00004256 CCC.IsObjCIvarLookup,
4257 Name == TypoName.getName() &&
4258 !Candidate.WillReplaceSpecifier());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004259
4260 switch (TmpRes.getResultKind()) {
4261 case LookupResult::NotFound:
4262 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain5a43b462011-09-07 20:25:59 +00004263 case LookupResult::FoundUnresolvedValue:
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00004264 if (TempSS) {
4265 // Immediately retry the lookup without the given CXXScopeSpec
4266 TempSS = NULL;
4267 Candidate.WillReplaceSpecifier(true);
4268 goto retry_lookup;
4269 }
4270 if (TempMemberContext) {
4271 if (SS && !TempSS)
4272 TempSS = SS;
4273 TempMemberContext = NULL;
4274 goto retry_lookup;
4275 }
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004276 QualifiedResults.push_back(Candidate);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004277 // We didn't find this name in our scope, or didn't like what we found;
4278 // ignore it.
4279 {
4280 TypoCorrectionConsumer::result_iterator Next = I;
4281 ++Next;
Benjamin Kramer73faad62012-04-14 08:26:28 +00004282 DI->second.erase(I);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004283 I = Next;
4284 }
4285 break;
4286
4287 case LookupResult::Ambiguous:
4288 // We don't deal with ambiguities.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004289 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004290
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004291 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004292 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004293 // Store all of the Decls for overloaded symbols
4294 for (LookupResult::iterator TRD = TmpRes.begin(),
4295 TRDEnd = TmpRes.end();
4296 TRD != TRDEnd; ++TRD)
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004297 Candidate.addCorrectionDecl(*TRD);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004298 ++I;
Kaelyn Uhrainb18b0c02013-07-02 23:47:35 +00004299 if (!isCandidateViable(CCC, Candidate)) {
4300 QualifiedResults.push_back(Candidate);
Benjamin Kramer73faad62012-04-14 08:26:28 +00004301 DI->second.erase(Prev);
Kaelyn Uhrainb18b0c02013-07-02 23:47:35 +00004302 }
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004303 break;
4304 }
4305
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004306 case LookupResult::Found: {
4307 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004308 Candidate.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004309 ++I;
Kaelyn Uhrainb18b0c02013-07-02 23:47:35 +00004310 if (!isCandidateViable(CCC, Candidate)) {
4311 QualifiedResults.push_back(Candidate);
Benjamin Kramer73faad62012-04-14 08:26:28 +00004312 DI->second.erase(Prev);
Kaelyn Uhrainb18b0c02013-07-02 23:47:35 +00004313 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004314 break;
4315 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004316
4317 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004318 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004319
Benjamin Kramer73faad62012-04-14 08:26:28 +00004320 if (DI->second.empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004321 Consumer.erase(DI);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004322 else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !DI->first)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004323 // If there are results in the closest possible bucket, stop
4324 break;
4325
4326 // Only perform the qualified lookups for C++
Douglas Gregorb11f9452012-03-26 16:54:18 +00004327 if (SearchNamespaces) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004328 TmpRes.suppressDiagnostics();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004329 for (SmallVector<TypoCorrection,
4330 16>::iterator QRI = QualifiedResults.begin(),
4331 QRIEnd = QualifiedResults.end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004332 QRI != QRIEnd; ++QRI) {
4333 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
4334 NIEnd = Namespaces.end();
4335 NI != NIEnd; ++NI) {
4336 DeclContext *Ctx = NI->DeclCtx;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004337 const Type *NSType = NI->NameSpecifier->getAsType();
4338
4339 // If the current NestedNameSpecifier refers to a class and the
4340 // current correction candidate is the name of that class, then skip
4341 // it as it is unlikely a qualified version of the class' constructor
4342 // is an appropriate correction.
4343 if (CXXRecordDecl *NSDecl =
4344 NSType ? NSType->getAsCXXRecordDecl() : 0) {
4345 if (NSDecl->getIdentifier() == QRI->getCorrectionAsIdentifierInfo())
4346 continue;
4347 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004348
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004349 TypoCorrection TC(*QRI);
4350 TC.ClearCorrectionDecls();
4351 TC.setCorrectionSpecifier(NI->NameSpecifier);
4352 TC.setQualifierDistance(NI->EditDistance);
4353 TC.setCallbackDistance(0); // Reset the callback distance
4354
4355 // If the current correction candidate and namespace combination are
4356 // too far away from the original typo based on the normalized edit
4357 // distance, then skip performing a qualified name lookup.
4358 unsigned TmpED = TC.getEditDistance(true);
4359 if (QRI->getCorrectionAsIdentifierInfo() != Typo &&
4360 TmpED && TypoLen / TmpED < 3)
4361 continue;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004362
4363 TmpRes.clear();
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00004364 TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004365 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
4366
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004367 // Any corrections added below will be validated in subsequent
4368 // iterations of the main while() loop over the Consumer's contents.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004369 switch (TmpRes.getResultKind()) {
Kaelyn Uhrainb18b0c02013-07-02 23:47:35 +00004370 case LookupResult::Found:
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004371 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00004372 if (SS && SS->isValid()) {
4373 std::string NewQualified = TC.getAsString(getLangOpts());
4374 std::string OldQualified;
4375 llvm::raw_string_ostream OldOStream(OldQualified);
4376 SS->getScopeRep()->print(OldOStream, getPrintingPolicy());
4377 OldOStream << TypoName;
4378 // If correction candidate would be an identical written qualified
4379 // identifer, then the existing CXXScopeSpec probably included a
4380 // typedef that didn't get accounted for properly.
4381 if (OldOStream.str() == NewQualified)
4382 break;
4383 }
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004384 for (LookupResult::iterator TRD = TmpRes.begin(),
4385 TRDEnd = TmpRes.end();
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004386 TRD != TRDEnd; ++TRD) {
4387 if (CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4388 NSType ? NSType->getAsCXXRecordDecl() : 0,
Eli Friedman3be1a1c2013-10-01 02:44:48 +00004389 TRD.getPair()) == AR_accessible)
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004390 TC.addCorrectionDecl(*TRD);
4391 }
4392 if (TC.isResolved())
4393 Consumer.addCorrection(TC);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004394 break;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004395 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004396 case LookupResult::NotFound:
4397 case LookupResult::NotFoundInCurrentInstantiation:
4398 case LookupResult::Ambiguous:
Kaelyn Uhrain5a43b462011-09-07 20:25:59 +00004399 case LookupResult::FoundUnresolvedValue:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004400 break;
4401 }
4402 }
4403 }
4404 }
4405
4406 QualifiedResults.clear();
4407 }
4408
4409 // No corrections remain...
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004410 if (Consumer.empty())
4411 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004412
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00004413 TypoResultsMap &BestResults = Consumer.getBestResults();
4414 ED = Consumer.getBestEditDistance(true);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004415
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004416 if (!AllowOnlyNNSChanges && ED > 0 && TypoLen / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004417 // If this was an unqualified lookup and we believe the callback
4418 // object wouldn't have filtered out possible corrections, note
4419 // that no correction was found.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004420 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4421 IsUnqualifiedLookup && !ValidatingCallback);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004422 }
4423
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004424 // If only a single name remains, return that result.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004425 if (BestResults.size() == 1) {
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004426 const TypoResultList &CorrectionList = BestResults.begin()->second;
4427 const TypoCorrection &Result = CorrectionList.front();
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004428 if (CorrectionList.size() != 1)
4429 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004430
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00004431 // Don't correct to a keyword that's the same as the typo; the keyword
4432 // wasn't actually in scope.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004433 if (ED == 0 && Result.isKeyword())
4434 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004435
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004436 // Record the correction for unqualified lookup.
4437 if (IsUnqualifiedLookup)
4438 UnqualifiedTyposCorrected[Typo] = Result;
4439
David Blaikie04ea41c2012-10-12 20:00:44 +00004440 TypoCorrection TC = Result;
4441 TC.setCorrectionRange(SS, TypoName);
Richard Smithe156254d2013-08-20 20:35:18 +00004442 checkCorrectionVisibility(*this, TC, TypoName.getName());
David Blaikie04ea41c2012-10-12 20:00:44 +00004443 return TC;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004444 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004445 else if (BestResults.size() > 1
4446 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4447 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4448 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4449 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00004450 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004451 && BestResults["super"].front().isKeyword()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004452 // Prefer 'super' when we're completing in a message-receiver
4453 // context.
4454
4455 // Don't correct to a keyword that's the same as the typo; the keyword
4456 // wasn't actually in scope.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004457 if (ED == 0)
4458 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004459
Douglas Gregor87074f12010-10-20 01:32:02 +00004460 // Record the correction for unqualified lookup.
4461 if (IsUnqualifiedLookup)
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004462 UnqualifiedTyposCorrected[Typo] = BestResults["super"].front();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004463
David Blaikie04ea41c2012-10-12 20:00:44 +00004464 TypoCorrection TC = BestResults["super"].front();
4465 TC.setCorrectionRange(SS, TypoName);
4466 return TC;
Douglas Gregoraf9eb592010-10-15 13:35:25 +00004467 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004468
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004469 // If this was an unqualified lookup and we believe the callback object did
4470 // not filter out possible corrections, note that no correction was found.
4471 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregor87074f12010-10-20 01:32:02 +00004472 (void)UnqualifiedTyposCorrected[Typo];
4473
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004474 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004475}
4476
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004477void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4478 if (!CDecl) return;
4479
4480 if (isKeyword())
4481 CorrectionDecls.clear();
4482
Kaelyn Uhrainf60b55a2012-11-19 18:49:53 +00004483 CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004484
4485 if (!CorrectionName)
4486 CorrectionName = CDecl->getDeclName();
4487}
4488
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004489std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4490 if (CorrectionNameSpec) {
4491 std::string tmpBuffer;
4492 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4493 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikied4da8722013-05-14 21:04:00 +00004494 PrefixOStream << CorrectionName;
Benjamin Kramer73faad62012-04-14 08:26:28 +00004495 return PrefixOStream.str();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004496 }
4497
4498 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00004499}
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004500
4501bool CorrectionCandidateCallback::ValidateCandidate(const TypoCorrection &candidate) {
4502 if (!candidate.isResolved())
4503 return true;
4504
4505 if (candidate.isKeyword())
4506 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4507 WantRemainingKeywords || WantObjCSuper;
4508
4509 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
4510 CDeclEnd = candidate.end();
4511 CDecl != CDeclEnd; ++CDecl) {
4512 if (!isa<TypeDecl>(*CDecl))
4513 return true;
4514 }
4515
4516 return WantTypeSpecifiers;
4517}
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004518
4519FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004520 bool HasExplicitTemplateArgs,
4521 bool AllowNonStaticMethods)
4522 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
4523 AllowNonStaticMethods(AllowNonStaticMethods),
4524 CurContext(SemaRef.CurContext) {
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004525 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
4526 WantRemainingKeywords = false;
4527}
4528
4529bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4530 if (!candidate.getCorrectionDecl())
4531 return candidate.isKeyword();
4532
4533 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
4534 DIEnd = candidate.end();
4535 DI != DIEnd; ++DI) {
4536 FunctionDecl *FD = 0;
4537 NamedDecl *ND = (*DI)->getUnderlyingDecl();
4538 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4539 FD = FTD->getTemplatedDecl();
4540 if (!HasExplicitTemplateArgs && !FD) {
4541 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4542 // If the Decl is neither a function nor a template function,
4543 // determine if it is a pointer or reference to a function. If so,
4544 // check against the number of arguments expected for the pointee.
4545 QualType ValType = cast<ValueDecl>(ND)->getType();
4546 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4547 ValType = ValType->getPointeeType();
4548 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
Alp Toker9cacbab2014-01-20 20:26:09 +00004549 if (FPT->getNumParams() == NumArgs)
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004550 return true;
4551 }
4552 }
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004553
4554 // Skip the current candidate if it is not a FunctionDecl or does not accept
4555 // the current number of arguments.
4556 if (!FD || !(FD->getNumParams() >= NumArgs &&
4557 FD->getMinRequiredArguments() <= NumArgs))
4558 continue;
4559
4560 // If the current candidate is a non-static C++ method and non-static
4561 // methods are being excluded, then skip the candidate unless the current
4562 // DeclContext is a method in the same class or a descendent class of the
4563 // candidate's parent class.
4564 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
4565 if (!AllowNonStaticMethods && !MD->isStatic()) {
4566 CXXMethodDecl *CurMD = dyn_cast_or_null<CXXMethodDecl>(CurContext);
4567 CXXRecordDecl *CurRD =
4568 CurMD ? CurMD->getParent()->getCanonicalDecl() : 0;
4569 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
4570 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
4571 continue;
4572 }
4573 }
4574 return true;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004575 }
4576 return false;
4577}
Richard Smithf9b15102013-08-17 00:46:16 +00004578
4579void Sema::diagnoseTypo(const TypoCorrection &Correction,
4580 const PartialDiagnostic &TypoDiag,
4581 bool ErrorRecovery) {
4582 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
4583 ErrorRecovery);
4584}
4585
Richard Smithe156254d2013-08-20 20:35:18 +00004586/// Find which declaration we should import to provide the definition of
4587/// the given declaration.
4588static const NamedDecl *getDefinitionToImport(const NamedDecl *D) {
4589 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4590 return VD->getDefinition();
4591 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4592 return FD->isDefined(FD) ? FD : 0;
4593 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
4594 return TD->getDefinition();
4595 if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
4596 return ID->getDefinition();
4597 if (const ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
4598 return PD->getDefinition();
4599 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
4600 return getDefinitionToImport(TD->getTemplatedDecl());
4601 return 0;
4602}
4603
Richard Smithf9b15102013-08-17 00:46:16 +00004604/// \brief Diagnose a successfully-corrected typo. Separated from the correction
4605/// itself to allow external validation of the result, etc.
4606///
4607/// \param Correction The result of performing typo correction.
4608/// \param TypoDiag The diagnostic to produce. This will have the corrected
4609/// string added to it (and usually also a fixit).
4610/// \param PrevNote A note to use when indicating the location of the entity to
4611/// which we are correcting. Will have the correction string added to it.
4612/// \param ErrorRecovery If \c true (the default), the caller is going to
4613/// recover from the typo as if the corrected string had been typed.
4614/// In this case, \c PDiag must be an error, and we will attach a fixit
4615/// to it.
4616void Sema::diagnoseTypo(const TypoCorrection &Correction,
4617 const PartialDiagnostic &TypoDiag,
4618 const PartialDiagnostic &PrevNote,
4619 bool ErrorRecovery) {
4620 std::string CorrectedStr = Correction.getAsString(getLangOpts());
4621 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
4622 FixItHint FixTypo = FixItHint::CreateReplacement(
4623 Correction.getCorrectionRange(), CorrectedStr);
4624
Richard Smithe156254d2013-08-20 20:35:18 +00004625 // Maybe we're just missing a module import.
4626 if (Correction.requiresImport()) {
4627 NamedDecl *Decl = Correction.getCorrectionDecl();
4628 assert(Decl && "import required but no declaration to import");
4629
4630 // Suggest importing a module providing the definition of this entity, if
4631 // possible.
4632 const NamedDecl *Def = getDefinitionToImport(Decl);
4633 if (!Def)
4634 Def = Decl;
4635 Module *Owner = Def->getOwningModule();
4636 assert(Owner && "definition of hidden declaration is not in a module");
4637
4638 Diag(Correction.getCorrectionRange().getBegin(),
4639 diag::err_module_private_declaration)
4640 << Def << Owner->getFullModuleName();
4641 Diag(Def->getLocation(), diag::note_previous_declaration);
4642
4643 // Recover by implicitly importing this module.
4644 if (!isSFINAEContext() && ErrorRecovery)
4645 createImplicitModuleImport(Correction.getCorrectionRange().getBegin(),
4646 Owner);
4647 return;
4648 }
4649
Richard Smithf9b15102013-08-17 00:46:16 +00004650 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
4651 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
4652
4653 NamedDecl *ChosenDecl =
4654 Correction.isKeyword() ? 0 : Correction.getCorrectionDecl();
4655 if (PrevNote.getDiagID() && ChosenDecl)
4656 Diag(ChosenDecl->getLocation(), PrevNote)
4657 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
4658}