blob: 779d2d48e70bf3ff136f14f3e0974662969534f8 [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;
Richard Smith83e78f52014-04-11 01:03:38 +0000247
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000248 case Sema::LookupLabel:
249 IDNS = Decl::IDNS_Label;
250 break;
Richard Smith83e78f52014-04-11 01:03:38 +0000251
Douglas Gregor889ceb72009-02-03 19:21:40 +0000252 case Sema::LookupMemberName:
253 IDNS = Decl::IDNS_Member;
254 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000255 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000256 break;
257
258 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000259 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
260 break;
261
Douglas Gregor889ceb72009-02-03 19:21:40 +0000262 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000263 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000264 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000265
John McCall84d87672009-12-10 09:41:52 +0000266 case Sema::LookupUsingDeclName:
Richard Smith83e78f52014-04-11 01:03:38 +0000267 assert(Redeclaration && "should only be used for redecl lookup");
268 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |
269 Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend |
270 Decl::IDNS_LocalExtern;
John McCall84d87672009-12-10 09:41:52 +0000271 break;
272
Douglas Gregor79947a22009-04-24 00:11:27 +0000273 case Sema::LookupObjCProtocolName:
274 IDNS = Decl::IDNS_ObjCProtocol;
275 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000276
Douglas Gregor39982192010-08-15 06:18:01 +0000277 case Sema::LookupAnyName:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000278 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
Douglas Gregor39982192010-08-15 06:18:01 +0000279 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
280 | Decl::IDNS_Type;
281 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000282 }
283 return IDNS;
284}
285
John McCallea305ed2009-12-18 10:40:03 +0000286void LookupResult::configure() {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000287 IDNS = getIDNS(LookupKind, SemaRef.getLangOpts().CPlusPlus,
John McCallea305ed2009-12-18 10:40:03 +0000288 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000289
Richard Smithbdd14642014-02-04 01:14:30 +0000290 // If we're looking for one of the allocation or deallocation
291 // operators, make sure that the implicitly-declared new and delete
292 // operators can be found.
293 switch (NameInfo.getName().getCXXOverloadedOperator()) {
294 case OO_New:
295 case OO_Delete:
296 case OO_Array_New:
297 case OO_Array_Delete:
298 SemaRef.DeclareGlobalNewDelete();
299 break;
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000300
Richard Smithbdd14642014-02-04 01:14:30 +0000301 default:
302 break;
303 }
Douglas Gregor15197662013-04-03 23:06:26 +0000304
Richard Smithbdd14642014-02-04 01:14:30 +0000305 // Compiler builtins are always visible, regardless of where they end
306 // up being declared.
307 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
308 if (unsigned BuiltinID = Id->getBuiltinID()) {
309 if (!SemaRef.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
310 AllowHidden = true;
Douglas Gregor15197662013-04-03 23:06:26 +0000311 }
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000312 }
John McCallea305ed2009-12-18 10:40:03 +0000313}
314
Alp Tokerc1086762013-12-07 13:51:35 +0000315bool LookupResult::sanity() const {
Richard Smithf97ad222014-04-01 18:33:50 +0000316 // This function is never called by NDEBUG builds.
John McCall19c1bfd2010-08-25 05:32:35 +0000317 assert(ResultKind != NotFound || Decls.size() == 0);
318 assert(ResultKind != Found || Decls.size() == 1);
319 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
320 (Decls.size() == 1 &&
321 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
322 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
323 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000324 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
325 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall19c1bfd2010-08-25 05:32:35 +0000326 assert((Paths != NULL) == (ResultKind == Ambiguous &&
327 (Ambiguity == AmbiguousBaseSubobjectTypes ||
328 Ambiguity == AmbiguousBaseSubobjects)));
Alp Tokerc1086762013-12-07 13:51:35 +0000329 return true;
John McCall19c1bfd2010-08-25 05:32:35 +0000330}
John McCall19c1bfd2010-08-25 05:32:35 +0000331
John McCall9f3059a2009-10-09 21:13:30 +0000332// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000333void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000334 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000335}
336
Richard Smith3876cc82013-10-30 01:02:04 +0000337/// Get a representative context for a declaration such that two declarations
338/// will have the same context if they were found within the same scope.
Benjamin Kramerfc58b042013-11-01 11:50:55 +0000339static DeclContext *getContextForScopeMatching(Decl *D) {
Richard Smith3876cc82013-10-30 01:02:04 +0000340 // For function-local declarations, use that function as the context. This
341 // doesn't account for scopes within the function; the caller must deal with
342 // those.
343 DeclContext *DC = D->getLexicalDeclContext();
344 if (DC->isFunctionOrMethod())
345 return DC;
346
347 // Otherwise, look at the semantic context of the declaration. The
348 // declaration must have been found there.
349 return D->getDeclContext()->getRedeclContext();
350}
351
John McCall283b9012009-11-22 00:44:51 +0000352/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000353void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000354 unsigned N = Decls.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000355
John McCall9f3059a2009-10-09 21:13:30 +0000356 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000357 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000358 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000359 return;
360 }
361
John McCall283b9012009-11-22 00:44:51 +0000362 // If there's a single decl, we need to examine it to decide what
363 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000364 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000365 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
366 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000367 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000368 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000369 ResultKind = FoundUnresolvedValue;
370 return;
371 }
John McCall9f3059a2009-10-09 21:13:30 +0000372
John McCall6538c932009-10-10 05:48:19 +0000373 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000374 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000375
John McCall9f3059a2009-10-09 21:13:30 +0000376 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor13e65872010-08-11 14:45:53 +0000377 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000378
John McCall9f3059a2009-10-09 21:13:30 +0000379 bool Ambiguous = false;
380 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000381 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000382
383 unsigned UniqueTagIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000384
John McCall9f3059a2009-10-09 21:13:30 +0000385 unsigned I = 0;
386 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000387 NamedDecl *D = Decls[I]->getUnderlyingDecl();
388 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000389
Argyrios Kyrtzidis1fcd7fd2013-02-22 06:58:37 +0000390 // Ignore an invalid declaration unless it's the only one left.
391 if (D->isInvalidDecl() && I < N-1) {
392 Decls[I] = Decls[--N];
393 continue;
394 }
395
Douglas Gregor13e65872010-08-11 14:45:53 +0000396 // Redeclarations of types via typedef can occur both within a scope
397 // and, through using declarations and directives, across scopes. There is
398 // no ambiguity if they all refer to the same type, so unique based on the
399 // canonical type.
400 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
401 if (!TD->getDeclContext()->isRecord()) {
402 QualType T = SemaRef.Context.getTypeDeclType(TD);
403 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
404 // The type is not unique; pull something off the back and continue
405 // at this index.
406 Decls[I] = Decls[--N];
407 continue;
408 }
409 }
410 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000411
John McCallf0f1cf02009-11-17 07:50:12 +0000412 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000413 // If it's not unique, pull something off the back (and
414 // continue at this index).
415 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000416 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000417 }
418
Douglas Gregor13e65872010-08-11 14:45:53 +0000419 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000420
Douglas Gregor13e65872010-08-11 14:45:53 +0000421 if (isa<UnresolvedUsingValueDecl>(D)) {
422 HasUnresolved = true;
423 } else if (isa<TagDecl>(D)) {
424 if (HasTag)
425 Ambiguous = true;
426 UniqueTagIndex = I;
427 HasTag = true;
428 } else if (isa<FunctionTemplateDecl>(D)) {
429 HasFunction = true;
430 HasFunctionTemplate = true;
431 } else if (isa<FunctionDecl>(D)) {
432 HasFunction = true;
433 } else {
434 if (HasNonFunction)
435 Ambiguous = true;
436 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000437 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000438 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000439 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000440
John McCall9f3059a2009-10-09 21:13:30 +0000441 // C++ [basic.scope.hiding]p2:
442 // A class name or enumeration name can be hidden by the name of
443 // an object, function, or enumerator declared in the same
444 // scope. If a class or enumeration name and an object, function,
445 // or enumerator are declared in the same scope (in any order)
446 // with the same name, the class or enumeration name is hidden
447 // wherever the object, function, or enumerator name is visible.
448 // But it's still an error if there are distinct tag types found,
449 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000450 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000451 (HasFunction || HasNonFunction || HasUnresolved)) {
Richard Smith3876cc82013-10-30 01:02:04 +0000452 if (getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
453 getContextForScopeMatching(Decls[UniqueTagIndex ? 0 : N - 1])))
Douglas Gregore63d0872010-10-23 16:06:17 +0000454 Decls[UniqueTagIndex] = Decls[--N];
455 else
456 Ambiguous = true;
457 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000458
John McCall9f3059a2009-10-09 21:13:30 +0000459 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000460
John McCall80053822009-12-03 00:58:24 +0000461 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000462 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000463
John McCall9f3059a2009-10-09 21:13:30 +0000464 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000465 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000466 else if (HasUnresolved)
467 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000468 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000469 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000470 else
John McCall27b18f82009-11-17 02:14:36 +0000471 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000472}
473
John McCall5cebab12009-11-18 07:57:50 +0000474void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000475 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000476 for (I = P.begin(), E = P.end(); I != E; ++I)
David Blaikieff7d47a2012-12-19 00:45:41 +0000477 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
478 DE = I->Decls.end(); DI != DE; ++DI)
John McCall9f3059a2009-10-09 21:13:30 +0000479 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000480}
481
John McCall5cebab12009-11-18 07:57:50 +0000482void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000483 Paths = new CXXBasePaths;
484 Paths->swap(P);
485 addDeclsFromBasePaths(*Paths);
486 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000487 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000488}
489
John McCall5cebab12009-11-18 07:57:50 +0000490void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000491 Paths = new CXXBasePaths;
492 Paths->swap(P);
493 addDeclsFromBasePaths(*Paths);
494 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000495 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000496}
497
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000498void LookupResult::print(raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000499 Out << Decls.size() << " result(s)";
500 if (isAmbiguous()) Out << ", ambiguous";
501 if (Paths) Out << ", base paths present";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000502
John McCall9f3059a2009-10-09 21:13:30 +0000503 for (iterator I = begin(), E = end(); I != E; ++I) {
504 Out << "\n";
505 (*I)->print(Out, 2);
506 }
507}
508
Douglas Gregord3a59182010-02-12 05:48:04 +0000509/// \brief Lookup a builtin function, when name lookup would otherwise
510/// fail.
511static bool LookupBuiltin(Sema &S, LookupResult &R) {
512 Sema::LookupNameKind NameKind = R.getLookupKind();
513
514 // If we didn't find a use of this identifier, and if the identifier
515 // corresponds to a compiler builtin, create the decl object for the builtin
516 // now, injecting it into translation unit scope, and return it.
517 if (NameKind == Sema::LookupOrdinaryName ||
518 NameKind == Sema::LookupRedeclarationWithLinkage) {
519 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
520 if (II) {
Nico Webere1687c52013-06-20 21:44:55 +0000521 if (S.getLangOpts().CPlusPlus11 && S.getLangOpts().GNUMode &&
522 II == S.getFloat128Identifier()) {
523 // libstdc++4.7's type_traits expects type __float128 to exist, so
524 // insert a dummy type to make that header build in gnu++11 mode.
525 R.addDecl(S.getASTContext().getFloat128StubType());
526 return true;
527 }
528
Douglas Gregord3a59182010-02-12 05:48:04 +0000529 // If this is a builtin on this (or all) targets, create the decl.
530 if (unsigned BuiltinID = II->getBuiltinID()) {
531 // In C++, we don't have any predefined library functions like
532 // 'malloc'. Instead, we'll just error.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000533 if (S.getLangOpts().CPlusPlus &&
Douglas Gregord3a59182010-02-12 05:48:04 +0000534 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
535 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000536
537 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
538 BuiltinID, S.TUScope,
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000539 R.isForRedeclaration(),
540 R.getNameLoc())) {
Douglas Gregord3a59182010-02-12 05:48:04 +0000541 R.addDecl(D);
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000542 return true;
543 }
Douglas Gregord3a59182010-02-12 05:48:04 +0000544 }
545 }
546 }
547
548 return false;
549}
550
Douglas Gregor7454c562010-07-02 20:37:36 +0000551/// \brief Determine whether we can declare a special member function within
552/// the class at this point.
Richard Smith7d125a12012-11-27 21:20:31 +0000553static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +0000554 // We need to have a definition for the class.
555 if (!Class->getDefinition() || Class->isDependentContext())
556 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000557
Douglas Gregor7454c562010-07-02 20:37:36 +0000558 // We can't be in the middle of defining the class.
Richard Smith7d125a12012-11-27 21:20:31 +0000559 return !Class->isBeingDefined();
Douglas Gregor7454c562010-07-02 20:37:36 +0000560}
561
562void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Richard Smith7d125a12012-11-27 21:20:31 +0000563 if (!CanDeclareSpecialMemberFunction(Class))
Douglas Gregora6d69502010-07-02 23:41:54 +0000564 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000565
566 // If the default constructor has not yet been declared, do so now.
Alexis Huntea6f0322011-05-11 22:34:38 +0000567 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +0000568 DeclareImplicitDefaultConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000569
Douglas Gregora6d69502010-07-02 23:41:54 +0000570 // If the copy constructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000571 if (Class->needsImplicitCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +0000572 DeclareImplicitCopyConstructor(Class);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000573
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000574 // If the copy assignment operator has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000575 if (Class->needsImplicitCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000576 DeclareImplicitCopyAssignment(Class);
577
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000578 if (getLangOpts().CPlusPlus11) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000579 // If the move constructor has not yet been declared, do so now.
580 if (Class->needsImplicitMoveConstructor())
581 DeclareImplicitMoveConstructor(Class); // might not actually do it
582
583 // If the move assignment operator has not yet been declared, do so now.
584 if (Class->needsImplicitMoveAssignment())
585 DeclareImplicitMoveAssignment(Class); // might not actually do it
586 }
587
Douglas Gregor7454c562010-07-02 20:37:36 +0000588 // If the destructor has not yet been declared, do so now.
Richard Smith2be35f52012-12-01 02:35:44 +0000589 if (Class->needsImplicitDestructor())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000590 DeclareImplicitDestructor(Class);
Douglas Gregor7454c562010-07-02 20:37:36 +0000591}
592
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000593/// \brief Determine whether this is the name of an implicitly-declared
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000594/// special member function.
595static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
596 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000597 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000598 case DeclarationName::CXXDestructorName:
599 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000600
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000601 case DeclarationName::CXXOperatorName:
602 return Name.getCXXOverloadedOperator() == OO_Equal;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000603
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000604 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000605 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000606 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000607
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000608 return false;
609}
610
611/// \brief If there are any implicit member functions with the given name
612/// that need to be declared in the given declaration context, do so.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000613static void DeclareImplicitMemberFunctionsWithName(Sema &S,
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000614 DeclarationName Name,
615 const DeclContext *DC) {
616 if (!DC)
617 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000618
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000619 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000620 case DeclarationName::CXXConstructorName:
621 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith7d125a12012-11-27 21:20:31 +0000622 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000623 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Alexis Huntea6f0322011-05-11 22:34:38 +0000624 if (Record->needsImplicitDefaultConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000625 S.DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +0000626 if (Record->needsImplicitCopyConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000627 S.DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000628 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000629 Record->needsImplicitMoveConstructor())
630 S.DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +0000631 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000632 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000633
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000634 case DeclarationName::CXXDestructorName:
635 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Richard Smith2be35f52012-12-01 02:35:44 +0000636 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
Richard Smith7d125a12012-11-27 21:20:31 +0000637 CanDeclareSpecialMemberFunction(Record))
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000638 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000639 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000640
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000641 case DeclarationName::CXXOperatorName:
642 if (Name.getCXXOverloadedOperator() != OO_Equal)
643 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000644
Sebastian Redl22653ba2011-08-30 19:58:05 +0000645 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
Richard Smith7d125a12012-11-27 21:20:31 +0000646 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +0000647 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
Richard Smith2be35f52012-12-01 02:35:44 +0000648 if (Record->needsImplicitCopyAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +0000649 S.DeclareImplicitCopyAssignment(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000650 if (S.getLangOpts().CPlusPlus11 &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000651 Record->needsImplicitMoveAssignment())
652 S.DeclareImplicitMoveAssignment(Class);
653 }
654 }
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000655 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000656
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000657 default:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000658 break;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000659 }
660}
Douglas Gregor7454c562010-07-02 20:37:36 +0000661
John McCall9f3059a2009-10-09 21:13:30 +0000662// Adds all qualifying matches for a name within a decl context to the
663// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000664static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000665 bool Found = false;
666
Douglas Gregor7454c562010-07-02 20:37:36 +0000667 // Lazily declare C++ special member functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000668 if (S.getLangOpts().CPlusPlus)
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000669 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000670
Douglas Gregor7454c562010-07-02 20:37:36 +0000671 // Perform lookup into this declaration context.
David Blaikieff7d47a2012-12-19 00:45:41 +0000672 DeclContext::lookup_const_result DR = DC->lookup(R.getLookupName());
673 for (DeclContext::lookup_const_iterator I = DR.begin(), E = DR.end(); I != E;
674 ++I) {
John McCall401982f2010-01-20 21:53:11 +0000675 NamedDecl *D = *I;
Douglas Gregor4a814562011-12-14 16:03:29 +0000676 if ((D = R.getAcceptableDecl(D))) {
John McCall401982f2010-01-20 21:53:11 +0000677 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000678 Found = true;
679 }
680 }
John McCall9f3059a2009-10-09 21:13:30 +0000681
Douglas Gregord3a59182010-02-12 05:48:04 +0000682 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
683 return true;
684
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000685 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000686 != DeclarationName::CXXConversionFunctionName ||
687 R.getLookupName().getCXXNameType()->isDependentType() ||
688 !isa<CXXRecordDecl>(DC))
689 return Found;
690
691 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000692 // A specialization of a conversion function template is not found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000693 // name lookup. Instead, any conversion function templates visible in the
694 // context of the use are considered. [...]
695 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
John McCallf937c022011-10-07 06:10:15 +0000696 if (!Record->isCompleteDefinition())
Chandler Carruth3a693b72010-01-31 11:44:02 +0000697 return Found;
698
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +0000699 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
700 UEnd = Record->conversion_end(); U != UEnd; ++U) {
Chandler Carruth3a693b72010-01-31 11:44:02 +0000701 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
702 if (!ConvTemplate)
703 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000704
Chandler Carruth3a693b72010-01-31 11:44:02 +0000705 // When we're performing lookup for the purposes of redeclaration, just
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000706 // add the conversion function template. When we deduce template
707 // arguments for specializations, we'll end up unifying the return
Chandler Carruth3a693b72010-01-31 11:44:02 +0000708 // type of the new declaration with the type of the function template.
709 if (R.isForRedeclaration()) {
710 R.addDecl(ConvTemplate);
711 Found = true;
712 continue;
713 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000714
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000715 // C++ [temp.mem]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000716 // [...] For each such operator, if argument deduction succeeds
717 // (14.9.2.3), the resulting specialization is used as if found by
Chandler Carruth3a693b72010-01-31 11:44:02 +0000718 // name lookup.
719 //
720 // When referencing a conversion function for any purpose other than
721 // a redeclaration (such that we'll be building an expression with the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000722 // result), perform template argument deduction and place the
Chandler Carruth3a693b72010-01-31 11:44:02 +0000723 // specialization into the result set. We do this to avoid forcing all
724 // callers to perform special deduction for conversion functions.
Craig Toppere6706e42012-09-19 02:26:47 +0000725 TemplateDeductionInfo Info(R.getNameLoc());
Chandler Carruth3a693b72010-01-31 11:44:02 +0000726 FunctionDecl *Specialization = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000727
728 const FunctionProtoType *ConvProto
Chandler Carruth3a693b72010-01-31 11:44:02 +0000729 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
730 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000731
Chandler Carruth3a693b72010-01-31 11:44:02 +0000732 // Compute the type of the function that we would expect the conversion
733 // function to have, if it were to match the name given.
734 // FIXME: Calling convention!
John McCalldb40c7f2010-12-14 08:05:40 +0000735 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
Reid Kleckner78af0702013-08-27 23:08:25 +0000736 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
Sebastian Redl7c6c9e92011-03-06 10:52:04 +0000737 EPI.ExceptionSpecType = EST_None;
John McCalldb40c7f2010-12-14 08:05:40 +0000738 EPI.NumExceptions = 0;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000739 QualType ExpectedType
740 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000741 None, EPI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000742
Chandler Carruth3a693b72010-01-31 11:44:02 +0000743 // Perform template argument deduction against the type that we would
744 // expect the function to have.
745 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
746 Specialization, Info)
747 == Sema::TDK_Success) {
748 R.addDecl(Specialization);
749 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000750 }
751 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000752
John McCall9f3059a2009-10-09 21:13:30 +0000753 return Found;
754}
755
John McCallf6c8a4e2009-11-10 07:01:13 +0000756// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000757static bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000758CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
Douglas Gregord3a59182010-02-12 05:48:04 +0000759 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000760
761 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
762
John McCallf6c8a4e2009-11-10 07:01:13 +0000763 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000764 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000765
John McCallf6c8a4e2009-11-10 07:01:13 +0000766 // Perform direct name lookup into the namespaces nominated by the
767 // using directives whose common ancestor is this namespace.
768 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000769 std::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000770
John McCallf6c8a4e2009-11-10 07:01:13 +0000771 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000772 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000773 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000774
775 R.resolveKind();
776
777 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000778}
779
780static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000781 if (DeclContext *Ctx = S->getEntity())
Douglas Gregor700792c2009-02-05 19:25:20 +0000782 return Ctx->isFileContext();
783 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000784}
Douglas Gregored8f2882009-01-30 01:04:22 +0000785
Douglas Gregor66230062010-03-15 14:33:29 +0000786// Find the next outer declaration context from this scope. This
787// routine actually returns the semantic outer context, which may
788// differ from the lexical context (encoded directly in the Scope
789// stack) when we are parsing a member of a class template. In this
790// case, the second element of the pair will be true, to indicate that
791// name lookup should continue searching in this semantic context when
792// it leaves the current template parameter scope.
793static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000794 DeclContext *DC = S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +0000795 DeclContext *Lexical = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000796 for (Scope *OuterS = S->getParent(); OuterS;
Douglas Gregor66230062010-03-15 14:33:29 +0000797 OuterS = OuterS->getParent()) {
798 if (OuterS->getEntity()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000799 Lexical = OuterS->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +0000800 break;
801 }
802 }
803
804 // C++ [temp.local]p8:
805 // In the definition of a member of a class template that appears
806 // outside of the namespace containing the class template
807 // definition, the name of a template-parameter hides the name of
808 // a member of this namespace.
809 //
810 // Example:
811 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000812 // namespace N {
813 // class C { };
Douglas Gregor66230062010-03-15 14:33:29 +0000814 //
815 // template<class T> class B {
816 // void f(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000817 // };
Douglas Gregor66230062010-03-15 14:33:29 +0000818 // }
819 //
820 // template<class C> void N::B<C>::f(C) {
821 // C b; // C is the template parameter, not N::C
822 // }
823 //
824 // In this example, the lexical context we return is the
825 // TranslationUnit, while the semantic context is the namespace N.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000826 if (!Lexical || !DC || !S->getParent() ||
Douglas Gregor66230062010-03-15 14:33:29 +0000827 !S->getParent()->isTemplateParamScope())
828 return std::make_pair(Lexical, false);
829
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000830 // Find the outermost template parameter scope.
Douglas Gregor66230062010-03-15 14:33:29 +0000831 // For the example, this is the scope for the template parameters of
832 // template<class C>.
833 Scope *OutermostTemplateScope = S->getParent();
834 while (OutermostTemplateScope->getParent() &&
835 OutermostTemplateScope->getParent()->isTemplateParamScope())
836 OutermostTemplateScope = OutermostTemplateScope->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000837
Douglas Gregor66230062010-03-15 14:33:29 +0000838 // Find the namespace context in which the original scope occurs. In
839 // the example, this is namespace N.
840 DeclContext *Semantic = DC;
841 while (!Semantic->isFileContext())
842 Semantic = Semantic->getParent();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000843
Douglas Gregor66230062010-03-15 14:33:29 +0000844 // Find the declaration context just outside of the template
845 // parameter scope. This is the context in which the template is
846 // being lexically declaration (a namespace context). In the
847 // example, this is the global scope.
848 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
849 Lexical->Encloses(Semantic))
850 return std::make_pair(Semantic, true);
851
852 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000853}
854
Richard Smith541b38b2013-09-20 01:15:31 +0000855namespace {
856/// An RAII object to specify that we want to find block scope extern
857/// declarations.
858struct FindLocalExternScope {
859 FindLocalExternScope(LookupResult &R)
860 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
861 Decl::IDNS_LocalExtern) {
862 R.setFindLocalExtern(R.getIdentifierNamespace() & Decl::IDNS_Ordinary);
863 }
864 void restore() {
865 R.setFindLocalExtern(OldFindLocalExtern);
866 }
867 ~FindLocalExternScope() {
868 restore();
869 }
870 LookupResult &R;
871 bool OldFindLocalExtern;
872};
873}
874
John McCall27b18f82009-11-17 02:14:36 +0000875bool Sema::CppLookupName(LookupResult &R, Scope *S) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000876 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000877
878 DeclarationName Name = R.getLookupName();
Richard Smith1c34fb72013-08-13 18:18:50 +0000879 Sema::LookupNameKind NameKind = R.getLookupKind();
John McCall27b18f82009-11-17 02:14:36 +0000880
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000881 // If this is the name of an implicitly-declared special member function,
882 // go through the scope stack to implicitly declare
883 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
884 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
Ted Kremenekc37877d2013-10-08 17:08:03 +0000885 if (DeclContext *DC = PreS->getEntity())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000886 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
887 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000888
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000889 // Implicitly declare member functions with the name we're looking for, if in
890 // fact we are in a scope where it matters.
891
Douglas Gregor889ceb72009-02-03 19:21:40 +0000892 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000893 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000894 I = IdResolver.begin(Name),
895 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000896
Douglas Gregor889ceb72009-02-03 19:21:40 +0000897 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000898 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000899 // ...During unqualified name lookup (3.4.1), the names appear as if
900 // they were declared in the nearest enclosing namespace which contains
901 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000902 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000903 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000904 //
905 // For example:
906 // namespace A { int i; }
907 // void foo() {
908 // int i;
909 // {
910 // using namespace A;
911 // ++i; // finds local 'i', A::i appears at global scope
912 // }
913 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000914 //
Douglas Gregorcc9406c2013-04-08 23:11:25 +0000915 UnqualUsingDirectiveSet UDirs;
916 bool VisitedUsingDirectives = false;
Richard Smith1c34fb72013-08-13 18:18:50 +0000917 bool LeftStartingScope = false;
Douglas Gregor66230062010-03-15 14:33:29 +0000918 DeclContext *OutsideOfTemplateParamDC = 0;
Richard Smith541b38b2013-09-20 01:15:31 +0000919
920 // When performing a scope lookup, we want to find local extern decls.
921 FindLocalExternScope FindLocals(R);
922
Douglas Gregor700792c2009-02-05 19:25:20 +0000923 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000924 DeclContext *Ctx = S->getEntity();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000925
Douglas Gregor889ceb72009-02-03 19:21:40 +0000926 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000927 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000928 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +0000929 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Richard Smith1c34fb72013-08-13 18:18:50 +0000930 if (NameKind == LookupRedeclarationWithLinkage) {
931 // Determine whether this (or a previous) declaration is
932 // out-of-scope.
933 if (!LeftStartingScope && !Initial->isDeclScope(*I))
934 LeftStartingScope = true;
935
936 // If we found something outside of our starting scope that
Richard Smith9a00bbf2013-10-16 21:12:00 +0000937 // does not have linkage, skip it. If it's a template parameter,
938 // we still find it, so we can diagnose the invalid redeclaration.
939 if (LeftStartingScope && !((*I)->hasLinkage()) &&
940 !(*I)->isTemplateParameter()) {
Richard Smith1c34fb72013-08-13 18:18:50 +0000941 R.setShadowed();
942 continue;
943 }
944 }
945
John McCall9f3059a2009-10-09 21:13:30 +0000946 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +0000947 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000948 }
949 }
John McCall9f3059a2009-10-09 21:13:30 +0000950 if (Found) {
951 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000952 if (S->isClassScope())
953 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
954 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000955 return true;
956 }
957
Richard Smith1c34fb72013-08-13 18:18:50 +0000958 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
Richard Smith114394f2013-08-09 04:35:01 +0000959 // C++11 [class.friend]p11:
960 // If a friend declaration appears in a local class and the name
961 // specified is an unqualified name, a prior declaration is
962 // looked up without considering scopes that are outside the
963 // innermost enclosing non-class scope.
964 return false;
965 }
966
Douglas Gregor66230062010-03-15 14:33:29 +0000967 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
968 S->getParent() && !S->getParent()->isTemplateParamScope()) {
969 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000970 // found nothing, so look into the contexts between the
Douglas Gregor66230062010-03-15 14:33:29 +0000971 // lexical and semantic declaration contexts returned by
972 // findOuterContext(). This implements the name lookup behavior
973 // of C++ [temp.local]p8.
974 Ctx = OutsideOfTemplateParamDC;
975 OutsideOfTemplateParamDC = 0;
976 }
977
978 if (Ctx) {
979 DeclContext *OuterCtx;
980 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000981 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregor66230062010-03-15 14:33:29 +0000982 if (SearchAfterTemplateScope)
983 OutsideOfTemplateParamDC = OuterCtx;
984
Douglas Gregorea166062010-03-15 15:26:48 +0000985 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000986 // We do not directly look into transparent contexts, since
987 // those entities will be found in the nearest enclosing
988 // non-transparent context.
989 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000990 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000991
992 // We do not look directly into function or method contexts,
993 // since all of the local variables and parameters of the
994 // function/method are present within the Scope.
995 if (Ctx->isFunctionOrMethod()) {
996 // If we have an Objective-C instance method, look for ivars
997 // in the corresponding interface.
998 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
999 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1000 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1001 ObjCInterfaceDecl *ClassDeclared;
1002 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001003 Name.getAsIdentifierInfo(),
Douglas Gregor337caf92010-02-19 16:08:35 +00001004 ClassDeclared)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001005 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1006 R.addDecl(ND);
Douglas Gregor337caf92010-02-19 16:08:35 +00001007 R.resolveKind();
1008 return true;
1009 }
1010 }
1011 }
1012 }
1013
1014 continue;
1015 }
1016
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001017 // If this is a file context, we need to perform unqualified name
1018 // lookup considering using directives.
1019 if (Ctx->isFileContext()) {
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001020 // If we haven't handled using directives yet, do so now.
1021 if (!VisitedUsingDirectives) {
1022 // Add using directives from this context up to the top level.
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001023 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1024 if (UCtx->isTransparentContext())
1025 continue;
1026
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001027 UDirs.visit(UCtx, UCtx);
Douglas Gregor8ccbc182013-04-09 01:49:26 +00001028 }
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001029
1030 // Find the innermost file scope, so we can add using directives
1031 // from local scopes.
1032 Scope *InnermostFileScope = S;
1033 while (InnermostFileScope &&
1034 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1035 InnermostFileScope = InnermostFileScope->getParent();
1036 UDirs.visitScopeChain(Initial, InnermostFileScope);
1037
1038 UDirs.done();
1039
1040 VisitedUsingDirectives = true;
1041 }
Douglas Gregorb0d0aa52013-03-27 12:51:49 +00001042
1043 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1044 R.resolveKind();
1045 return true;
1046 }
1047
1048 continue;
1049 }
1050
Douglas Gregor7f737c02009-09-10 16:57:35 +00001051 // Perform qualified name lookup into this context.
1052 // FIXME: In some cases, we know that every name that could be found by
1053 // this qualified name lookup will also be on the identifier chain. For
1054 // example, inside a class without any base classes, we never need to
1055 // perform qualified lookup because all of the members are on top of the
1056 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001057 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +00001058 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +00001059 }
Douglas Gregor700792c2009-02-05 19:25:20 +00001060 }
Douglas Gregored8f2882009-01-30 01:04:22 +00001061 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001062
John McCallf6c8a4e2009-11-10 07:01:13 +00001063 // Stop if we ran out of scopes.
1064 // FIXME: This really, really shouldn't be happening.
1065 if (!S) return false;
1066
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001067 // If we are looking for members, no need to look into global/namespace scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00001068 if (NameKind == LookupMemberName)
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +00001069 return false;
1070
Douglas Gregor700792c2009-02-05 19:25:20 +00001071 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +00001072 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +00001073 //
Mike Stump87c57ac2009-05-16 07:39:55 +00001074 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1075 // don't build it for each lookup!
Douglas Gregorcc9406c2013-04-08 23:11:25 +00001076 if (!VisitedUsingDirectives) {
1077 UDirs.visitScopeChain(Initial, S);
1078 UDirs.done();
1079 }
Richard Smith541b38b2013-09-20 01:15:31 +00001080
1081 // If we're not performing redeclaration lookup, do not look for local
1082 // extern declarations outside of a function scope.
1083 if (!R.isForRedeclaration())
1084 FindLocals.restore();
1085
Douglas Gregor700792c2009-02-05 19:25:20 +00001086 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +00001087 // Unqualified name lookup in C++ requires looking into scopes
1088 // that aren't strictly lexical, and therefore we walk through the
1089 // context as well as walking through the scopes.
1090 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001091 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +00001092 bool Found = false;
John McCall48871652010-08-21 09:40:31 +00001093 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Douglas Gregor4a814562011-12-14 16:03:29 +00001094 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001095 // We found something. Look for anything else in our scope
1096 // with this same name and in an acceptable identifier
1097 // namespace, so that we can construct an overload set if we
1098 // need to.
John McCall9f3059a2009-10-09 21:13:30 +00001099 Found = true;
Douglas Gregor4a814562011-12-14 16:03:29 +00001100 R.addDecl(ND);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001101 }
1102 }
1103
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001104 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +00001105 R.resolveKind();
1106 return true;
1107 }
1108
Ted Kremenekc37877d2013-10-08 17:08:03 +00001109 DeclContext *Ctx = S->getEntity();
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001110 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1111 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1112 // We've just searched the last template parameter scope and
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001113 // found nothing, so look into the contexts between the
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001114 // lexical and semantic declaration contexts returned by
1115 // findOuterContext(). This implements the name lookup behavior
1116 // of C++ [temp.local]p8.
1117 Ctx = OutsideOfTemplateParamDC;
1118 OutsideOfTemplateParamDC = 0;
1119 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001120
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001121 if (Ctx) {
1122 DeclContext *OuterCtx;
1123 bool SearchAfterTemplateScope;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001124 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001125 if (SearchAfterTemplateScope)
1126 OutsideOfTemplateParamDC = OuterCtx;
1127
1128 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1129 // We do not directly look into transparent contexts, since
1130 // those entities will be found in the nearest enclosing
1131 // non-transparent context.
1132 if (Ctx->isTransparentContext())
1133 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001134
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001135 // If we have a context, and it's not a context stashed in the
1136 // template parameter scope for an out-of-line definition, also
1137 // look into that context.
1138 if (!(Found && S && S->isTemplateParamScope())) {
1139 assert(Ctx->isFileContext() &&
1140 "We should have been looking only at file context here already.");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001141
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001142 // Look into context considering using-directives.
1143 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1144 Found = true;
1145 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001146
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001147 if (Found) {
1148 R.resolveKind();
1149 return true;
1150 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001151
Douglas Gregorf3d3ae62010-05-14 04:53:42 +00001152 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1153 return false;
1154 }
1155 }
1156
Douglas Gregor3ce74932010-02-05 07:07:10 +00001157 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001158 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001159 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001160
John McCall9f3059a2009-10-09 21:13:30 +00001161 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001162}
1163
Richard Smith0e5d7b82013-07-25 23:08:39 +00001164/// \brief Find the declaration that a class temploid member specialization was
1165/// instantiated from, or the member itself if it is an explicit specialization.
1166static Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) {
1167 return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom();
1168}
1169
1170/// \brief Find the module in which the given declaration was defined.
1171static Module *getDefiningModule(Decl *Entity) {
1172 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1173 // If this function was instantiated from a template, the defining module is
1174 // the module containing the pattern.
1175 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1176 Entity = Pattern;
1177 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
1178 // If it's a class template specialization, find the template or partial
1179 // specialization from which it was instantiated.
1180 if (ClassTemplateSpecializationDecl *SpecRD =
1181 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
1182 llvm::PointerUnion<ClassTemplateDecl*,
1183 ClassTemplatePartialSpecializationDecl*> From =
1184 SpecRD->getInstantiatedFrom();
1185 if (ClassTemplateDecl *FromTemplate = From.dyn_cast<ClassTemplateDecl*>())
1186 Entity = FromTemplate->getTemplatedDecl();
1187 else if (From)
1188 Entity = From.get<ClassTemplatePartialSpecializationDecl*>();
1189 // Otherwise, it's an explicit specialization.
1190 } else if (MemberSpecializationInfo *MSInfo =
1191 RD->getMemberSpecializationInfo())
1192 Entity = getInstantiatedFrom(RD, MSInfo);
1193 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1194 if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo())
1195 Entity = getInstantiatedFrom(ED, MSInfo);
1196 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1197 // FIXME: Map from variable template specializations back to the template.
1198 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo())
1199 Entity = getInstantiatedFrom(VD, MSInfo);
1200 }
1201
1202 // Walk up to the containing context. That might also have been instantiated
1203 // from a template.
1204 DeclContext *Context = Entity->getDeclContext();
1205 if (Context->isFileContext())
1206 return Entity->getOwningModule();
1207 return getDefiningModule(cast<Decl>(Context));
1208}
1209
1210llvm::DenseSet<Module*> &Sema::getLookupModules() {
1211 unsigned N = ActiveTemplateInstantiations.size();
1212 for (unsigned I = ActiveTemplateInstantiationLookupModules.size();
1213 I != N; ++I) {
1214 Module *M = getDefiningModule(ActiveTemplateInstantiations[I].Entity);
1215 if (M && !LookupModulesCache.insert(M).second)
1216 M = 0;
1217 ActiveTemplateInstantiationLookupModules.push_back(M);
1218 }
1219 return LookupModulesCache;
1220}
1221
1222/// \brief Determine whether a declaration is visible to name lookup.
1223///
1224/// This routine determines whether the declaration D is visible in the current
1225/// lookup context, taking into account the current template instantiation
1226/// stack. During template instantiation, a declaration is visible if it is
1227/// visible from a module containing any entity on the template instantiation
1228/// path (by instantiating a template, you allow it to see the declarations that
1229/// your module can see, including those later on in your module).
1230bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
1231 assert(D->isHidden() && !SemaRef.ActiveTemplateInstantiations.empty() &&
1232 "should not call this: not in slow case");
1233 Module *DeclModule = D->getOwningModule();
1234 assert(DeclModule && "hidden decl not from a module");
1235
1236 // Find the extra places where we need to look.
1237 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
1238 if (LookupModules.empty())
1239 return false;
1240
1241 // If our lookup set contains the decl's module, it's visible.
1242 if (LookupModules.count(DeclModule))
1243 return true;
1244
1245 // If the declaration isn't exported, it's not visible in any other module.
1246 if (D->isModulePrivate())
1247 return false;
1248
1249 // Check whether DeclModule is transitively exported to an import of
1250 // the lookup set.
1251 for (llvm::DenseSet<Module *>::iterator I = LookupModules.begin(),
1252 E = LookupModules.end();
1253 I != E; ++I)
1254 if ((*I)->isModuleVisible(DeclModule))
1255 return true;
1256 return false;
1257}
1258
Douglas Gregor4a814562011-12-14 16:03:29 +00001259/// \brief Retrieve the visible declaration corresponding to D, if any.
1260///
1261/// This routine determines whether the declaration D is visible in the current
1262/// module, with the current imports. If not, it checks whether any
1263/// redeclaration of D is visible, and if so, returns that declaration.
Richard Smith0e5d7b82013-07-25 23:08:39 +00001264///
Douglas Gregor4a814562011-12-14 16:03:29 +00001265/// \returns D, or a visible previous declaration of D, whichever is more recent
1266/// and visible. If no declaration of D is visible, returns null.
Richard Smithe156254d2013-08-20 20:35:18 +00001267static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
1268 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
Richard Smith0e5d7b82013-07-25 23:08:39 +00001269
Aaron Ballman86c93902014-03-06 23:45:36 +00001270 for (auto RD : D->redecls()) {
1271 if (auto ND = dyn_cast<NamedDecl>(RD)) {
Richard Smithe156254d2013-08-20 20:35:18 +00001272 if (LookupResult::isVisible(SemaRef, ND))
Douglas Gregor54079202012-01-06 22:05:37 +00001273 return ND;
1274 }
Douglas Gregor4a814562011-12-14 16:03:29 +00001275 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001276
Douglas Gregor4a814562011-12-14 16:03:29 +00001277 return 0;
1278}
1279
Richard Smithe156254d2013-08-20 20:35:18 +00001280NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
1281 return findAcceptableDecl(SemaRef, D);
1282}
1283
Douglas Gregor34074322009-01-14 22:20:51 +00001284/// @brief Perform unqualified name lookup starting from a given
1285/// scope.
1286///
1287/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1288/// used to find names within the current scope. For example, 'x' in
1289/// @code
1290/// int x;
1291/// int f() {
1292/// return x; // unqualified name look finds 'x' in the global scope
1293/// }
1294/// @endcode
1295///
1296/// Different lookup criteria can find different names. For example, a
1297/// particular scope can have both a struct and a function of the same
1298/// name, and each can be found by certain lookup criteria. For more
1299/// information about lookup criteria, see the documentation for the
1300/// class LookupCriteria.
1301///
1302/// @param S The scope from which unqualified name lookup will
1303/// begin. If the lookup criteria permits, name lookup may also search
1304/// in the parent scopes.
1305///
James Dennett91738ff2012-06-22 10:32:46 +00001306/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1307/// look up and the lookup kind), and is updated with the results of lookup
1308/// including zero or more declarations and possibly additional information
1309/// used to diagnose ambiguities.
Douglas Gregor34074322009-01-14 22:20:51 +00001310///
James Dennett91738ff2012-06-22 10:32:46 +00001311/// @returns \c true if lookup succeeded and false otherwise.
John McCall27b18f82009-11-17 02:14:36 +00001312bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1313 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001314 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001315
John McCall27b18f82009-11-17 02:14:36 +00001316 LookupNameKind NameKind = R.getLookupKind();
1317
David Blaikiebbafb8a2012-03-11 07:00:24 +00001318 if (!getLangOpts().CPlusPlus) {
Douglas Gregor34074322009-01-14 22:20:51 +00001319 // Unqualified name lookup in C/Objective-C is purely lexical, so
1320 // search in the declarations attached to the name.
John McCallea305ed2009-12-18 10:40:03 +00001321 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001322 // Find the nearest non-transparent declaration scope.
1323 while (!(S->getFlags() & Scope::DeclScope) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001324 (S->getEntity() && S->getEntity()->isTransparentContext()))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001325 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001326 }
1327
Richard Smith541b38b2013-09-20 01:15:31 +00001328 // When performing a scope lookup, we want to find local extern decls.
1329 FindLocalExternScope FindLocals(R);
1330
Douglas Gregor34074322009-01-14 22:20:51 +00001331 // Scan up the scope chain looking for a decl that matches this
1332 // identifier that is in the appropriate namespace. This search
1333 // should not take long, as shadowing of names is uncommon, and
1334 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001335 bool LeftStartingScope = false;
1336
Douglas Gregored8f2882009-01-30 01:04:22 +00001337 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001338 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001339 I != IEnd; ++I)
Richard Smith0e5d7b82013-07-25 23:08:39 +00001340 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001341 if (NameKind == LookupRedeclarationWithLinkage) {
1342 // Determine whether this (or a previous) declaration is
1343 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001344 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001345 LeftStartingScope = true;
1346
1347 // If we found something outside of our starting scope that
1348 // does not have linkage, skip it.
Richard Smith1c34fb72013-08-13 18:18:50 +00001349 if (LeftStartingScope && !((*I)->hasLinkage())) {
1350 R.setShadowed();
Douglas Gregoreddf4332009-02-24 20:03:32 +00001351 continue;
Richard Smith1c34fb72013-08-13 18:18:50 +00001352 }
Douglas Gregoreddf4332009-02-24 20:03:32 +00001353 }
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001354 else if (NameKind == LookupObjCImplicitSelfParam &&
1355 !isa<ImplicitParamDecl>(*I))
1356 continue;
Richard Smith0e5d7b82013-07-25 23:08:39 +00001357
Douglas Gregor4a814562011-12-14 16:03:29 +00001358 R.addDecl(D);
John McCall9f3059a2009-10-09 21:13:30 +00001359
Douglas Gregorb59643b2012-01-03 23:26:26 +00001360 // Check whether there are any other declarations with the same name
1361 // and in the same scope.
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001362 if (I != IEnd) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001363 // Find the scope in which this declaration was declared (if it
1364 // actually exists in a Scope).
1365 while (S && !S->isDeclScope(D))
1366 S = S->getParent();
1367
1368 // If the scope containing the declaration is the translation unit,
1369 // then we'll need to perform our checks based on the matching
1370 // DeclContexts rather than matching scopes.
1371 if (S && isNamespaceOrTranslationUnitScope(S))
1372 S = 0;
1373
1374 // Compute the DeclContext, if we need it.
1375 DeclContext *DC = 0;
1376 if (!S)
1377 DC = (*I)->getDeclContext()->getRedeclContext();
1378
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001379 IdentifierResolver::iterator LastI = I;
1380 for (++LastI; LastI != IEnd; ++LastI) {
Douglas Gregor81bd0382012-01-13 23:06:53 +00001381 if (S) {
1382 // Match based on scope.
1383 if (!S->isDeclScope(*LastI))
1384 break;
1385 } else {
1386 // Match based on DeclContext.
1387 DeclContext *LastDC
1388 = (*LastI)->getDeclContext()->getRedeclContext();
1389 if (!LastDC->Equals(DC))
1390 break;
1391 }
Richard Smith0e5d7b82013-07-25 23:08:39 +00001392
1393 // If the declaration is in the right namespace and visible, add it.
1394 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1395 R.addDecl(LastD);
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001396 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001397
Douglas Gregor9b7b3912012-01-04 16:44:10 +00001398 R.resolveKind();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001399 }
Richard Smith541b38b2013-09-20 01:15:31 +00001400
John McCall9f3059a2009-10-09 21:13:30 +00001401 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001402 }
Douglas Gregor34074322009-01-14 22:20:51 +00001403 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001404 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001405 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001406 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001407 }
1408
1409 // If we didn't find a use of this identifier, and if the identifier
1410 // corresponds to a compiler builtin, create the decl object for the builtin
1411 // now, injecting it into translation unit scope, and return it.
Axel Naumann43dec142011-04-13 13:19:46 +00001412 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1413 return true;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001414
Axel Naumann016538a2011-02-24 16:47:47 +00001415 // If we didn't find a use of this identifier, the ExternalSource
1416 // may be able to handle the situation.
1417 // Note: some lookup failures are expected!
1418 // See e.g. R.isForRedeclaration().
1419 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
Douglas Gregor34074322009-01-14 22:20:51 +00001420}
1421
John McCall6538c932009-10-10 05:48:19 +00001422/// @brief Perform qualified name lookup in the namespaces nominated by
1423/// using directives by the given context.
1424///
1425/// C++98 [namespace.qual]p2:
James Dennett51a8d8b2012-06-19 21:05:49 +00001426/// Given X::m (where X is a user-declared namespace), or given \::m
John McCall6538c932009-10-10 05:48:19 +00001427/// (where X is the global namespace), let S be the set of all
1428/// declarations of m in X and in the transitive closure of all
1429/// namespaces nominated by using-directives in X and its used
1430/// namespaces, except that using-directives are ignored in any
1431/// namespace, including X, directly containing one or more
1432/// declarations of m. No namespace is searched more than once in
1433/// the lookup of a name. If S is the empty set, the program is
1434/// ill-formed. Otherwise, if S has exactly one member, or if the
1435/// context of the reference is a using-declaration
1436/// (namespace.udecl), S is the required set of declarations of
1437/// m. Otherwise if the use of m is not one that allows a unique
1438/// declaration to be chosen from S, the program is ill-formed.
James Dennett51a8d8b2012-06-19 21:05:49 +00001439///
John McCall6538c932009-10-10 05:48:19 +00001440/// C++98 [namespace.qual]p5:
1441/// During the lookup of a qualified namespace member name, if the
1442/// lookup finds more than one declaration of the member, and if one
1443/// declaration introduces a class name or enumeration name and the
1444/// other declarations either introduce the same object, the same
1445/// enumerator or a set of functions, the non-type name hides the
1446/// class or enumeration name if and only if the declarations are
1447/// from the same namespace; otherwise (the declarations are from
1448/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001449static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001450 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001451 assert(StartDC->isFileContext() && "start context is not a file context");
1452
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001453 DeclContext::udir_range UsingDirectives = StartDC->using_directives();
1454 if (UsingDirectives.begin() == UsingDirectives.end()) return false;
John McCall6538c932009-10-10 05:48:19 +00001455
1456 // We have at least added all these contexts to the queue.
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001457 llvm::SmallPtrSet<DeclContext*, 8> Visited;
John McCall6538c932009-10-10 05:48:19 +00001458 Visited.insert(StartDC);
1459
1460 // We have not yet looked into these namespaces, much less added
1461 // their "using-children" to the queue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001462 SmallVector<NamespaceDecl*, 8> Queue;
John McCall6538c932009-10-10 05:48:19 +00001463
1464 // We have already looked into the initial namespace; seed the queue
1465 // with its using-children.
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001466 for (auto *I : UsingDirectives) {
1467 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001468 if (Visited.insert(ND))
John McCall6538c932009-10-10 05:48:19 +00001469 Queue.push_back(ND);
1470 }
1471
1472 // The easiest way to implement the restriction in [namespace.qual]p5
1473 // is to check whether any of the individual results found a tag
1474 // and, if so, to declare an ambiguity if the final result is not
1475 // a tag.
1476 bool FoundTag = false;
1477 bool FoundNonTag = false;
1478
John McCall5cebab12009-11-18 07:57:50 +00001479 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001480
1481 bool Found = false;
1482 while (!Queue.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001483 NamespaceDecl *ND = Queue.pop_back_val();
John McCall6538c932009-10-10 05:48:19 +00001484
1485 // We go through some convolutions here to avoid copying results
1486 // between LookupResults.
1487 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001488 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001489 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001490
1491 if (FoundDirect) {
1492 // First do any local hiding.
1493 DirectR.resolveKind();
1494
1495 // If the local result is a tag, remember that.
1496 if (DirectR.isSingleTagDecl())
1497 FoundTag = true;
1498 else
1499 FoundNonTag = true;
1500
1501 // Append the local results to the total results if necessary.
1502 if (UseLocal) {
1503 R.addAllDecls(LocalR);
1504 LocalR.clear();
1505 }
1506 }
1507
1508 // If we find names in this namespace, ignore its using directives.
1509 if (FoundDirect) {
1510 Found = true;
1511 continue;
1512 }
1513
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001514 for (auto I : ND->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00001515 NamespaceDecl *Nom = I->getNominatedNamespace();
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00001516 if (Visited.insert(Nom))
John McCall6538c932009-10-10 05:48:19 +00001517 Queue.push_back(Nom);
1518 }
1519 }
1520
1521 if (Found) {
1522 if (FoundTag && FoundNonTag)
1523 R.setAmbiguousQualifiedTagHiding();
1524 else
1525 R.resolveKind();
1526 }
1527
1528 return Found;
1529}
1530
Douglas Gregor39982192010-08-15 06:18:01 +00001531/// \brief Callback that looks for any member of a class with the given name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001532static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
Douglas Gregor39982192010-08-15 06:18:01 +00001533 CXXBasePath &Path,
1534 void *Name) {
1535 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001536
Douglas Gregor39982192010-08-15 06:18:01 +00001537 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1538 Path.Decls = BaseRecord->lookup(N);
David Blaikieff7d47a2012-12-19 00:45:41 +00001539 return !Path.Decls.empty();
Douglas Gregor39982192010-08-15 06:18:01 +00001540}
1541
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001542/// \brief Determine whether the given set of member declarations contains only
Douglas Gregorc0d24902010-10-22 22:08:47 +00001543/// static members, nested types, and enumerators.
1544template<typename InputIterator>
1545static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1546 Decl *D = (*First)->getUnderlyingDecl();
1547 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1548 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001549
Douglas Gregorc0d24902010-10-22 22:08:47 +00001550 if (isa<CXXMethodDecl>(D)) {
1551 // Determine whether all of the methods are static.
1552 bool AllMethodsAreStatic = true;
1553 for(; First != Last; ++First) {
1554 D = (*First)->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001555
Douglas Gregorc0d24902010-10-22 22:08:47 +00001556 if (!isa<CXXMethodDecl>(D)) {
1557 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1558 break;
1559 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001560
Douglas Gregorc0d24902010-10-22 22:08:47 +00001561 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1562 AllMethodsAreStatic = false;
1563 break;
1564 }
1565 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001566
Douglas Gregorc0d24902010-10-22 22:08:47 +00001567 if (AllMethodsAreStatic)
1568 return true;
1569 }
1570
1571 return false;
1572}
1573
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001574/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001575///
1576/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1577/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001578/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001579///
1580/// Different lookup criteria can find different names. For example, a
1581/// particular scope can have both a struct and a function of the same
1582/// name, and each can be found by certain lookup criteria. For more
1583/// information about lookup criteria, see the documentation for the
1584/// class LookupCriteria.
1585///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001586/// \param R captures both the lookup criteria and any lookup results found.
1587///
1588/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001589/// search. If the lookup criteria permits, name lookup may also search
1590/// in the parent contexts or (for C++ classes) base classes.
1591///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001592/// \param InUnqualifiedLookup true if this is qualified name lookup that
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001593/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001594///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001595/// \returns true if lookup succeeded, false if it failed.
1596bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1597 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001598 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001599
John McCall27b18f82009-11-17 02:14:36 +00001600 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001601 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001602
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001603 // Make sure that the declaration context is complete.
1604 assert((!isa<TagDecl>(LookupCtx) ||
1605 LookupCtx->isDependentContext() ||
John McCallf937c022011-10-07 06:10:15 +00001606 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
Richard Smith7d137e32012-03-23 03:33:32 +00001607 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001608 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001609
Douglas Gregor34074322009-01-14 22:20:51 +00001610 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001611 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001612 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001613 if (isa<CXXRecordDecl>(LookupCtx))
1614 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001615 return true;
1616 }
Douglas Gregor34074322009-01-14 22:20:51 +00001617
John McCall6538c932009-10-10 05:48:19 +00001618 // Don't descend into implied contexts for redeclarations.
1619 // C++98 [namespace.qual]p6:
1620 // In a declaration for a namespace member in which the
1621 // declarator-id is a qualified-id, given that the qualified-id
1622 // for the namespace member has the form
1623 // nested-name-specifier unqualified-id
1624 // the unqualified-id shall name a member of the namespace
1625 // designated by the nested-name-specifier.
1626 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001627 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001628 return false;
1629
John McCall27b18f82009-11-17 02:14:36 +00001630 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001631 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001632 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001633
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001634 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001635 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001636 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001637 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001638 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001639
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001640 // If we're performing qualified name lookup into a dependent class,
1641 // then we are actually looking into a current instantiation. If we have any
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001642 // dependent base classes, then we either have to delay lookup until
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001643 // template instantiation time (at which point all bases will be available)
1644 // or we have to fail.
1645 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1646 LookupRec->hasAnyDependentBases()) {
1647 R.setNotFoundInCurrentInstantiation();
1648 return false;
1649 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001650
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001651 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001652 CXXBasePaths Paths;
1653 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001654
1655 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001656 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001657 switch (R.getLookupKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001658 case LookupObjCImplicitSelfParam:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001659 case LookupOrdinaryName:
1660 case LookupMemberName:
1661 case LookupRedeclarationWithLinkage:
Richard Smith114394f2013-08-09 04:35:01 +00001662 case LookupLocalFriendName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001663 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1664 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001665
Douglas Gregor36d1b142009-10-06 17:59:45 +00001666 case LookupTagName:
1667 BaseCallback = &CXXRecordDecl::FindTagMember;
1668 break;
John McCall84d87672009-12-10 09:41:52 +00001669
Douglas Gregor39982192010-08-15 06:18:01 +00001670 case LookupAnyName:
1671 BaseCallback = &LookupAnyMember;
1672 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001673
John McCall84d87672009-12-10 09:41:52 +00001674 case LookupUsingDeclName:
1675 // This lookup is for redeclarations only.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001676
Douglas Gregor36d1b142009-10-06 17:59:45 +00001677 case LookupOperatorName:
1678 case LookupNamespaceName:
1679 case LookupObjCProtocolName:
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001680 case LookupLabel:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001681 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001682 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001683
Douglas Gregor36d1b142009-10-06 17:59:45 +00001684 case LookupNestedNameSpecifierName:
1685 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1686 break;
1687 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001688
John McCall27b18f82009-11-17 02:14:36 +00001689 if (!LookupRec->lookupInBases(BaseCallback,
1690 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001691 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001692
John McCall553c0792010-01-23 00:46:32 +00001693 R.setNamingClass(LookupRec);
1694
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001695 // C++ [class.member.lookup]p2:
1696 // [...] If the resulting set of declarations are not all from
1697 // sub-objects of the same type, or the set has a nonstatic member
1698 // and includes members from distinct sub-objects, there is an
1699 // ambiguity and the program is ill-formed. Otherwise that set is
1700 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001701 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001702 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001703 AccessSpecifier SubobjectAccess = AS_none;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001704
Douglas Gregor36d1b142009-10-06 17:59:45 +00001705 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001706 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001707 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001708
John McCall401982f2010-01-20 21:53:11 +00001709 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1710 // across all paths.
1711 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001712
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001713 // Determine whether we're looking at a distinct sub-object or not.
1714 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001715 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001716 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1717 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001718 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001719 }
1720
Douglas Gregorc0d24902010-10-22 22:08:47 +00001721 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001722 != Context.getCanonicalType(PathElement.Base->getType())) {
1723 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001724 // different types. If the declaration sets aren't the same, this
1725 // this lookup is ambiguous.
David Blaikieff7d47a2012-12-19 00:45:41 +00001726 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00001727 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
David Blaikieff7d47a2012-12-19 00:45:41 +00001728 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
1729 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001730
David Blaikieff7d47a2012-12-19 00:45:41 +00001731 while (FirstD != FirstPath->Decls.end() &&
1732 CurrentD != Path->Decls.end()) {
Douglas Gregorc0d24902010-10-22 22:08:47 +00001733 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1734 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1735 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001736
Douglas Gregorc0d24902010-10-22 22:08:47 +00001737 ++FirstD;
1738 ++CurrentD;
1739 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001740
David Blaikieff7d47a2012-12-19 00:45:41 +00001741 if (FirstD == FirstPath->Decls.end() &&
1742 CurrentD == Path->Decls.end())
Douglas Gregorc0d24902010-10-22 22:08:47 +00001743 continue;
1744 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001745
John McCall9f3059a2009-10-09 21:13:30 +00001746 R.setAmbiguousBaseSubobjectTypes(Paths);
1747 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001748 }
1749
Douglas Gregorc0d24902010-10-22 22:08:47 +00001750 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001751 // We have a different subobject of the same type.
1752
1753 // C++ [class.member.lookup]p5:
1754 // A static member, a nested type or an enumerator defined in
1755 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001756 // has more than one base class subobject of type T.
David Blaikieff7d47a2012-12-19 00:45:41 +00001757 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001758 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001759
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001760 // We have found a nonstatic member name in multiple, distinct
1761 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001762 R.setAmbiguousBaseSubobjects(Paths);
1763 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001764 }
1765 }
1766
1767 // Lookup in a base class succeeded; return these results.
1768
David Blaikieff7d47a2012-12-19 00:45:41 +00001769 DeclContext::lookup_result DR = Paths.front().Decls;
1770 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E; ++I) {
John McCall553c0792010-01-23 00:46:32 +00001771 NamedDecl *D = *I;
1772 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1773 D->getAccess());
1774 R.addDecl(D, AS);
1775 }
John McCall9f3059a2009-10-09 21:13:30 +00001776 R.resolveKind();
1777 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001778}
1779
1780/// @brief Performs name lookup for a name that was parsed in the
1781/// source code, and may contain a C++ scope specifier.
1782///
1783/// This routine is a convenience routine meant to be called from
1784/// contexts that receive a name and an optional C++ scope specifier
1785/// (e.g., "N::M::x"). It will then perform either qualified or
1786/// unqualified name lookup (with LookupQualifiedName or LookupName,
1787/// respectively) on the given name and return those results.
1788///
1789/// @param S The scope from which unqualified name lookup will
1790/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001791///
Douglas Gregore861bac2009-08-25 22:51:20 +00001792/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001793///
Douglas Gregore861bac2009-08-25 22:51:20 +00001794/// @param EnteringContext Indicates whether we are going to enter the
1795/// context of the scope-specifier SS (if present).
1796///
John McCall9f3059a2009-10-09 21:13:30 +00001797/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001798bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001799 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001800 if (SS && SS->isInvalid()) {
1801 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001802 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001803 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001804 }
Mike Stump11289f42009-09-09 15:08:12 +00001805
Douglas Gregore861bac2009-08-25 22:51:20 +00001806 if (SS && SS->isSet()) {
1807 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001808 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001809 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001810 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001811 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001812
John McCall27b18f82009-11-17 02:14:36 +00001813 R.setContextRange(SS->getRange());
John McCall27b18f82009-11-17 02:14:36 +00001814 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001815 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001816
Douglas Gregore861bac2009-08-25 22:51:20 +00001817 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001818 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001819 // Name lookup can't find anything in this case.
Douglas Gregor89ab56d2011-10-24 22:24:50 +00001820 R.setNotFoundInCurrentInstantiation();
1821 R.setContextRange(SS->getRange());
John McCall9f3059a2009-10-09 21:13:30 +00001822 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001823 }
1824
Mike Stump11289f42009-09-09 15:08:12 +00001825 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001826 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001827}
1828
Douglas Gregor889ceb72009-02-03 19:21:40 +00001829
James Dennett41725122012-06-22 10:16:05 +00001830/// \brief Produce a diagnostic describing the ambiguity that resulted
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001831/// from name lookup.
1832///
James Dennett41725122012-06-22 10:16:05 +00001833/// \param Result The result of the ambiguous lookup to be diagnosed.
Serge Pavlov99292092013-08-29 07:23:24 +00001834void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001835 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1836
John McCall27b18f82009-11-17 02:14:36 +00001837 DeclarationName Name = Result.getLookupName();
1838 SourceLocation NameLoc = Result.getNameLoc();
1839 SourceRange LookupRange = Result.getContextRange();
1840
John McCall6538c932009-10-10 05:48:19 +00001841 switch (Result.getAmbiguityKind()) {
1842 case LookupResult::AmbiguousBaseSubobjects: {
1843 CXXBasePaths *Paths = Result.getBasePaths();
1844 QualType SubobjectType = Paths->front().back().Base->getType();
1845 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1846 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1847 << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001848
David Blaikieff7d47a2012-12-19 00:45:41 +00001849 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
John McCall6538c932009-10-10 05:48:19 +00001850 while (isa<CXXMethodDecl>(*Found) &&
1851 cast<CXXMethodDecl>(*Found)->isStatic())
1852 ++Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001853
John McCall6538c932009-10-10 05:48:19 +00001854 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
Serge Pavlov99292092013-08-29 07:23:24 +00001855 break;
John McCall6538c932009-10-10 05:48:19 +00001856 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001857
John McCall6538c932009-10-10 05:48:19 +00001858 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001859 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1860 << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001861
John McCall6538c932009-10-10 05:48:19 +00001862 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001863 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001864 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1865 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001866 Path != PathEnd; ++Path) {
David Blaikieff7d47a2012-12-19 00:45:41 +00001867 Decl *D = Path->Decls.front();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001868 if (DeclsPrinted.insert(D).second)
1869 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1870 }
Serge Pavlov99292092013-08-29 07:23:24 +00001871 break;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001872 }
1873
John McCall6538c932009-10-10 05:48:19 +00001874 case LookupResult::AmbiguousTagHiding: {
1875 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001876
John McCall6538c932009-10-10 05:48:19 +00001877 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1878
1879 LookupResult::iterator DI, DE = Result.end();
1880 for (DI = Result.begin(); DI != DE; ++DI)
1881 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1882 TagDecls.insert(TD);
1883 Diag(TD->getLocation(), diag::note_hidden_tag);
1884 }
1885
1886 for (DI = Result.begin(); DI != DE; ++DI)
1887 if (!isa<TagDecl>(*DI))
1888 Diag((*DI)->getLocation(), diag::note_hiding_object);
1889
1890 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001891 LookupResult::Filter F = Result.makeFilter();
1892 while (F.hasNext()) {
1893 if (TagDecls.count(F.next()))
1894 F.erase();
1895 }
1896 F.done();
Serge Pavlov99292092013-08-29 07:23:24 +00001897 break;
John McCall6538c932009-10-10 05:48:19 +00001898 }
1899
1900 case LookupResult::AmbiguousReference: {
1901 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001902
John McCall6538c932009-10-10 05:48:19 +00001903 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1904 for (; DI != DE; ++DI)
1905 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
Serge Pavlov99292092013-08-29 07:23:24 +00001906 break;
John McCall6538c932009-10-10 05:48:19 +00001907 }
Serge Pavlov99292092013-08-29 07:23:24 +00001908 }
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001909}
Douglas Gregore254f902009-02-04 00:32:51 +00001910
John McCallf24d7bb2010-05-28 18:45:08 +00001911namespace {
1912 struct AssociatedLookup {
John McCall7d8b0412012-08-24 20:38:34 +00001913 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
John McCallf24d7bb2010-05-28 18:45:08 +00001914 Sema::AssociatedNamespaceSet &Namespaces,
1915 Sema::AssociatedClassSet &Classes)
John McCall7d8b0412012-08-24 20:38:34 +00001916 : S(S), Namespaces(Namespaces), Classes(Classes),
1917 InstantiationLoc(InstantiationLoc) {
John McCallf24d7bb2010-05-28 18:45:08 +00001918 }
1919
1920 Sema &S;
1921 Sema::AssociatedNamespaceSet &Namespaces;
1922 Sema::AssociatedClassSet &Classes;
John McCall7d8b0412012-08-24 20:38:34 +00001923 SourceLocation InstantiationLoc;
John McCallf24d7bb2010-05-28 18:45:08 +00001924 };
1925}
1926
Mike Stump11289f42009-09-09 15:08:12 +00001927static void
John McCallf24d7bb2010-05-28 18:45:08 +00001928addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001929
Douglas Gregor8b895222010-04-30 07:08:38 +00001930static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1931 DeclContext *Ctx) {
1932 // Add the associated namespace for this class.
1933
1934 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1935 // be a locally scoped record.
1936
Sebastian Redlbd595762010-08-31 20:53:31 +00001937 // We skip out of inline namespaces. The innermost non-inline namespace
1938 // contains all names of all its nested inline namespaces anyway, so we can
1939 // replace the entire inline namespace tree with its root.
1940 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1941 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00001942 Ctx = Ctx->getParent();
1943
John McCallc7e8e792009-08-07 22:18:02 +00001944 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001945 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001946}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001947
Mike Stump11289f42009-09-09 15:08:12 +00001948// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001949// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001950static void
John McCallf24d7bb2010-05-28 18:45:08 +00001951addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1952 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001953 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001954 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001955 switch (Arg.getKind()) {
1956 case TemplateArgument::Null:
1957 break;
Mike Stump11289f42009-09-09 15:08:12 +00001958
Douglas Gregor197e5f72009-07-08 07:51:57 +00001959 case TemplateArgument::Type:
1960 // [...] the namespaces and classes associated with the types of the
1961 // template arguments provided for template type parameters (excluding
1962 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001963 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001964 break;
Mike Stump11289f42009-09-09 15:08:12 +00001965
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001966 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001967 case TemplateArgument::TemplateExpansion: {
Mike Stump11289f42009-09-09 15:08:12 +00001968 // [...] the namespaces in which any template template arguments are
1969 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001970 // template template arguments are defined.
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001971 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
Mike Stump11289f42009-09-09 15:08:12 +00001972 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001973 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001974 DeclContext *Ctx = ClassTemplate->getDeclContext();
1975 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001976 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001977 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001978 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001979 }
1980 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001981 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001982
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001983 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001984 case TemplateArgument::Integral:
1985 case TemplateArgument::Expression:
Eli Friedmanb826a002012-09-26 02:36:12 +00001986 case TemplateArgument::NullPtr:
Mike Stump11289f42009-09-09 15:08:12 +00001987 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001988 // associated namespaces. ]
1989 break;
Mike Stump11289f42009-09-09 15:08:12 +00001990
Douglas Gregor197e5f72009-07-08 07:51:57 +00001991 case TemplateArgument::Pack:
1992 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1993 PEnd = Arg.pack_end();
1994 P != PEnd; ++P)
John McCallf24d7bb2010-05-28 18:45:08 +00001995 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001996 break;
1997 }
1998}
1999
Douglas Gregore254f902009-02-04 00:32:51 +00002000// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00002001// argument-dependent lookup with an argument of class type
2002// (C++ [basic.lookup.koenig]p2).
2003static void
John McCallf24d7bb2010-05-28 18:45:08 +00002004addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2005 CXXRecordDecl *Class) {
2006
2007 // Just silently ignore anything whose name is __va_list_tag.
2008 if (Class->getDeclName() == Result.S.VAListTagName)
2009 return;
2010
Douglas Gregore254f902009-02-04 00:32:51 +00002011 // C++ [basic.lookup.koenig]p2:
2012 // [...]
2013 // -- If T is a class type (including unions), its associated
2014 // classes are: the class itself; the class of which it is a
2015 // member, if any; and its direct and indirect base
2016 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00002017 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00002018
2019 // Add the class of which it is a member, if any.
2020 DeclContext *Ctx = Class->getDeclContext();
2021 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002022 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002023 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002024 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002025
Douglas Gregore254f902009-02-04 00:32:51 +00002026 // Add the class itself. If we've already seen this class, we don't
2027 // need to visit base classes.
Richard Smith594461f2014-03-14 22:07:27 +00002028 //
2029 // FIXME: That's not correct, we may have added this class only because it
2030 // was the enclosing class of another class, and in that case we won't have
2031 // added its base classes yet.
John McCallf24d7bb2010-05-28 18:45:08 +00002032 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00002033 return;
2034
Mike Stump11289f42009-09-09 15:08:12 +00002035 // -- If T is a template-id, its associated namespaces and classes are
2036 // the namespace in which the template is defined; for member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002037 // templates, the member template's class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00002038 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00002039 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00002040 // namespaces in which any template template arguments are defined; and
2041 // the classes in which any member templates used as template template
2042 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00002043 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00002044 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00002045 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2046 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2047 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002048 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002049 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002050 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00002051
Douglas Gregor197e5f72009-07-08 07:51:57 +00002052 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2053 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00002054 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00002055 }
Mike Stump11289f42009-09-09 15:08:12 +00002056
John McCall67da35c2010-02-04 22:26:26 +00002057 // Only recurse into base classes for complete types.
Richard Smith594461f2014-03-14 22:07:27 +00002058 if (!Class->hasDefinition())
2059 return;
John McCall67da35c2010-02-04 22:26:26 +00002060
Douglas Gregore254f902009-02-04 00:32:51 +00002061 // Add direct and indirect base classes along with their associated
2062 // namespaces.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002063 SmallVector<CXXRecordDecl *, 32> Bases;
Douglas Gregore254f902009-02-04 00:32:51 +00002064 Bases.push_back(Class);
2065 while (!Bases.empty()) {
2066 // Pop this class off the stack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002067 Class = Bases.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002068
2069 // Visit the base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +00002070 for (const auto &Base : Class->bases()) {
2071 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00002072 // In dependent contexts, we do ADL twice, and the first time around,
2073 // the base type might be a dependent TemplateSpecializationType, or a
2074 // TemplateTypeParmType. If that happens, simply ignore it.
2075 // FIXME: If we want to support export, we probably need to add the
2076 // namespace of the template in a TemplateSpecializationType, or even
2077 // the classes and namespaces of known non-dependent arguments.
2078 if (!BaseType)
2079 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002080 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002081 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00002082 // Find the associated namespace for this base class.
2083 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00002084 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00002085
2086 // Make sure we visit the bases of this base class.
2087 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2088 Bases.push_back(BaseDecl);
2089 }
2090 }
2091 }
2092}
2093
2094// \brief Add the associated classes and namespaces for
2095// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00002096// (C++ [basic.lookup.koenig]p2).
2097static void
John McCallf24d7bb2010-05-28 18:45:08 +00002098addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00002099 // C++ [basic.lookup.koenig]p2:
2100 //
2101 // For each argument type T in the function call, there is a set
2102 // of zero or more associated namespaces and a set of zero or more
2103 // associated classes to be considered. The sets of namespaces and
2104 // classes is determined entirely by the types of the function
2105 // arguments (and the namespace of any template template
2106 // argument). Typedef names and using-declarations used to specify
2107 // the types do not contribute to this set. The sets of namespaces
2108 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00002109
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002110 SmallVector<const Type *, 16> Queue;
John McCall0af3d3b2010-05-28 06:08:54 +00002111 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2112
Douglas Gregore254f902009-02-04 00:32:51 +00002113 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00002114 switch (T->getTypeClass()) {
2115
2116#define TYPE(Class, Base)
2117#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2118#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2119#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2120#define ABSTRACT_TYPE(Class, Base)
2121#include "clang/AST/TypeNodes.def"
2122 // T is canonical. We can also ignore dependent types because
2123 // we don't need to do ADL at the definition point, but if we
2124 // wanted to implement template export (or if we find some other
2125 // use for associated classes and namespaces...) this would be
2126 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00002127 break;
Douglas Gregore254f902009-02-04 00:32:51 +00002128
John McCall0af3d3b2010-05-28 06:08:54 +00002129 // -- If T is a pointer to U or an array of U, its associated
2130 // namespaces and classes are those associated with U.
2131 case Type::Pointer:
2132 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2133 continue;
2134 case Type::ConstantArray:
2135 case Type::IncompleteArray:
2136 case Type::VariableArray:
2137 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2138 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00002139
John McCall0af3d3b2010-05-28 06:08:54 +00002140 // -- If T is a fundamental type, its associated sets of
2141 // namespaces and classes are both empty.
2142 case Type::Builtin:
2143 break;
2144
2145 // -- If T is a class type (including unions), its associated
2146 // classes are: the class itself; the class of which it is a
2147 // member, if any; and its direct and indirect base
2148 // classes. Its associated namespaces are the namespaces in
2149 // which its associated classes are defined.
2150 case Type::Record: {
Richard Smith594461f2014-03-14 22:07:27 +00002151 Result.S.RequireCompleteType(Result.InstantiationLoc, QualType(T, 0),
2152 /*no diagnostic*/ 0);
John McCall0af3d3b2010-05-28 06:08:54 +00002153 CXXRecordDecl *Class
2154 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00002155 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00002156 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00002157 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00002158
John McCall0af3d3b2010-05-28 06:08:54 +00002159 // -- If T is an enumeration type, its associated namespace is
2160 // the namespace in which it is defined. If it is class
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002161 // member, its associated class is the member's class; else
John McCall0af3d3b2010-05-28 06:08:54 +00002162 // it has no associated class.
2163 case Type::Enum: {
2164 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002165
John McCall0af3d3b2010-05-28 06:08:54 +00002166 DeclContext *Ctx = Enum->getDeclContext();
2167 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00002168 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00002169
John McCall0af3d3b2010-05-28 06:08:54 +00002170 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00002171 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00002172
John McCall0af3d3b2010-05-28 06:08:54 +00002173 break;
2174 }
2175
2176 // -- If T is a function type, its associated namespaces and
2177 // classes are those associated with the function parameter
2178 // types and those associated with the return type.
2179 case Type::FunctionProto: {
2180 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002181 for (const auto &Arg : Proto->param_types())
2182 Queue.push_back(Arg.getTypePtr());
John McCall0af3d3b2010-05-28 06:08:54 +00002183 // fallthrough
2184 }
2185 case Type::FunctionNoProto: {
2186 const FunctionType *FnType = cast<FunctionType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00002187 T = FnType->getReturnType().getTypePtr();
John McCall0af3d3b2010-05-28 06:08:54 +00002188 continue;
2189 }
2190
2191 // -- If T is a pointer to a member function of a class X, its
2192 // associated namespaces and classes are those associated
2193 // with the function parameter types and return type,
2194 // together with those associated with X.
2195 //
2196 // -- If T is a pointer to a data member of class X, its
2197 // associated namespaces and classes are those associated
2198 // with the member type together with those associated with
2199 // X.
2200 case Type::MemberPointer: {
2201 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2202
2203 // Queue up the class type into which this points.
2204 Queue.push_back(MemberPtr->getClass());
2205
2206 // And directly continue with the pointee type.
2207 T = MemberPtr->getPointeeType().getTypePtr();
2208 continue;
2209 }
2210
2211 // As an extension, treat this like a normal pointer.
2212 case Type::BlockPointer:
2213 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2214 continue;
2215
2216 // References aren't covered by the standard, but that's such an
2217 // obvious defect that we cover them anyway.
2218 case Type::LValueReference:
2219 case Type::RValueReference:
2220 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2221 continue;
2222
2223 // These are fundamental types.
2224 case Type::Vector:
2225 case Type::ExtVector:
2226 case Type::Complex:
2227 break;
2228
Richard Smith27d807c2013-04-30 13:56:41 +00002229 // Non-deduced auto types only get here for error cases.
2230 case Type::Auto:
2231 break;
2232
Douglas Gregor8e936662011-04-12 01:02:45 +00002233 // If T is an Objective-C object or interface type, or a pointer to an
2234 // object or interface type, the associated namespace is the global
2235 // namespace.
John McCall0af3d3b2010-05-28 06:08:54 +00002236 case Type::ObjCObject:
2237 case Type::ObjCInterface:
2238 case Type::ObjCObjectPointer:
Douglas Gregor8e936662011-04-12 01:02:45 +00002239 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
John McCall0af3d3b2010-05-28 06:08:54 +00002240 break;
Eli Friedman0dfb8892011-10-06 23:00:33 +00002241
2242 // Atomic types are just wrappers; use the associations of the
2243 // contained type.
2244 case Type::Atomic:
2245 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2246 continue;
John McCall0af3d3b2010-05-28 06:08:54 +00002247 }
2248
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002249 if (Queue.empty())
2250 break;
2251 T = Queue.pop_back_val();
Douglas Gregore254f902009-02-04 00:32:51 +00002252 }
Douglas Gregore254f902009-02-04 00:32:51 +00002253}
2254
2255/// \brief Find the associated classes and namespaces for
2256/// argument-dependent lookup for a call with the given set of
2257/// arguments.
2258///
2259/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00002260/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00002261/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00002262void Sema::FindAssociatedClassesAndNamespaces(
2263 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2264 AssociatedNamespaceSet &AssociatedNamespaces,
2265 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00002266 AssociatedNamespaces.clear();
2267 AssociatedClasses.clear();
2268
John McCall7d8b0412012-08-24 20:38:34 +00002269 AssociatedLookup Result(*this, InstantiationLoc,
2270 AssociatedNamespaces, AssociatedClasses);
John McCallf24d7bb2010-05-28 18:45:08 +00002271
Douglas Gregore254f902009-02-04 00:32:51 +00002272 // C++ [basic.lookup.koenig]p2:
2273 // For each argument type T in the function call, there is a set
2274 // of zero or more associated namespaces and a set of zero or more
2275 // associated classes to be considered. The sets of namespaces and
2276 // classes is determined entirely by the types of the function
2277 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00002278 // argument).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002279 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
Douglas Gregore254f902009-02-04 00:32:51 +00002280 Expr *Arg = Args[ArgIdx];
2281
2282 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00002283 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002284 continue;
2285 }
2286
2287 // [...] In addition, if the argument is the name or address of a
2288 // set of overloaded functions and/or function templates, its
2289 // associated classes and namespaces are the union of those
2290 // associated with each of the members of the set: the namespace
2291 // in which the function or function template is defined and the
2292 // classes and namespaces associated with its (non-dependent)
2293 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002294 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002295 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002296 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002297 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002298
John McCallf24d7bb2010-05-28 18:45:08 +00002299 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2300 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002301
John McCallf24d7bb2010-05-28 18:45:08 +00002302 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2303 I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002304 // Look through any using declarations to find the underlying function.
Alp Tokera2794f92014-01-22 07:29:52 +00002305 FunctionDecl *FDecl = (*I)->getUnderlyingDecl()->getAsFunction();
Douglas Gregore254f902009-02-04 00:32:51 +00002306
2307 // Add the classes and namespaces associated with the parameter
2308 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002309 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002310 }
2311 }
2312}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002313
John McCall5cebab12009-11-18 07:57:50 +00002314NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002315 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002316 LookupNameKind NameKind,
2317 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002318 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002319 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002320 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002321}
2322
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002323/// \brief Find the protocol with the given name, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002324ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
Douglas Gregor32c17572012-01-01 20:30:41 +00002325 SourceLocation IdLoc,
2326 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002327 Decl *D = LookupSingleName(TUScope, II, IdLoc,
Douglas Gregor32c17572012-01-01 20:30:41 +00002328 LookupObjCProtocolName, Redecl);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002329 return cast_or_null<ObjCProtocolDecl>(D);
2330}
2331
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002332void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002333 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002334 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002335 // C++ [over.match.oper]p3:
2336 // -- The set of non-member candidates is the result of the
2337 // unqualified lookup of operator@ in the context of the
2338 // expression according to the usual rules for name lookup in
2339 // unqualified function calls (3.4.2) except that all member
Richard Smith100b24a2014-04-17 01:52:14 +00002340 // functions are ignored.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002341 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002342 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2343 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002344
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002345 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
Richard Smith100b24a2014-04-17 01:52:14 +00002346 Functions.append(Operators.begin(), Operators.end());
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002347}
2348
Alexis Hunt1da39282011-06-24 02:11:39 +00002349Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002350 CXXSpecialMember SM,
2351 bool ConstArg,
2352 bool VolatileArg,
2353 bool RValueThis,
2354 bool ConstThis,
2355 bool VolatileThis) {
Richard Smith7d125a12012-11-27 21:20:31 +00002356 assert(CanDeclareSpecialMemberFunction(RD) &&
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002357 "doing special member lookup into record that isn't fully complete");
Richard Smith7d125a12012-11-27 21:20:31 +00002358 RD = RD->getDefinition();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002359 if (RValueThis || ConstThis || VolatileThis)
2360 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2361 "constructors and destructors always have unqualified lvalue this");
2362 if (ConstArg || VolatileArg)
2363 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2364 "parameter-less special members can't have qualified arguments");
2365
2366 llvm::FoldingSetNodeID ID;
Alexis Hunt1da39282011-06-24 02:11:39 +00002367 ID.AddPointer(RD);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002368 ID.AddInteger(SM);
2369 ID.AddInteger(ConstArg);
2370 ID.AddInteger(VolatileArg);
2371 ID.AddInteger(RValueThis);
2372 ID.AddInteger(ConstThis);
2373 ID.AddInteger(VolatileThis);
2374
2375 void *InsertPoint;
2376 SpecialMemberOverloadResult *Result =
2377 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2378
2379 // This was already cached
2380 if (Result)
2381 return Result;
2382
Alexis Huntba8e18d2011-06-07 00:11:58 +00002383 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2384 Result = new (Result) SpecialMemberOverloadResult(ID);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002385 SpecialMemberCache.InsertNode(Result, InsertPoint);
2386
2387 if (SM == CXXDestructor) {
Richard Smith2be35f52012-12-01 02:35:44 +00002388 if (RD->needsImplicitDestructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002389 DeclareImplicitDestructor(RD);
2390 CXXDestructorDecl *DD = RD->getDestructor();
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002391 assert(DD && "record without a destructor");
2392 Result->setMethod(DD);
Richard Smith852265f2012-03-30 20:53:28 +00002393 Result->setKind(DD->isDeleted() ?
2394 SpecialMemberOverloadResult::NoMemberOrDeleted :
Richard Smith83c478d2012-04-20 18:46:14 +00002395 SpecialMemberOverloadResult::Success);
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002396 return Result;
2397 }
2398
Alexis Hunteef8ee02011-06-10 03:50:41 +00002399 // Prepare for overload resolution. Here we construct a synthetic argument
2400 // if necessary and make sure that implicit functions are declared.
Alexis Hunt1da39282011-06-24 02:11:39 +00002401 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
Alexis Hunteef8ee02011-06-10 03:50:41 +00002402 DeclarationName Name;
2403 Expr *Arg = 0;
2404 unsigned NumArgs;
2405
Richard Smith83c478d2012-04-20 18:46:14 +00002406 QualType ArgType = CanTy;
2407 ExprValueKind VK = VK_LValue;
2408
Alexis Hunteef8ee02011-06-10 03:50:41 +00002409 if (SM == CXXDefaultConstructor) {
2410 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2411 NumArgs = 0;
Alexis Hunt1da39282011-06-24 02:11:39 +00002412 if (RD->needsImplicitDefaultConstructor())
2413 DeclareImplicitDefaultConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002414 } else {
2415 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2416 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
Richard Smith2be35f52012-12-01 02:35:44 +00002417 if (RD->needsImplicitCopyConstructor())
Alexis Hunt1da39282011-06-24 02:11:39 +00002418 DeclareImplicitCopyConstructor(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002419 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002420 DeclareImplicitMoveConstructor(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002421 } else {
2422 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Richard Smith2be35f52012-12-01 02:35:44 +00002423 if (RD->needsImplicitCopyAssignment())
Alexis Hunt1da39282011-06-24 02:11:39 +00002424 DeclareImplicitCopyAssignment(RD);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002425 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002426 DeclareImplicitMoveAssignment(RD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002427 }
2428
Alexis Hunteef8ee02011-06-10 03:50:41 +00002429 if (ConstArg)
2430 ArgType.addConst();
2431 if (VolatileArg)
2432 ArgType.addVolatile();
2433
2434 // This isn't /really/ specified by the standard, but it's implied
2435 // we should be working from an RValue in the case of move to ensure
2436 // that we prefer to bind to rvalue references, and an LValue in the
2437 // case of copy to ensure we don't bind to rvalue references.
2438 // Possibly an XValue is actually correct in the case of move, but
2439 // there is no semantic difference for class types in this restricted
2440 // case.
Alexis Hunt46d1ce22011-06-22 22:13:13 +00002441 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
Alexis Hunteef8ee02011-06-10 03:50:41 +00002442 VK = VK_LValue;
2443 else
2444 VK = VK_RValue;
Richard Smith83c478d2012-04-20 18:46:14 +00002445 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00002446
Richard Smith83c478d2012-04-20 18:46:14 +00002447 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2448
2449 if (SM != CXXDefaultConstructor) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002450 NumArgs = 1;
Richard Smith83c478d2012-04-20 18:46:14 +00002451 Arg = &FakeArg;
Alexis Hunteef8ee02011-06-10 03:50:41 +00002452 }
2453
2454 // Create the object argument
2455 QualType ThisTy = CanTy;
2456 if (ConstThis)
2457 ThisTy.addConst();
2458 if (VolatileThis)
2459 ThisTy.addVolatile();
Alexis Hunt080709f2011-06-23 00:26:20 +00002460 Expr::Classification Classification =
Richard Smith83c478d2012-04-20 18:46:14 +00002461 OpaqueValueExpr(SourceLocation(), ThisTy,
2462 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002463
2464 // Now we perform lookup on the name we computed earlier and do overload
2465 // resolution. Lookup is only performed directly into the class since there
2466 // will always be a (possibly implicit) declaration to shadow any others.
Richard Smith100b24a2014-04-17 01:52:14 +00002467 OverloadCandidateSet OCS(RD->getLocation(), OverloadCandidateSet::CSK_Normal);
David Blaikieff7d47a2012-12-19 00:45:41 +00002468 DeclContext::lookup_result R = RD->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00002469 assert(!R.empty() &&
Alexis Hunteef8ee02011-06-10 03:50:41 +00002470 "lookup for a constructor or assignment operator was empty");
Chandler Carruth7deaae72013-08-18 07:20:52 +00002471
2472 // Copy the candidates as our processing of them may load new declarations
2473 // from an external source and invalidate lookup_result.
2474 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2475
2476 for (SmallVectorImpl<NamedDecl *>::iterator I = Candidates.begin(),
Richard Smithd55889a2013-09-09 16:55:27 +00002477 E = Candidates.end();
Chandler Carruth7deaae72013-08-18 07:20:52 +00002478 I != E; ++I) {
2479 NamedDecl *Cand = *I;
Alexis Hunt080709f2011-06-23 00:26:20 +00002480
Alexis Hunt1da39282011-06-24 02:11:39 +00002481 if (Cand->isInvalidDecl())
Alexis Hunteef8ee02011-06-10 03:50:41 +00002482 continue;
2483
Alexis Hunt1da39282011-06-24 02:11:39 +00002484 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2485 // FIXME: [namespace.udecl]p15 says that we should only consider a
2486 // using declaration here if it does not match a declaration in the
2487 // derived class. We do not implement this correctly in other cases
2488 // either.
2489 Cand = U->getTargetDecl();
2490
2491 if (Cand->isInvalidDecl())
2492 continue;
2493 }
2494
2495 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002496 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
Alexis Hunt1da39282011-06-24 02:11:39 +00002497 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002498 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2499 OCS, true);
Alexis Hunt080709f2011-06-23 00:26:20 +00002500 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002501 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2502 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
Alexis Hunt2949f022011-06-22 02:58:46 +00002503 } else if (FunctionTemplateDecl *Tmpl =
Alexis Hunt1da39282011-06-24 02:11:39 +00002504 dyn_cast<FunctionTemplateDecl>(Cand)) {
Alexis Hunt080709f2011-06-23 00:26:20 +00002505 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2506 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002507 RD, 0, ThisTy, Classification,
2508 llvm::makeArrayRef(&Arg, NumArgs),
Alexis Hunt080709f2011-06-23 00:26:20 +00002509 OCS, true);
2510 else
2511 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002512 0, llvm::makeArrayRef(&Arg, NumArgs),
2513 OCS, true);
Alexis Hunt1da39282011-06-24 02:11:39 +00002514 } else {
2515 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
Alexis Hunteef8ee02011-06-10 03:50:41 +00002516 }
2517 }
2518
2519 OverloadCandidateSet::iterator Best;
2520 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2521 case OR_Success:
2522 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith83c478d2012-04-20 18:46:14 +00002523 Result->setKind(SpecialMemberOverloadResult::Success);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002524 break;
2525
2526 case OR_Deleted:
2527 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
Richard Smith852265f2012-03-30 20:53:28 +00002528 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002529 break;
2530
2531 case OR_Ambiguous:
Richard Smith852265f2012-03-30 20:53:28 +00002532 Result->setMethod(0);
2533 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2534 break;
2535
Alexis Hunteef8ee02011-06-10 03:50:41 +00002536 case OR_No_Viable_Function:
2537 Result->setMethod(0);
Richard Smith852265f2012-03-30 20:53:28 +00002538 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
Alexis Hunteef8ee02011-06-10 03:50:41 +00002539 break;
2540 }
2541
2542 return Result;
2543}
2544
2545/// \brief Look up the default constructor for the given class.
2546CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002547 SpecialMemberOverloadResult *Result =
Alexis Hunteef8ee02011-06-10 03:50:41 +00002548 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2549 false, false);
2550
2551 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002552}
2553
Alexis Hunt491ec602011-06-21 23:42:56 +00002554/// \brief Look up the copying constructor for the given class.
2555CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
Richard Smith83c478d2012-04-20 18:46:14 +00002556 unsigned Quals) {
Alexis Hunt899bd442011-06-10 04:44:37 +00002557 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2558 "non-const, non-volatile qualifiers for copy ctor arg");
2559 SpecialMemberOverloadResult *Result =
2560 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2561 Quals & Qualifiers::Volatile, false, false, false);
2562
Alexis Hunt899bd442011-06-10 04:44:37 +00002563 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2564}
2565
Sebastian Redl22653ba2011-08-30 19:58:05 +00002566/// \brief Look up the moving constructor for the given class.
Richard Smith1c6461e2012-07-18 03:36:00 +00002567CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2568 unsigned Quals) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002569 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002570 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2571 Quals & Qualifiers::Volatile, false, false, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002572
2573 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2574}
2575
Douglas Gregor52b72822010-07-02 23:12:18 +00002576/// \brief Look up the constructors for the given class.
2577DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00002578 // If the implicit constructors have not yet been declared, do so now.
Richard Smith7d125a12012-11-27 21:20:31 +00002579 if (CanDeclareSpecialMemberFunction(Class)) {
Alexis Huntea6f0322011-05-11 22:34:38 +00002580 if (Class->needsImplicitDefaultConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002581 DeclareImplicitDefaultConstructor(Class);
Richard Smith2be35f52012-12-01 02:35:44 +00002582 if (Class->needsImplicitCopyConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002583 DeclareImplicitCopyConstructor(Class);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002584 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
Sebastian Redl22653ba2011-08-30 19:58:05 +00002585 DeclareImplicitMoveConstructor(Class);
Douglas Gregor9672f922010-07-03 00:47:00 +00002586 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002587
Douglas Gregor52b72822010-07-02 23:12:18 +00002588 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2589 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2590 return Class->lookup(Name);
2591}
2592
Alexis Hunt491ec602011-06-21 23:42:56 +00002593/// \brief Look up the copying assignment operator for the given class.
2594CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2595 unsigned Quals, bool RValueThis,
Richard Smith83c478d2012-04-20 18:46:14 +00002596 unsigned ThisQuals) {
Alexis Hunt491ec602011-06-21 23:42:56 +00002597 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2598 "non-const, non-volatile qualifiers for copy assignment arg");
2599 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2600 "non-const, non-volatile qualifiers for copy assignment this");
2601 SpecialMemberOverloadResult *Result =
2602 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2603 Quals & Qualifiers::Volatile, RValueThis,
2604 ThisQuals & Qualifiers::Const,
2605 ThisQuals & Qualifiers::Volatile);
2606
Alexis Hunt491ec602011-06-21 23:42:56 +00002607 return Result->getMethod();
2608}
2609
Sebastian Redl22653ba2011-08-30 19:58:05 +00002610/// \brief Look up the moving assignment operator for the given class.
2611CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
Richard Smith1c6461e2012-07-18 03:36:00 +00002612 unsigned Quals,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002613 bool RValueThis,
2614 unsigned ThisQuals) {
2615 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2616 "non-const, non-volatile qualifiers for copy assignment this");
2617 SpecialMemberOverloadResult *Result =
Richard Smith1c6461e2012-07-18 03:36:00 +00002618 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2619 Quals & Qualifiers::Volatile, RValueThis,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002620 ThisQuals & Qualifiers::Const,
2621 ThisQuals & Qualifiers::Volatile);
2622
2623 return Result->getMethod();
2624}
2625
Douglas Gregore71edda2010-07-01 22:47:18 +00002626/// \brief Look for the destructor of the given class.
2627///
Alexis Hunt967ea7c2011-06-03 21:10:40 +00002628/// During semantic analysis, this routine should be used in lieu of
2629/// CXXRecordDecl::getDestructor().
Douglas Gregore71edda2010-07-01 22:47:18 +00002630///
2631/// \returns The destructor for this class.
2632CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Alexis Hunt4ac55e32011-06-04 04:32:43 +00002633 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2634 false, false, false,
2635 false, false)->getMethod());
Douglas Gregore71edda2010-07-01 22:47:18 +00002636}
2637
Richard Smithbcc22fc2012-03-09 08:00:36 +00002638/// LookupLiteralOperator - Determine which literal operator should be used for
2639/// a user-defined literal, per C++11 [lex.ext].
2640///
2641/// Normal overload resolution is not used to select which literal operator to
2642/// call for a user-defined literal. Look up the provided literal operator name,
2643/// and filter the results to the appropriate set for the given argument types.
2644Sema::LiteralOperatorLookupResult
2645Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2646 ArrayRef<QualType> ArgTys,
Richard Smithb8b41d32013-10-07 19:57:58 +00002647 bool AllowRaw, bool AllowTemplate,
2648 bool AllowStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002649 LookupName(R, S);
2650 assert(R.getResultKind() != LookupResult::Ambiguous &&
2651 "literal operator lookup can't be ambiguous");
2652
2653 // Filter the lookup results appropriately.
2654 LookupResult::Filter F = R.makeFilter();
2655
Richard Smithbcc22fc2012-03-09 08:00:36 +00002656 bool FoundRaw = false;
Richard Smithb8b41d32013-10-07 19:57:58 +00002657 bool FoundTemplate = false;
2658 bool FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002659 bool FoundExactMatch = false;
2660
2661 while (F.hasNext()) {
2662 Decl *D = F.next();
2663 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2664 D = USD->getTargetDecl();
2665
Douglas Gregorc1970572013-04-10 05:18:00 +00002666 // If the declaration we found is invalid, skip it.
2667 if (D->isInvalidDecl()) {
2668 F.erase();
2669 continue;
2670 }
2671
Richard Smithb8b41d32013-10-07 19:57:58 +00002672 bool IsRaw = false;
2673 bool IsTemplate = false;
2674 bool IsStringTemplate = false;
2675 bool IsExactMatch = false;
2676
Richard Smithbcc22fc2012-03-09 08:00:36 +00002677 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2678 if (FD->getNumParams() == 1 &&
2679 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2680 IsRaw = true;
Richard Smith550de452013-01-15 07:12:59 +00002681 else if (FD->getNumParams() == ArgTys.size()) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002682 IsExactMatch = true;
2683 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2684 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2685 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2686 IsExactMatch = false;
2687 break;
2688 }
2689 }
2690 }
2691 }
Richard Smithb8b41d32013-10-07 19:57:58 +00002692 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
2693 TemplateParameterList *Params = FD->getTemplateParameters();
2694 if (Params->size() == 1)
2695 IsTemplate = true;
2696 else
2697 IsStringTemplate = true;
2698 }
Richard Smithbcc22fc2012-03-09 08:00:36 +00002699
2700 if (IsExactMatch) {
2701 FoundExactMatch = true;
Richard Smithb8b41d32013-10-07 19:57:58 +00002702 AllowRaw = false;
2703 AllowTemplate = false;
2704 AllowStringTemplate = false;
2705 if (FoundRaw || FoundTemplate || FoundStringTemplate) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00002706 // Go through again and remove the raw and template decls we've
2707 // already found.
2708 F.restart();
Richard Smithb8b41d32013-10-07 19:57:58 +00002709 FoundRaw = FoundTemplate = FoundStringTemplate = false;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002710 }
Richard Smithb8b41d32013-10-07 19:57:58 +00002711 } else if (AllowRaw && IsRaw) {
2712 FoundRaw = true;
2713 } else if (AllowTemplate && IsTemplate) {
2714 FoundTemplate = true;
2715 } else if (AllowStringTemplate && IsStringTemplate) {
2716 FoundStringTemplate = true;
Richard Smithbcc22fc2012-03-09 08:00:36 +00002717 } else {
2718 F.erase();
2719 }
2720 }
2721
2722 F.done();
2723
2724 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2725 // parameter type, that is used in preference to a raw literal operator
2726 // or literal operator template.
2727 if (FoundExactMatch)
2728 return LOLR_Cooked;
2729
2730 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2731 // operator template, but not both.
2732 if (FoundRaw && FoundTemplate) {
2733 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
Alp Tokera2794f92014-01-22 07:29:52 +00002734 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2735 NoteOverloadCandidate((*I)->getUnderlyingDecl()->getAsFunction());
Richard Smithbcc22fc2012-03-09 08:00:36 +00002736 return LOLR_Error;
2737 }
2738
2739 if (FoundRaw)
2740 return LOLR_Raw;
2741
2742 if (FoundTemplate)
2743 return LOLR_Template;
2744
Richard Smithb8b41d32013-10-07 19:57:58 +00002745 if (FoundStringTemplate)
2746 return LOLR_StringTemplate;
2747
Richard Smithbcc22fc2012-03-09 08:00:36 +00002748 // Didn't find anything we could use.
2749 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2750 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
Richard Smithb8b41d32013-10-07 19:57:58 +00002751 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
2752 << (AllowTemplate || AllowStringTemplate);
Richard Smithbcc22fc2012-03-09 08:00:36 +00002753 return LOLR_Error;
2754}
2755
John McCall8fe68082010-01-26 07:16:45 +00002756void ADLResult::insert(NamedDecl *New) {
2757 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2758
2759 // If we haven't yet seen a decl for this key, or the last decl
2760 // was exactly this one, we're done.
2761 if (Old == 0 || Old == New) {
2762 Old = New;
2763 return;
2764 }
2765
2766 // Otherwise, decide which is a more recent redeclaration.
Alp Tokera2794f92014-01-22 07:29:52 +00002767 FunctionDecl *OldFD = Old->getAsFunction();
2768 FunctionDecl *NewFD = New->getAsFunction();
John McCall8fe68082010-01-26 07:16:45 +00002769
2770 FunctionDecl *Cursor = NewFD;
2771 while (true) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002772 Cursor = Cursor->getPreviousDecl();
John McCall8fe68082010-01-26 07:16:45 +00002773
2774 // If we got to the end without finding OldFD, OldFD is the newer
2775 // declaration; leave things as they are.
2776 if (!Cursor) return;
2777
2778 // If we do find OldFD, then NewFD is newer.
2779 if (Cursor == OldFD) break;
2780
2781 // Otherwise, keep looking.
2782 }
2783
2784 Old = New;
2785}
2786
Richard Smith100b24a2014-04-17 01:52:14 +00002787void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
2788 ArrayRef<Expr *> Args, ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002789 // Find all of the associated namespaces and classes based on the
2790 // arguments we have.
2791 AssociatedNamespaceSet AssociatedNamespaces;
2792 AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00002793 FindAssociatedClassesAndNamespaces(Loc, Args,
John McCallc7e8e792009-08-07 22:18:02 +00002794 AssociatedNamespaces,
2795 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002796
2797 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002798 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2799 // and let Y be the lookup set produced by argument dependent
2800 // lookup (defined as follows). If X contains [...] then Y is
2801 // empty. Otherwise Y is the set of declarations found in the
2802 // namespaces associated with the argument types as described
2803 // below. The set of declarations found by the lookup of the name
2804 // is the union of X and Y.
2805 //
2806 // Here, we compute Y and add its members to the overloaded
2807 // candidate set.
2808 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00002809 NSEnd = AssociatedNamespaces.end();
2810 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002811 // When considering an associated namespace, the lookup is the
2812 // same as the lookup performed when the associated namespace is
2813 // used as a qualifier (3.4.3.2) except that:
2814 //
2815 // -- Any using-directives in the associated namespace are
2816 // ignored.
2817 //
John McCallc7e8e792009-08-07 22:18:02 +00002818 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002819 // associated classes are visible within their respective
2820 // namespaces even if they are not visible during an ordinary
2821 // lookup (11.4).
David Blaikieff7d47a2012-12-19 00:45:41 +00002822 DeclContext::lookup_result R = (*NS)->lookup(Name);
2823 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
2824 ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00002825 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00002826 // If the only declaration here is an ordinary friend, consider
2827 // it only if it was declared in an associated classes.
Richard Smith541b38b2013-09-20 01:15:31 +00002828 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) {
2829 // If it's neither ordinarily visible nor a friend, we can't find it.
2830 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0)
2831 continue;
2832
Richard Smith64017682013-07-17 23:53:16 +00002833 bool DeclaredInAssociatedClass = false;
2834 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
2835 DeclContext *LexDC = DI->getLexicalDeclContext();
2836 if (isa<CXXRecordDecl>(LexDC) &&
2837 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) {
2838 DeclaredInAssociatedClass = true;
2839 break;
2840 }
2841 }
2842 if (!DeclaredInAssociatedClass)
John McCalld1e9d832009-08-11 06:59:38 +00002843 continue;
2844 }
Mike Stump11289f42009-09-09 15:08:12 +00002845
John McCall91f61fc2010-01-26 06:04:06 +00002846 if (isa<UsingShadowDecl>(D))
2847 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002848
Richard Smith100b24a2014-04-17 01:52:14 +00002849 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D))
John McCall8fe68082010-01-26 07:16:45 +00002850 continue;
2851
2852 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002853 }
2854 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002855}
Douglas Gregor2d435302009-12-30 17:04:44 +00002856
2857//----------------------------------------------------------------------------
2858// Search for all visible declarations.
2859//----------------------------------------------------------------------------
2860VisibleDeclConsumer::~VisibleDeclConsumer() { }
2861
Richard Smithe156254d2013-08-20 20:35:18 +00002862bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
2863
Douglas Gregor2d435302009-12-30 17:04:44 +00002864namespace {
2865
2866class ShadowContextRAII;
2867
2868class VisibleDeclsRecord {
2869public:
2870 /// \brief An entry in the shadow map, which is optimized to store a
2871 /// single declaration (the common case) but can also store a list
2872 /// of declarations.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002873 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
Douglas Gregor2d435302009-12-30 17:04:44 +00002874
2875private:
2876 /// \brief A mapping from declaration names to the declarations that have
2877 /// this name within a particular scope.
2878 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2879
2880 /// \brief A list of shadow maps, which is used to model name hiding.
2881 std::list<ShadowMap> ShadowMaps;
2882
2883 /// \brief The declaration contexts we have already visited.
2884 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2885
2886 friend class ShadowContextRAII;
2887
2888public:
2889 /// \brief Determine whether we have already visited this context
2890 /// (and, if not, note that we are going to visit that context now).
2891 bool visitedContext(DeclContext *Ctx) {
2892 return !VisitedContexts.insert(Ctx);
2893 }
2894
Douglas Gregor39982192010-08-15 06:18:01 +00002895 bool alreadyVisitedContext(DeclContext *Ctx) {
2896 return VisitedContexts.count(Ctx);
2897 }
2898
Douglas Gregor2d435302009-12-30 17:04:44 +00002899 /// \brief Determine whether the given declaration is hidden in the
2900 /// current scope.
2901 ///
2902 /// \returns the declaration that hides the given declaration, or
2903 /// NULL if no such declaration exists.
2904 NamedDecl *checkHidden(NamedDecl *ND);
2905
2906 /// \brief Add a declaration to the current shadow map.
Chris Lattner83cfc7c2011-07-18 01:54:02 +00002907 void add(NamedDecl *ND) {
2908 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2909 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002910};
2911
2912/// \brief RAII object that records when we've entered a shadow context.
2913class ShadowContextRAII {
2914 VisibleDeclsRecord &Visible;
2915
2916 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2917
2918public:
2919 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2920 Visible.ShadowMaps.push_back(ShadowMap());
2921 }
2922
2923 ~ShadowContextRAII() {
Douglas Gregor2d435302009-12-30 17:04:44 +00002924 Visible.ShadowMaps.pop_back();
2925 }
2926};
2927
2928} // end anonymous namespace
2929
Douglas Gregor2d435302009-12-30 17:04:44 +00002930NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002931 // Look through using declarations.
2932 ND = ND->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002933
Douglas Gregor2d435302009-12-30 17:04:44 +00002934 unsigned IDNS = ND->getIdentifierNamespace();
2935 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2936 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2937 SM != SMEnd; ++SM) {
2938 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2939 if (Pos == SM->end())
2940 continue;
2941
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002942 for (ShadowMapEntry::iterator I = Pos->second.begin(),
Douglas Gregor2d435302009-12-30 17:04:44 +00002943 IEnd = Pos->second.end();
2944 I != IEnd; ++I) {
2945 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +00002946 if ((*I)->hasTagIdentifierNamespace() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002947 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Douglas Gregor2d435302009-12-30 17:04:44 +00002948 Decl::IDNS_ObjCProtocol)))
2949 continue;
2950
2951 // Protocols are in distinct namespaces from everything else.
2952 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2953 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2954 (*I)->getIdentifierNamespace() != IDNS)
2955 continue;
2956
Douglas Gregor09bbc652010-01-14 15:47:35 +00002957 // Functions and function templates in the same scope overload
2958 // rather than hide. FIXME: Look for hiding based on function
2959 // signatures!
Alp Tokera2794f92014-01-22 07:29:52 +00002960 if ((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
2961 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002962 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002963 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002964
Douglas Gregor2d435302009-12-30 17:04:44 +00002965 // We've found a declaration that hides this one.
2966 return *I;
2967 }
2968 }
2969
2970 return 0;
2971}
2972
2973static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2974 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002975 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002976 VisibleDeclConsumer &Consumer,
2977 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002978 if (!Ctx)
2979 return;
2980
Douglas Gregor2d435302009-12-30 17:04:44 +00002981 // Make sure we don't visit the same context twice.
2982 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2983 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002984
Douglas Gregor7454c562010-07-02 20:37:36 +00002985 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2986 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2987
Douglas Gregor2d435302009-12-30 17:04:44 +00002988 // Enumerate all of the results in this context.
Aaron Ballman576114e2014-03-14 15:28:49 +00002989 for (const auto &R : Ctx->lookups()) {
2990 for (auto *I : R) {
2991 if (NamedDecl *ND = dyn_cast<NamedDecl>(I)) {
Douglas Gregor4a814562011-12-14 16:03:29 +00002992 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00002993 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002994 Visited.add(ND);
2995 }
Douglas Gregora3b23b02010-12-09 21:44:02 +00002996 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002997 }
2998 }
2999
3000 // Traverse using directives for qualified name lookup.
3001 if (QualifiedNameLookup) {
3002 ShadowContextRAII Shadow(Visited);
Aaron Ballman804a7fb2014-03-17 17:14:12 +00003003 for (auto I : Ctx->using_directives()) {
Aaron Ballman63ab7602014-03-07 13:44:44 +00003004 LookupVisibleDecls(I->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003005 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003006 }
3007 }
3008
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003009 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00003010 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00003011 if (!Record->hasDefinition())
3012 return;
3013
Aaron Ballman574705e2014-03-13 15:41:46 +00003014 for (const auto &B : Record->bases()) {
3015 QualType BaseType = B.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003016
Douglas Gregor2d435302009-12-30 17:04:44 +00003017 // Don't look into dependent bases, because name lookup can't look
3018 // there anyway.
3019 if (BaseType->isDependentType())
3020 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003021
Douglas Gregor2d435302009-12-30 17:04:44 +00003022 const RecordType *Record = BaseType->getAs<RecordType>();
3023 if (!Record)
3024 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003025
Douglas Gregor2d435302009-12-30 17:04:44 +00003026 // FIXME: It would be nice to be able to determine whether referencing
3027 // a particular member would be ambiguous. For example, given
3028 //
3029 // struct A { int member; };
3030 // struct B { int member; };
3031 // struct C : A, B { };
3032 //
3033 // void f(C *c) { c->### }
3034 //
3035 // accessing 'member' would result in an ambiguity. However, we
3036 // could be smart enough to qualify the member with the base
3037 // class, e.g.,
3038 //
3039 // c->B::member
3040 //
3041 // or
3042 //
3043 // c->A::member
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003044
Douglas Gregor2d435302009-12-30 17:04:44 +00003045 // Find results in this base class (and its bases).
3046 ShadowContextRAII Shadow(Visited);
3047 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003048 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003049 }
3050 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003051
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003052 // Traverse the contexts of Objective-C classes.
3053 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3054 // Traverse categories.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003055 for (auto *Cat : IFace->visible_categories()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003056 ShadowContextRAII Shadow(Visited);
Aaron Ballman3fe486a2014-03-13 21:23:55 +00003057 LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003058 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003059 }
3060
3061 // Traverse protocols.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003062 for (auto *I : IFace->all_referenced_protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003063 ShadowContextRAII Shadow(Visited);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00003064 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003065 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003066 }
3067
3068 // Traverse the superclass.
3069 if (IFace->getSuperClass()) {
3070 ShadowContextRAII Shadow(Visited);
3071 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003072 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003073 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003074
Douglas Gregor0b59e802010-04-19 18:02:19 +00003075 // If there is an implementation, traverse it. We do this to find
3076 // synthesized ivars.
3077 if (IFace->getImplementation()) {
3078 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003079 LookupVisibleDecls(IFace->getImplementation(), Result,
Nick Lewycky13668f22012-04-03 20:26:45 +00003080 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor0b59e802010-04-19 18:02:19 +00003081 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003082 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003083 for (auto *I : Protocol->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003084 ShadowContextRAII Shadow(Visited);
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003085 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003086 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003087 }
3088 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003089 for (auto *I : Category->protocols()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003090 ShadowContextRAII Shadow(Visited);
Aaron Ballman19a41762014-03-14 12:55:57 +00003091 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003092 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003093 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003094
Douglas Gregor0b59e802010-04-19 18:02:19 +00003095 // If there is an implementation, traverse it.
3096 if (Category->getImplementation()) {
3097 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003098 LookupVisibleDecls(Category->getImplementation(), Result,
Douglas Gregor0b59e802010-04-19 18:02:19 +00003099 QualifiedNameLookup, true, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003100 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003101 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003102}
3103
3104static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3105 UnqualUsingDirectiveSet &UDirs,
3106 VisibleDeclConsumer &Consumer,
3107 VisibleDeclsRecord &Visited) {
3108 if (!S)
3109 return;
3110
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003111 if (!S->getEntity() ||
3112 (!S->getParent() &&
Ted Kremenekc37877d2013-10-08 17:08:03 +00003113 !Visited.alreadyVisitedContext(S->getEntity())) ||
3114 (S->getEntity())->isFunctionOrMethod()) {
Richard Smith541b38b2013-09-20 01:15:31 +00003115 FindLocalExternScope FindLocals(Result);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003116 // Walk through the declarations in this Scope.
Aaron Ballman35c54952014-03-17 16:55:25 +00003117 for (auto *D : S->decls()) {
3118 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Douglas Gregor4a814562011-12-14 16:03:29 +00003119 if ((ND = Result.getAcceptableDecl(ND))) {
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003120 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003121 Visited.add(ND);
3122 }
3123 }
3124 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003125
Douglas Gregor66230062010-03-15 14:33:29 +00003126 // FIXME: C++ [temp.local]p8
Douglas Gregor2d435302009-12-30 17:04:44 +00003127 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00003128 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003129 // Look into this scope's declaration context, along with any of its
3130 // parent lookup contexts (e.g., enclosing classes), up to the point
3131 // where we hit the context stored in the next outer scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00003132 Entity = S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00003133 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003134
Douglas Gregorea166062010-03-15 15:26:48 +00003135 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00003136 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003137 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3138 if (Method->isInstanceMethod()) {
3139 // For instance methods, look for ivars in the method's interface.
3140 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3141 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003142 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003143 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Richard Smithe156254d2013-08-20 20:35:18 +00003144 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00003145 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003146 }
3147
3148 // We've already performed all of the name lookup that we need
3149 // to for Objective-C methods; the next context will be the
3150 // outer scope.
3151 break;
3152 }
3153
Douglas Gregor2d435302009-12-30 17:04:44 +00003154 if (Ctx->isFunctionOrMethod())
3155 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003156
3157 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003158 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003159 }
3160 } else if (!S->getParent()) {
3161 // Look into the translation unit scope. We walk through the translation
3162 // unit's declaration context, because the Scope itself won't have all of
3163 // the declarations if we loaded a precompiled header.
3164 // FIXME: We would like the translation unit's Scope object to point to the
3165 // translation unit, so we don't need this special "if" branch. However,
3166 // doing so would force the normal C++ name-lookup code to look into the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003167 // translation unit decl when the IdentifierInfo chains would suffice.
Douglas Gregor2d435302009-12-30 17:04:44 +00003168 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00003169 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00003170 Entity = Result.getSema().Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003171 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003172 /*InBaseClass=*/false, Consumer, Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003173 }
3174
Douglas Gregor2d435302009-12-30 17:04:44 +00003175 if (Entity) {
3176 // Lookup visible declarations in any namespaces found by using
3177 // directives.
3178 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003179 std::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
Douglas Gregor2d435302009-12-30 17:04:44 +00003180 for (; UI != UEnd; ++UI)
3181 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003182 Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003183 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003184 }
3185
3186 // Lookup names in the parent scope.
3187 ShadowContextRAII Shadow(Visited);
3188 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3189}
3190
3191void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003192 VisibleDeclConsumer &Consumer,
3193 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003194 // Determine the set of using directives available during
3195 // unqualified name lookup.
3196 Scope *Initial = S;
3197 UnqualUsingDirectiveSet UDirs;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003198 if (getLangOpts().CPlusPlus) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003199 // Find the first namespace or translation-unit scope.
3200 while (S && !isNamespaceOrTranslationUnitScope(S))
3201 S = S->getParent();
3202
3203 UDirs.visitScopeChain(Initial, S);
3204 }
3205 UDirs.done();
3206
3207 // Look for visible declarations.
3208 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003209 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003210 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003211 if (!IncludeGlobalScope)
3212 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003213 ShadowContextRAII Shadow(Visited);
3214 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3215}
3216
3217void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00003218 VisibleDeclConsumer &Consumer,
3219 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003220 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
Richard Smithe156254d2013-08-20 20:35:18 +00003221 Result.setAllowHidden(Consumer.includeHiddenDecls());
Douglas Gregor2d435302009-12-30 17:04:44 +00003222 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00003223 if (!IncludeGlobalScope)
3224 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00003225 ShadowContextRAII Shadow(Visited);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003226 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
Douglas Gregor09bbc652010-01-14 15:47:35 +00003227 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00003228}
3229
Chris Lattner43e7f312011-02-18 02:08:43 +00003230/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003231/// If GnuLabelLoc is a valid source location, then this is a definition
3232/// of an __label__ label name, otherwise it is a normal label definition
3233/// or use.
Chris Lattner43e7f312011-02-18 02:08:43 +00003234LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003235 SourceLocation GnuLabelLoc) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003236 // Do a lookup to see if we have a label with this name already.
Chris Lattner43e7f312011-02-18 02:08:43 +00003237 NamedDecl *Res = 0;
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003238
3239 if (GnuLabelLoc.isValid()) {
3240 // Local label definitions always shadow existing labels.
3241 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3242 Scope *S = CurScope;
3243 PushOnScopeChains(Res, S, true);
3244 return cast<LabelDecl>(Res);
3245 }
3246
3247 // Not a GNU local label.
3248 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3249 // If we found a label, check to see if it is in the same context as us.
3250 // When in a Block, we don't want to reuse a label in an enclosing function.
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003251 if (Res && Res->getDeclContext() != CurContext)
3252 Res = 0;
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003253 if (Res == 0) {
3254 // If not forward referenced or defined already, create the backing decl.
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003255 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3256 Scope *S = CurScope->getFnParent();
Chris Lattner9ba479b2011-02-18 21:16:39 +00003257 assert(S && "Not in a function?");
3258 PushOnScopeChains(Res, S, true);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003259 }
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003260 return cast<LabelDecl>(Res);
3261}
3262
3263//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003264// Typo correction
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00003265//===----------------------------------------------------------------------===//
Douglas Gregor2d435302009-12-30 17:04:44 +00003266
3267namespace {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003268
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003269typedef SmallVector<TypoCorrection, 1> TypoResultList;
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003270typedef llvm::StringMap<TypoResultList, llvm::BumpPtrAllocator> TypoResultsMap;
Benjamin Kramer73faad62012-04-14 08:26:28 +00003271typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003272
3273static const unsigned MaxTypoDistanceResultSets = 5;
3274
Douglas Gregor2d435302009-12-30 17:04:44 +00003275class TypoCorrectionConsumer : public VisibleDeclConsumer {
3276 /// \brief The name written that is a typo in the source.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003277 StringRef Typo;
Douglas Gregor2d435302009-12-30 17:04:44 +00003278
3279 /// \brief The results found that have the smallest edit distance
3280 /// found (so far) with the typo name.
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003281 ///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003282 /// The pointer value being set to the current DeclContext indicates
3283 /// whether there is a keyword with this name.
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003284 TypoEditDistanceMap CorrectionResults;
Douglas Gregor2d435302009-12-30 17:04:44 +00003285
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003286 Sema &SemaRef;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003287
Douglas Gregor2d435302009-12-30 17:04:44 +00003288public:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003289 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003290 : Typo(Typo->getName()),
Richard Smithe156254d2013-08-20 20:35:18 +00003291 SemaRef(SemaRef) {}
3292
Craig Toppere14c0f82014-03-12 04:55:44 +00003293 bool includeHiddenDecls() const override { return true; }
Douglas Gregor2d435302009-12-30 17:04:44 +00003294
Craig Toppere14c0f82014-03-12 04:55:44 +00003295 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3296 bool InBaseClass) override;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003297 void FoundName(StringRef Name);
3298 void addKeywordResult(StringRef Keyword);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003299 void addName(StringRef Name, NamedDecl *ND, NestedNameSpecifier *NNS = NULL,
3300 bool isKeyword = false);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003301 void addCorrection(TypoCorrection Correction);
Douglas Gregor2d435302009-12-30 17:04:44 +00003302
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003303 typedef TypoResultsMap::iterator result_iterator;
3304 typedef TypoEditDistanceMap::iterator distance_iterator;
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003305 distance_iterator begin() { return CorrectionResults.begin(); }
3306 distance_iterator end() { return CorrectionResults.end(); }
3307 void erase(distance_iterator I) { CorrectionResults.erase(I); }
3308 unsigned size() const { return CorrectionResults.size(); }
3309 bool empty() const { return CorrectionResults.empty(); }
Douglas Gregor2d435302009-12-30 17:04:44 +00003310
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003311 TypoResultList &operator[](StringRef Name) {
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003312 return CorrectionResults.begin()->second[Name];
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003313 }
3314
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003315 unsigned getBestEditDistance(bool Normalized) {
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003316 if (CorrectionResults.empty())
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003317 return (std::numeric_limits<unsigned>::max)();
3318
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003319 unsigned BestED = CorrectionResults.begin()->first;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003320 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003321 }
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003322
3323 TypoResultsMap &getBestResults() {
3324 return CorrectionResults.begin()->second;
3325 }
3326
Douglas Gregor2d435302009-12-30 17:04:44 +00003327};
3328
3329}
3330
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003331void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00003332 DeclContext *Ctx, bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00003333 // Don't consider hidden names for typo correction.
3334 if (Hiding)
3335 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003336
Douglas Gregor2d435302009-12-30 17:04:44 +00003337 // Only consider entities with identifiers for names, ignoring
3338 // special names (constructors, overloaded operators, selectors,
3339 // etc.).
3340 IdentifierInfo *Name = ND->getIdentifier();
3341 if (!Name)
3342 return;
3343
Richard Smithe156254d2013-08-20 20:35:18 +00003344 // Only consider visible declarations and declarations from modules with
3345 // names that exactly match.
3346 if (!LookupResult::isVisible(SemaRef, ND) && Name->getName() != Typo &&
3347 !findAcceptableDecl(SemaRef, ND))
3348 return;
3349
Douglas Gregor57756ea2010-10-14 22:11:03 +00003350 FoundName(Name->getName());
3351}
3352
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003353void TypoCorrectionConsumer::FoundName(StringRef Name) {
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003354 // Compute the edit distance between the typo and the name of this
3355 // entity, and add the identifier to the list of results.
3356 addName(Name, NULL);
3357}
3358
3359void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3360 // Compute the edit distance between the typo and this keyword,
3361 // and add the keyword to the list of results.
3362 addName(Keyword, NULL, NULL, true);
3363}
3364
3365void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
3366 NestedNameSpecifier *NNS, bool isKeyword) {
Douglas Gregor93910a52010-10-19 19:39:10 +00003367 // Use a simple length-based heuristic to determine the minimum possible
3368 // edit distance. If the minimum isn't good enough, bail out early.
3369 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00003370 if (MinED && Typo.size() / MinED < 3)
Douglas Gregor93910a52010-10-19 19:39:10 +00003371 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003372
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00003373 // Compute an upper bound on the allowable edit distance, so that the
3374 // edit-distance algorithm can short-circuit.
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003375 unsigned UpperBound = (Typo.size() + 2) / 3 + 1;
3376 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
3377 if (ED >= UpperBound) return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003378
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003379 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00003380 if (isKeyword) TC.makeKeyword();
3381 addCorrection(TC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003382}
3383
3384void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003385 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003386 TypoResultList &CList =
3387 CorrectionResults[Correction.getEditDistance(false)][Name];
Chandler Carruth7d85c9b2011-06-28 22:48:40 +00003388
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00003389 if (!CList.empty() && !CList.back().isResolved())
3390 CList.pop_back();
3391 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3392 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3393 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3394 RI != RIEnd; ++RI) {
3395 // If the Correction refers to a decl already in the result list,
3396 // replace the existing result if the string representation of Correction
3397 // comes before the current result alphabetically, then stop as there is
3398 // nothing more to be done to add Correction to the candidate set.
3399 if (RI->getCorrectionDecl() == NewND) {
3400 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3401 *RI = Correction;
3402 return;
3403 }
3404 }
3405 }
3406 if (CList.empty() || Correction.isResolved())
3407 CList.push_back(Correction);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003408
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00003409 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
Benjamin Kramer167e9992014-03-02 12:20:24 +00003410 erase(std::prev(CorrectionResults.end()));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003411}
3412
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003413// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3414// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3415// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3416static void getNestedNameSpecifierIdentifiers(
3417 NestedNameSpecifier *NNS,
3418 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3419 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3420 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3421 else
3422 Identifiers.clear();
3423
3424 const IdentifierInfo *II = NULL;
3425
3426 switch (NNS->getKind()) {
3427 case NestedNameSpecifier::Identifier:
3428 II = NNS->getAsIdentifier();
3429 break;
3430
3431 case NestedNameSpecifier::Namespace:
3432 if (NNS->getAsNamespace()->isAnonymousNamespace())
3433 return;
3434 II = NNS->getAsNamespace()->getIdentifier();
3435 break;
3436
3437 case NestedNameSpecifier::NamespaceAlias:
3438 II = NNS->getAsNamespaceAlias()->getIdentifier();
3439 break;
3440
3441 case NestedNameSpecifier::TypeSpecWithTemplate:
3442 case NestedNameSpecifier::TypeSpec:
3443 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3444 break;
3445
3446 case NestedNameSpecifier::Global:
3447 return;
3448 }
3449
3450 if (II)
3451 Identifiers.push_back(II);
3452}
3453
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003454namespace {
3455
3456class SpecifierInfo {
3457 public:
3458 DeclContext* DeclCtx;
3459 NestedNameSpecifier* NameSpecifier;
3460 unsigned EditDistance;
3461
3462 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3463 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3464};
3465
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003466typedef SmallVector<DeclContext*, 4> DeclContextList;
3467typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003468
3469class NamespaceSpecifierSet {
3470 ASTContext &Context;
3471 DeclContextList CurContextChain;
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003472 std::string CurNameSpecifier;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003473 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3474 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003475 bool isSorted;
3476
3477 SpecifierInfoList Specifiers;
3478 llvm::SmallSetVector<unsigned, 4> Distances;
3479 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3480
3481 /// \brief Helper for building the list of DeclContexts between the current
3482 /// context and the top of the translation unit
3483 static DeclContextList BuildContextChain(DeclContext *Start);
3484
3485 void SortNamespaces();
3486
3487 public:
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003488 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3489 CXXScopeSpec *CurScopeSpec)
Benjamin Kramerde1d6232011-07-05 09:46:31 +00003490 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
Kaelyn Uhrain52dd02d2013-06-24 17:49:03 +00003491 isSorted(false) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003492 if (NestedNameSpecifier *NNS =
3493 CurScopeSpec ? CurScopeSpec->getScopeRep() : 0) {
3494 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
3495 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3496
3497 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
3498 }
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003499 // Build the list of identifiers that would be used for an absolute
Benjamin Kramer474261a2012-06-02 10:20:41 +00003500 // (from the global context) NestedNameSpecifier referring to the current
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003501 // context.
3502 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3503 CEnd = CurContextChain.rend();
3504 C != CEnd; ++C) {
3505 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3506 CurContextIdentifiers.push_back(ND->getIdentifier());
3507 }
Kaelyn Uhrain52dd02d2013-06-24 17:49:03 +00003508
3509 // Add the global context as a NestedNameSpecifier
3510 Distances.insert(1);
3511 DistanceMap[1].push_back(
3512 SpecifierInfo(cast<DeclContext>(Context.getTranslationUnitDecl()),
3513 NestedNameSpecifier::GlobalSpecifier(Context), 1));
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003514 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003515
Kaelyn Uhrain5315a462013-10-19 00:04:49 +00003516 /// \brief Add the DeclContext (a namespace or record) to the set, computing
3517 /// the corresponding NestedNameSpecifier and its distance in the process.
3518 void AddNameSpecifier(DeclContext *Ctx);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003519
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003520 typedef SpecifierInfoList::iterator iterator;
3521 iterator begin() {
3522 if (!isSorted) SortNamespaces();
3523 return Specifiers.begin();
3524 }
3525 iterator end() { return Specifiers.end(); }
3526};
3527
3528}
3529
3530DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
Nick Lewycky0d9b3192013-04-08 21:55:21 +00003531 assert(Start && "Building a context chain from a null context");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003532 DeclContextList Chain;
3533 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3534 DC = DC->getLookupParent()) {
3535 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3536 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3537 !(ND && ND->isAnonymousNamespace()))
3538 Chain.push_back(DC->getPrimaryContext());
3539 }
3540 return Chain;
3541}
3542
3543void NamespaceSpecifierSet::SortNamespaces() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003544 SmallVector<unsigned, 4> sortedDistances;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003545 sortedDistances.append(Distances.begin(), Distances.end());
3546
3547 if (sortedDistances.size() > 1)
3548 std::sort(sortedDistances.begin(), sortedDistances.end());
3549
3550 Specifiers.clear();
Craig Topper2341c0d2013-07-04 03:08:24 +00003551 for (SmallVectorImpl<unsigned>::iterator DI = sortedDistances.begin(),
3552 DIEnd = sortedDistances.end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003553 DI != DIEnd; ++DI) {
3554 SpecifierInfoList &SpecList = DistanceMap[*DI];
3555 Specifiers.append(SpecList.begin(), SpecList.end());
3556 }
3557
3558 isSorted = true;
3559}
3560
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003561static unsigned BuildNestedNameSpecifier(ASTContext &Context,
3562 DeclContextList &DeclChain,
3563 NestedNameSpecifier *&NNS) {
3564 unsigned NumSpecifiers = 0;
3565 for (DeclContextList::reverse_iterator C = DeclChain.rbegin(),
3566 CEnd = DeclChain.rend();
3567 C != CEnd; ++C) {
3568 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) {
3569 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3570 ++NumSpecifiers;
3571 } else if (RecordDecl *RD = dyn_cast_or_null<RecordDecl>(*C)) {
3572 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
3573 RD->getTypeForDecl());
3574 ++NumSpecifiers;
3575 }
3576 }
3577 return NumSpecifiers;
3578}
3579
Kaelyn Uhrain5315a462013-10-19 00:04:49 +00003580void NamespaceSpecifierSet::AddNameSpecifier(DeclContext *Ctx) {
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003581 NestedNameSpecifier *NNS = NULL;
3582 unsigned NumSpecifiers = 0;
3583 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
3584 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
3585
3586 // Eliminate common elements from the two DeclContext chains.
3587 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3588 CEnd = CurContextChain.rend();
3589 C != CEnd && !NamespaceDeclChain.empty() &&
3590 NamespaceDeclChain.back() == *C; ++C) {
3591 NamespaceDeclChain.pop_back();
3592 }
3593
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003594 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3595 NumSpecifiers = BuildNestedNameSpecifier(Context, NamespaceDeclChain, NNS);
3596
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003597 // Add an explicit leading '::' specifier if needed.
3598 if (NamespaceDeclChain.empty()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003599 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003600 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003601 NumSpecifiers =
3602 BuildNestedNameSpecifier(Context, FullNamespaceDeclChain, NNS);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003603 } else if (NamedDecl *ND =
3604 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003605 IdentifierInfo *Name = ND->getIdentifier();
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003606 bool SameNameSpecifier = false;
3607 if (std::find(CurNameSpecifierIdentifiers.begin(),
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003608 CurNameSpecifierIdentifiers.end(),
3609 Name) != CurNameSpecifierIdentifiers.end()) {
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003610 std::string NewNameSpecifier;
3611 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
3612 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
3613 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3614 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3615 SpecifierOStream.flush();
3616 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003617 }
Kaelyn Uhrainf7b63e32013-10-19 00:04:52 +00003618 if (SameNameSpecifier ||
3619 std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3620 Name) != CurContextIdentifiers.end()) {
3621 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
3622 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3623 NumSpecifiers =
3624 BuildNestedNameSpecifier(Context, FullNamespaceDeclChain, NNS);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00003625 }
3626 }
3627
3628 // If the built NestedNameSpecifier would be replacing an existing
3629 // NestedNameSpecifier, use the number of component identifiers that
3630 // would need to be changed as the edit distance instead of the number
3631 // of components in the built NestedNameSpecifier.
3632 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3633 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3634 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3635 NumSpecifiers = llvm::ComputeEditDistance(
3636 ArrayRef<const IdentifierInfo *>(CurNameSpecifierIdentifiers),
3637 ArrayRef<const IdentifierInfo *>(NewNameSpecifierIdentifiers));
3638 }
3639
3640 isSorted = false;
3641 Distances.insert(NumSpecifiers);
3642 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
3643}
3644
Douglas Gregord507d772010-10-20 03:06:34 +00003645/// \brief Perform name lookup for a possible result for typo correction.
3646static void LookupPotentialTypoResult(Sema &SemaRef,
3647 LookupResult &Res,
3648 IdentifierInfo *Name,
3649 Scope *S, CXXScopeSpec *SS,
3650 DeclContext *MemberContext,
3651 bool EnteringContext,
Richard Smithe156254d2013-08-20 20:35:18 +00003652 bool isObjCIvarLookup,
3653 bool FindHidden) {
Douglas Gregord507d772010-10-20 03:06:34 +00003654 Res.suppressDiagnostics();
3655 Res.clear();
3656 Res.setLookupName(Name);
Richard Smithe156254d2013-08-20 20:35:18 +00003657 Res.setAllowHidden(FindHidden);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003658 if (MemberContext) {
Douglas Gregord507d772010-10-20 03:06:34 +00003659 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003660 if (isObjCIvarLookup) {
Douglas Gregord507d772010-10-20 03:06:34 +00003661 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3662 Res.addDecl(Ivar);
3663 Res.resolveKind();
3664 return;
3665 }
3666 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003667
Douglas Gregord507d772010-10-20 03:06:34 +00003668 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3669 Res.addDecl(Prop);
3670 Res.resolveKind();
3671 return;
3672 }
3673 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003674
Douglas Gregord507d772010-10-20 03:06:34 +00003675 SemaRef.LookupQualifiedName(Res, MemberContext);
3676 return;
3677 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003678
3679 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
Douglas Gregord507d772010-10-20 03:06:34 +00003680 EnteringContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003681
Douglas Gregord507d772010-10-20 03:06:34 +00003682 // Fake ivar lookup; this should really be part of
3683 // LookupParsedName.
3684 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3685 if (Method->isInstanceMethod() && Method->getClassInterface() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003686 (Res.empty() ||
Douglas Gregord507d772010-10-20 03:06:34 +00003687 (Res.isSingleResult() &&
3688 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003689 if (ObjCIvarDecl *IV
Douglas Gregord507d772010-10-20 03:06:34 +00003690 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3691 Res.addDecl(IV);
3692 Res.resolveKind();
3693 }
3694 }
3695 }
3696}
3697
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003698/// \brief Add keywords to the consumer as possible typo corrections.
3699static void AddKeywordsToConsumer(Sema &SemaRef,
3700 TypoCorrectionConsumer &Consumer,
Richard Smithb3a1df02012-06-08 21:35:42 +00003701 Scope *S, CorrectionCandidateCallback &CCC,
3702 bool AfterNestedNameSpecifier) {
3703 if (AfterNestedNameSpecifier) {
3704 // For 'X::', we know exactly which keywords can appear next.
3705 Consumer.addKeywordResult("template");
3706 if (CCC.WantExpressionKeywords)
3707 Consumer.addKeywordResult("operator");
3708 return;
3709 }
3710
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003711 if (CCC.WantObjCSuper)
3712 Consumer.addKeywordResult("super");
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003713
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003714 if (CCC.WantTypeSpecifiers) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003715 // Add type-specifier keywords to the set of results.
Craig Topperd6d31ac2013-07-15 08:24:27 +00003716 static const char *const CTypeSpecs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003717 "char", "const", "double", "enum", "float", "int", "long", "short",
Douglas Gregor3b22a882011-07-01 21:27:45 +00003718 "signed", "struct", "union", "unsigned", "void", "volatile",
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003719 "_Complex", "_Imaginary",
3720 // storage-specifiers as well
3721 "extern", "inline", "static", "typedef"
3722 };
3723
Craig Toppere5ce8312013-07-15 03:38:40 +00003724 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003725 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3726 Consumer.addKeywordResult(CTypeSpecs[I]);
3727
David Blaikiebbafb8a2012-03-11 07:00:24 +00003728 if (SemaRef.getLangOpts().C99)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003729 Consumer.addKeywordResult("restrict");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003730 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003731 Consumer.addKeywordResult("bool");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003732 else if (SemaRef.getLangOpts().C99)
Douglas Gregor3b22a882011-07-01 21:27:45 +00003733 Consumer.addKeywordResult("_Bool");
3734
David Blaikiebbafb8a2012-03-11 07:00:24 +00003735 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003736 Consumer.addKeywordResult("class");
3737 Consumer.addKeywordResult("typename");
3738 Consumer.addKeywordResult("wchar_t");
3739
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003740 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003741 Consumer.addKeywordResult("char16_t");
3742 Consumer.addKeywordResult("char32_t");
3743 Consumer.addKeywordResult("constexpr");
3744 Consumer.addKeywordResult("decltype");
3745 Consumer.addKeywordResult("thread_local");
3746 }
3747 }
3748
David Blaikiebbafb8a2012-03-11 07:00:24 +00003749 if (SemaRef.getLangOpts().GNUMode)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003750 Consumer.addKeywordResult("typeof");
3751 }
3752
David Blaikiebbafb8a2012-03-11 07:00:24 +00003753 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003754 Consumer.addKeywordResult("const_cast");
3755 Consumer.addKeywordResult("dynamic_cast");
3756 Consumer.addKeywordResult("reinterpret_cast");
3757 Consumer.addKeywordResult("static_cast");
3758 }
3759
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003760 if (CCC.WantExpressionKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003761 Consumer.addKeywordResult("sizeof");
David Blaikiebbafb8a2012-03-11 07:00:24 +00003762 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003763 Consumer.addKeywordResult("false");
3764 Consumer.addKeywordResult("true");
3765 }
3766
David Blaikiebbafb8a2012-03-11 07:00:24 +00003767 if (SemaRef.getLangOpts().CPlusPlus) {
Craig Topperd6d31ac2013-07-15 08:24:27 +00003768 static const char *const CXXExprs[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003769 "delete", "new", "operator", "throw", "typeid"
3770 };
Craig Toppere5ce8312013-07-15 03:38:40 +00003771 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003772 for (unsigned I = 0; I != NumCXXExprs; ++I)
3773 Consumer.addKeywordResult(CXXExprs[I]);
3774
3775 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3776 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3777 Consumer.addKeywordResult("this");
3778
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003779 if (SemaRef.getLangOpts().CPlusPlus11) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003780 Consumer.addKeywordResult("alignof");
3781 Consumer.addKeywordResult("nullptr");
3782 }
3783 }
Jordan Rose58d54722012-06-30 21:33:57 +00003784
3785 if (SemaRef.getLangOpts().C11) {
3786 // FIXME: We should not suggest _Alignof if the alignof macro
3787 // is present.
3788 Consumer.addKeywordResult("_Alignof");
3789 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003790 }
3791
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003792 if (CCC.WantRemainingKeywords) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003793 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3794 // Statements.
Craig Topperd6d31ac2013-07-15 08:24:27 +00003795 static const char *const CStmts[] = {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003796 "do", "else", "for", "goto", "if", "return", "switch", "while" };
Craig Toppere5ce8312013-07-15 03:38:40 +00003797 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003798 for (unsigned I = 0; I != NumCStmts; ++I)
3799 Consumer.addKeywordResult(CStmts[I]);
3800
David Blaikiebbafb8a2012-03-11 07:00:24 +00003801 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003802 Consumer.addKeywordResult("catch");
3803 Consumer.addKeywordResult("try");
3804 }
3805
3806 if (S && S->getBreakParent())
3807 Consumer.addKeywordResult("break");
3808
3809 if (S && S->getContinueParent())
3810 Consumer.addKeywordResult("continue");
3811
3812 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3813 Consumer.addKeywordResult("case");
3814 Consumer.addKeywordResult("default");
3815 }
3816 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003817 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003818 Consumer.addKeywordResult("namespace");
3819 Consumer.addKeywordResult("template");
3820 }
3821
3822 if (S && S->isClassScope()) {
3823 Consumer.addKeywordResult("explicit");
3824 Consumer.addKeywordResult("friend");
3825 Consumer.addKeywordResult("mutable");
3826 Consumer.addKeywordResult("private");
3827 Consumer.addKeywordResult("protected");
3828 Consumer.addKeywordResult("public");
3829 Consumer.addKeywordResult("virtual");
3830 }
3831 }
3832
David Blaikiebbafb8a2012-03-11 07:00:24 +00003833 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003834 Consumer.addKeywordResult("using");
3835
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003836 if (SemaRef.getLangOpts().CPlusPlus11)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003837 Consumer.addKeywordResult("static_assert");
3838 }
3839 }
3840}
3841
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003842static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3843 TypoCorrection &Candidate) {
3844 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3845 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3846}
3847
Richard Smithe156254d2013-08-20 20:35:18 +00003848/// \brief Check whether the declarations found for a typo correction are
3849/// visible, and if none of them are, convert the correction to an 'import
3850/// a module' correction.
3851static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC,
3852 DeclarationName TypoName) {
3853 if (TC.begin() == TC.end())
3854 return;
3855
3856 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3857
3858 for (/**/; DI != DE; ++DI)
3859 if (!LookupResult::isVisible(SemaRef, *DI))
3860 break;
3861 // Nothing to do if all decls are visible.
3862 if (DI == DE)
3863 return;
3864
3865 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3866 bool AnyVisibleDecls = !NewDecls.empty();
3867
3868 for (/**/; DI != DE; ++DI) {
3869 NamedDecl *VisibleDecl = *DI;
3870 if (!LookupResult::isVisible(SemaRef, *DI))
3871 VisibleDecl = findAcceptableDecl(SemaRef, *DI);
3872
3873 if (VisibleDecl) {
3874 if (!AnyVisibleDecls) {
3875 // Found a visible decl, discard all hidden ones.
3876 AnyVisibleDecls = true;
3877 NewDecls.clear();
3878 }
3879 NewDecls.push_back(VisibleDecl);
3880 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
3881 NewDecls.push_back(*DI);
3882 }
3883
3884 if (NewDecls.empty())
3885 TC = TypoCorrection();
3886 else {
3887 TC.setCorrectionDecls(NewDecls);
3888 TC.setRequiresImport(!AnyVisibleDecls);
3889 }
3890}
3891
Douglas Gregor2d435302009-12-30 17:04:44 +00003892/// \brief Try to "correct" a typo in the source code by finding
3893/// visible declarations whose names are similar to the name that was
3894/// present in the source code.
3895///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003896/// \param TypoName the \c DeclarationNameInfo structure that contains
3897/// the name that was present in the source code along with its location.
3898///
3899/// \param LookupKind the name-lookup criteria used to search for the name.
Douglas Gregor2d435302009-12-30 17:04:44 +00003900///
3901/// \param S the scope in which name lookup occurs.
3902///
3903/// \param SS the nested-name-specifier that precedes the name we're
3904/// looking for, if present.
3905///
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003906/// \param CCC A CorrectionCandidateCallback object that provides further
3907/// validation of typo correction candidates. It also provides flags for
3908/// determining the set of keywords permitted.
3909///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003910/// \param MemberContext if non-NULL, the context in which to look for
3911/// a member access expression.
3912///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003913/// \param EnteringContext whether we're entering the context described by
Douglas Gregor598b08f2009-12-31 05:20:13 +00003914/// the nested-name-specifier SS.
3915///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003916/// \param OPT when non-NULL, the search for visible declarations will
3917/// also walk the protocols in the qualified interfaces of \p OPT.
3918///
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003919/// \returns a \c TypoCorrection containing the corrected name if the typo
3920/// along with information such as the \c NamedDecl where the corrected name
3921/// was declared, and any additional \c NestedNameSpecifier needed to access
3922/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3923TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3924 Sema::LookupNameKind LookupKind,
3925 Scope *S, CXXScopeSpec *SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00003926 CorrectionCandidateCallback &CCC,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003927 DeclContext *MemberContext,
3928 bool EnteringContext,
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00003929 const ObjCObjectPointerType *OPT,
3930 bool RecordFailure) {
Kaelyn Uhrainf0aabda2013-08-12 19:54:38 +00003931 // Always let the ExternalSource have the first chance at correction, even
3932 // if we would otherwise have given up.
3933 if (ExternalSource) {
3934 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
3935 TypoName, LookupKind, S, SS, CCC, MemberContext, EnteringContext, OPT))
3936 return Correction;
3937 }
3938
Richard Smith1fff95c2013-09-12 23:28:08 +00003939 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
3940 DisableTypoCorrection)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003941 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003942
Francois Pichet9c391132011-12-03 15:55:29 +00003943 // In Microsoft mode, don't perform typo correction in a template member
3944 // function dependent context because it interferes with the "lookup into
3945 // dependent bases of class templates" feature.
Alp Tokerbfa39342014-01-14 12:51:41 +00003946 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
Francois Pichet9c391132011-12-03 15:55:29 +00003947 isa<CXXMethodDecl>(CurContext))
3948 return TypoCorrection();
3949
Douglas Gregor2d435302009-12-30 17:04:44 +00003950 // We only attempt to correct typos for identifiers.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003951 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
Douglas Gregor2d435302009-12-30 17:04:44 +00003952 if (!Typo)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003953 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00003954
3955 // If the scope specifier itself was invalid, don't try to correct
3956 // typos.
3957 if (SS && SS->isInvalid())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003958 return TypoCorrection();
Douglas Gregor2d435302009-12-30 17:04:44 +00003959
3960 // Never try to correct typos during template deduction or
3961 // instantiation.
3962 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003963 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003964
Argyrios Kyrtzidis3e56dd42013-03-14 22:56:43 +00003965 // Don't try to correct 'super'.
3966 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
3967 return TypoCorrection();
3968
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00003969 // Abort if typo correction already failed for this specific typo.
3970 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
3971 if (locs != TypoCorrectionFailures.end() &&
Aaron Ballman7fc6e1b2013-10-05 19:56:07 +00003972 locs->second.count(TypoName.getLoc()))
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00003973 return TypoCorrection();
3974
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00003975 // Don't try to correct the identifier "vector" when in AltiVec mode.
3976 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
3977 // remove this workaround.
3978 if (getLangOpts().AltiVec && Typo->isStr("vector"))
3979 return TypoCorrection();
3980
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003981 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003982
3983 TypoCorrectionConsumer Consumer(*this, Typo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003984
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003985 // If a callback object considers an empty typo correction candidate to be
3986 // viable, assume it does not do any actual validation of the candidates.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003987 TypoCorrection EmptyCorrection;
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00003988 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00003989
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003990 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor87074f12010-10-20 01:32:02 +00003991 bool IsUnqualifiedLookup = false;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00003992 DeclContext *QualifiedDC = MemberContext;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003993 if (MemberContext) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003994 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003995
3996 // Look in qualified interfaces.
3997 if (OPT) {
Aaron Ballman83731462014-03-17 16:14:00 +00003998 for (auto *I : OPT->quals())
3999 LookupVisibleDecls(I, LookupKind, Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00004000 }
4001 } else if (SS && SS->isSet()) {
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004002 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4003 if (!QualifiedDC)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004004 return TypoCorrection();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004005
Douglas Gregor87074f12010-10-20 01:32:02 +00004006 // Provide a stop gap for files that are just seriously broken. Trying
4007 // to correct all typos can turn into a HUGE performance penalty, causing
4008 // some files to take minutes to get rejected by the parser.
4009 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004010 return TypoCorrection();
Douglas Gregor87074f12010-10-20 01:32:02 +00004011 ++TyposCorrected;
4012
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004013 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
Douglas Gregor2d435302009-12-30 17:04:44 +00004014 } else {
Douglas Gregor87074f12010-10-20 01:32:02 +00004015 IsUnqualifiedLookup = true;
4016 UnqualifiedTyposCorrectedMap::iterator Cached
4017 = UnqualifiedTyposCorrected.find(Typo);
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004018 if (Cached != UnqualifiedTyposCorrected.end()) {
4019 // Add the cached value, unless it's a keyword or fails validation. In the
4020 // keyword case, we'll end up adding the keyword below.
4021 if (Cached->second) {
4022 if (!Cached->second.isKeyword() &&
Serge Pavlovc0cd80f2013-10-14 14:05:48 +00004023 isCandidateViable(CCC, Cached->second)) {
4024 // Do not use correction that is unaccessible in the given scope.
Serge Pavlove8ae13f2013-10-15 14:24:32 +00004025 NamedDecl *CorrectionDecl = Cached->second.getCorrectionDecl();
Serge Pavlovc0cd80f2013-10-14 14:05:48 +00004026 DeclarationNameInfo NameInfo(CorrectionDecl->getDeclName(),
4027 CorrectionDecl->getLocation());
4028 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4029 if (LookupName(R, S))
4030 Consumer.addCorrection(Cached->second);
4031 }
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004032 } else {
4033 // Only honor no-correction cache hits when a callback that will validate
4034 // correction candidates is not being used.
4035 if (!ValidatingCallback)
4036 return TypoCorrection();
4037 }
4038 }
4039 if (Cached == UnqualifiedTyposCorrected.end()) {
Douglas Gregor87074f12010-10-20 01:32:02 +00004040 // Provide a stop gap for files that are just seriously broken. Trying
4041 // to correct all typos can turn into a HUGE performance penalty, causing
4042 // some files to take minutes to get rejected by the parser.
4043 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004044 return TypoCorrection();
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004045 }
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004046 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004047
Douglas Gregorb11f9452012-03-26 16:54:18 +00004048 // Determine whether we are going to search in the various namespaces for
4049 // corrections.
4050 bool SearchNamespaces
Kaelyn Uhrainf4657d52012-04-03 18:20:11 +00004051 = getLangOpts().CPlusPlus &&
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00004052 (IsUnqualifiedLookup || (SS && SS->isSet()));
Richard Smithe156254d2013-08-20 20:35:18 +00004053 // In a few cases we *only* want to search for corrections based on just
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004054 // adding or changing the nested name specifier.
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004055 unsigned TypoLen = Typo->getName().size();
4056 bool AllowOnlyNNSChanges = TypoLen < 3;
4057
Douglas Gregorb11f9452012-03-26 16:54:18 +00004058 if (IsUnqualifiedLookup || SearchNamespaces) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004059 // For unqualified lookup, look through all of the names that we have
4060 // seen in this translation unit.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00004061 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004062 for (IdentifierTable::iterator I = Context.Idents.begin(),
4063 IEnd = Context.Idents.end();
4064 I != IEnd; ++I)
4065 Consumer.FoundName(I->getKey());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004066
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004067 // Walk through identifiers in external identifier sources.
Kaelyn Uhrain1c75d402012-02-07 01:32:58 +00004068 // FIXME: Re-add the ability to skip very unlikely potential corrections.
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004069 if (IdentifierInfoLookup *External
4070 = Context.Idents.getExternalIdentifierLookup()) {
Ahmed Charlesb8984322014-03-07 20:03:18 +00004071 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004072 do {
4073 StringRef Name = Iter->Next();
4074 if (Name.empty())
4075 break;
Douglas Gregor57756ea2010-10-14 22:11:03 +00004076
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004077 Consumer.FoundName(Name);
4078 } while (true);
Douglas Gregor57756ea2010-10-14 22:11:03 +00004079 }
Douglas Gregor2d435302009-12-30 17:04:44 +00004080 }
4081
Richard Smithb3a1df02012-06-08 21:35:42 +00004082 AddKeywordsToConsumer(*this, Consumer, S, CCC, SS && SS->isNotEmpty());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004083
Douglas Gregor280e1ee2010-04-14 20:04:41 +00004084 // If we haven't found anything, we're done.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004085 if (Consumer.empty())
4086 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4087 IsUnqualifiedLookup);
Douglas Gregor2d435302009-12-30 17:04:44 +00004088
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004089 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4090 // is not more that about a third of the length of the typo's identifier.
Kaelyn Uhrain0a16a8e2012-02-14 18:56:48 +00004091 unsigned ED = Consumer.getBestEditDistance(true);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004092 if (ED > 0 && TypoLen / ED < 3)
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004093 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4094 IsUnqualifiedLookup);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004095
Douglas Gregorb11f9452012-03-26 16:54:18 +00004096 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4097 // to search those namespaces.
4098 if (SearchNamespaces) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004099 // Load any externally-known namespaces.
4100 if (ExternalSource && !LoadedExternalKnownNamespaces) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004101 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004102 LoadedExternalKnownNamespaces = true;
4103 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4104 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
4105 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
4106 }
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004107
Kaelyn Uhrainbbfc0572014-03-21 21:54:22 +00004108 for (auto KNPair : KnownNamespaces)
4109 Namespaces.AddNameSpecifier(KNPair.first);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004110
Kaelyn Uhrain0e353552014-02-09 21:47:04 +00004111 bool SSIsTemplate = false;
4112 if (NestedNameSpecifier *NNS =
4113 (SS && SS->isValid()) ? SS->getScopeRep() : 0) {
4114 if (const Type *T = NNS->getAsType())
4115 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
4116 }
Aaron Ballmane42430e2014-03-14 21:11:14 +00004117 for (const auto *TI : Context.types()) {
4118 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
Kaelyn Uhrain5315a462013-10-19 00:04:49 +00004119 CD = CD->getCanonicalDecl();
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004120 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
Kaelyn Uhrain21a66172014-02-05 18:57:51 +00004121 !CD->isUnion() && CD->getIdentifier() &&
Kaelyn Uhrain0e353552014-02-09 21:47:04 +00004122 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
Kaelyn Uhrain5315a462013-10-19 00:04:49 +00004123 (CD->isBeingDefined() || CD->isCompleteDefinition()))
4124 Namespaces.AddNameSpecifier(CD);
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004125 }
4126 }
Douglas Gregor87074f12010-10-20 01:32:02 +00004127 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004128
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004129 // Weed out any names that could not be found by name lookup or, if a
4130 // CorrectionCandidateCallback object was provided, failed validation.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004131 SmallVector<TypoCorrection, 16> QualifiedResults;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004132 LookupResult TmpRes(*this, TypoName, LookupKind);
4133 TmpRes.suppressDiagnostics();
4134 while (!Consumer.empty()) {
4135 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
Benjamin Kramer73faad62012-04-14 08:26:28 +00004136 for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(),
4137 IEnd = DI->second.end();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004138 I != IEnd; /* Increment in loop. */) {
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004139 // If we only want nested name specifier corrections, ignore potential
Kaelyn Uhrainec262992014-03-21 21:54:25 +00004140 // corrections that have a different base identifier from the typo or
4141 // which have a normalized edit distance longer than the typo itself.
4142 if (AllowOnlyNNSChanges) {
4143 TypoCorrection &TC = I->second.front();
4144 if (TC.getCorrectionAsIdentifierInfo() != Typo ||
4145 TC.getEditDistance(true) > TypoLen) {
4146 TypoCorrectionConsumer::result_iterator Prev = I;
4147 ++I;
4148 DI->second.erase(Prev);
4149 continue;
4150 }
Kaelyn Uhrain493ea632012-06-06 20:54:51 +00004151 }
4152
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004153 // If the item already has been looked up or is a keyword, keep it.
4154 // If a validator callback object was given, drop the correction
4155 // unless it passes validation.
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004156 bool Viable = false;
Benjamin Kramera2dcac12012-07-27 10:21:08 +00004157 for (TypoResultList::iterator RI = I->second.begin();
4158 RI != I->second.end(); /* Increment in loop. */) {
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004159 TypoResultList::iterator Prev = RI;
4160 ++RI;
4161 if (Prev->isResolved()) {
4162 if (!isCandidateViable(CCC, *Prev))
Benjamin Kramera2dcac12012-07-27 10:21:08 +00004163 RI = I->second.erase(Prev);
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004164 else
4165 Viable = true;
4166 }
4167 }
4168 if (Viable || I->second.empty()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004169 TypoCorrectionConsumer::result_iterator Prev = I;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004170 ++I;
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004171 if (!Viable)
Benjamin Kramer73faad62012-04-14 08:26:28 +00004172 DI->second.erase(Prev);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004173 continue;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004174 }
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004175 assert(I->second.size() == 1 && "Expected a single unresolved candidate");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004176
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004177 // Perform name lookup on this name.
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004178 TypoCorrection &Candidate = I->second.front();
4179 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00004180 DeclContext *TempMemberContext = MemberContext;
4181 CXXScopeSpec *TempSS = SS;
4182retry_lookup:
4183 LookupPotentialTypoResult(*this, TmpRes, Name, S, TempSS,
4184 TempMemberContext, EnteringContext,
Richard Smithe156254d2013-08-20 20:35:18 +00004185 CCC.IsObjCIvarLookup,
4186 Name == TypoName.getName() &&
4187 !Candidate.WillReplaceSpecifier());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004188
4189 switch (TmpRes.getResultKind()) {
4190 case LookupResult::NotFound:
4191 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain5a43b462011-09-07 20:25:59 +00004192 case LookupResult::FoundUnresolvedValue:
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00004193 if (TempSS) {
4194 // Immediately retry the lookup without the given CXXScopeSpec
4195 TempSS = NULL;
4196 Candidate.WillReplaceSpecifier(true);
4197 goto retry_lookup;
4198 }
4199 if (TempMemberContext) {
4200 if (SS && !TempSS)
4201 TempSS = SS;
4202 TempMemberContext = NULL;
4203 goto retry_lookup;
4204 }
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004205 QualifiedResults.push_back(Candidate);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004206 // We didn't find this name in our scope, or didn't like what we found;
4207 // ignore it.
4208 {
4209 TypoCorrectionConsumer::result_iterator Next = I;
4210 ++Next;
Benjamin Kramer73faad62012-04-14 08:26:28 +00004211 DI->second.erase(I);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004212 I = Next;
4213 }
4214 break;
4215
4216 case LookupResult::Ambiguous:
4217 // We don't deal with ambiguities.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004218 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004219
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004220 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004221 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004222 // Store all of the Decls for overloaded symbols
Kaelyn Uhrainbbfc0572014-03-21 21:54:22 +00004223 for (auto *TRD : TmpRes)
4224 Candidate.addCorrectionDecl(TRD);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004225 ++I;
Kaelyn Uhrainb18b0c02013-07-02 23:47:35 +00004226 if (!isCandidateViable(CCC, Candidate)) {
4227 QualifiedResults.push_back(Candidate);
Benjamin Kramer73faad62012-04-14 08:26:28 +00004228 DI->second.erase(Prev);
Kaelyn Uhrainb18b0c02013-07-02 23:47:35 +00004229 }
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004230 break;
4231 }
4232
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004233 case LookupResult::Found: {
4234 TypoCorrectionConsumer::result_iterator Prev = I;
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004235 Candidate.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004236 ++I;
Kaelyn Uhrainb18b0c02013-07-02 23:47:35 +00004237 if (!isCandidateViable(CCC, Candidate)) {
4238 QualifiedResults.push_back(Candidate);
Benjamin Kramer73faad62012-04-14 08:26:28 +00004239 DI->second.erase(Prev);
Kaelyn Uhrainb18b0c02013-07-02 23:47:35 +00004240 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004241 break;
4242 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004243
4244 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004245 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004246
Benjamin Kramer73faad62012-04-14 08:26:28 +00004247 if (DI->second.empty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004248 Consumer.erase(DI);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004249 else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !DI->first)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004250 // If there are results in the closest possible bucket, stop
4251 break;
4252
4253 // Only perform the qualified lookups for C++
Douglas Gregorb11f9452012-03-26 16:54:18 +00004254 if (SearchNamespaces) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004255 TmpRes.suppressDiagnostics();
Kaelyn Uhrainbbfc0572014-03-21 21:54:22 +00004256 for (auto QR : QualifiedResults) {
4257 for (auto NSI : Namespaces) {
4258 DeclContext *Ctx = NSI.DeclCtx;
4259 const Type *NSType = NSI.NameSpecifier->getAsType();
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004260
4261 // If the current NestedNameSpecifier refers to a class and the
4262 // current correction candidate is the name of that class, then skip
4263 // it as it is unlikely a qualified version of the class' constructor
4264 // is an appropriate correction.
4265 if (CXXRecordDecl *NSDecl =
4266 NSType ? NSType->getAsCXXRecordDecl() : 0) {
Kaelyn Uhrainbbfc0572014-03-21 21:54:22 +00004267 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004268 continue;
4269 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004270
Kaelyn Uhrainbbfc0572014-03-21 21:54:22 +00004271 TypoCorrection TC(QR);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004272 TC.ClearCorrectionDecls();
Kaelyn Uhrainbbfc0572014-03-21 21:54:22 +00004273 TC.setCorrectionSpecifier(NSI.NameSpecifier);
4274 TC.setQualifierDistance(NSI.EditDistance);
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004275 TC.setCallbackDistance(0); // Reset the callback distance
4276
4277 // If the current correction candidate and namespace combination are
4278 // too far away from the original typo based on the normalized edit
4279 // distance, then skip performing a qualified name lookup.
4280 unsigned TmpED = TC.getEditDistance(true);
Kaelyn Uhrainbbfc0572014-03-21 21:54:22 +00004281 if (QR.getCorrectionAsIdentifierInfo() != Typo &&
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004282 TmpED && TypoLen / TmpED < 3)
4283 continue;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004284
4285 TmpRes.clear();
Kaelyn Uhrainbbfc0572014-03-21 21:54:22 +00004286 TmpRes.setLookupName(QR.getCorrectionAsIdentifierInfo());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004287 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
4288
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004289 // Any corrections added below will be validated in subsequent
4290 // iterations of the main while() loop over the Consumer's contents.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004291 switch (TmpRes.getResultKind()) {
Kaelyn Uhrainb18b0c02013-07-02 23:47:35 +00004292 case LookupResult::Found:
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004293 case LookupResult::FoundOverloaded: {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00004294 if (SS && SS->isValid()) {
4295 std::string NewQualified = TC.getAsString(getLangOpts());
4296 std::string OldQualified;
4297 llvm::raw_string_ostream OldOStream(OldQualified);
4298 SS->getScopeRep()->print(OldOStream, getPrintingPolicy());
4299 OldOStream << TypoName;
4300 // If correction candidate would be an identical written qualified
4301 // identifer, then the existing CXXScopeSpec probably included a
4302 // typedef that didn't get accounted for properly.
4303 if (OldOStream.str() == NewQualified)
4304 break;
4305 }
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004306 for (LookupResult::iterator TRD = TmpRes.begin(),
4307 TRDEnd = TmpRes.end();
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004308 TRD != TRDEnd; ++TRD) {
4309 if (CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4310 NSType ? NSType->getAsCXXRecordDecl() : 0,
Eli Friedman3be1a1c2013-10-01 02:44:48 +00004311 TRD.getPair()) == AR_accessible)
Kaelyn Uhrain95995be2013-09-26 19:10:29 +00004312 TC.addCorrectionDecl(*TRD);
4313 }
4314 if (TC.isResolved())
4315 Consumer.addCorrection(TC);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004316 break;
Kaelyn Uhrain5986c3e2012-02-15 22:14:18 +00004317 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004318 case LookupResult::NotFound:
4319 case LookupResult::NotFoundInCurrentInstantiation:
4320 case LookupResult::Ambiguous:
Kaelyn Uhrain5a43b462011-09-07 20:25:59 +00004321 case LookupResult::FoundUnresolvedValue:
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004322 break;
4323 }
4324 }
4325 }
4326 }
4327
4328 QualifiedResults.clear();
4329 }
4330
4331 // No corrections remain...
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004332 if (Consumer.empty())
4333 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004334
Kaelyn Uhrain34fab552012-05-31 23:32:58 +00004335 TypoResultsMap &BestResults = Consumer.getBestResults();
4336 ED = Consumer.getBestEditDistance(true);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004337
Kaelyn Uhrain653ff242013-10-02 18:26:35 +00004338 if (!AllowOnlyNNSChanges && ED > 0 && TypoLen / ED < 3) {
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004339 // If this was an unqualified lookup and we believe the callback
4340 // object wouldn't have filtered out possible corrections, note
4341 // that no correction was found.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004342 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4343 IsUnqualifiedLookup && !ValidatingCallback);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004344 }
4345
Douglas Gregor0afa7f62010-10-14 20:34:08 +00004346 // If only a single name remains, return that result.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004347 if (BestResults.size() == 1) {
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004348 const TypoResultList &CorrectionList = BestResults.begin()->second;
4349 const TypoCorrection &Result = CorrectionList.front();
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004350 if (CorrectionList.size() != 1)
4351 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004352
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00004353 // Don't correct to a keyword that's the same as the typo; the keyword
4354 // wasn't actually in scope.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004355 if (ED == 0 && Result.isKeyword())
4356 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004357
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004358 // Record the correction for unqualified lookup.
4359 if (IsUnqualifiedLookup)
4360 UnqualifiedTyposCorrected[Typo] = Result;
4361
David Blaikie04ea41c2012-10-12 20:00:44 +00004362 TypoCorrection TC = Result;
4363 TC.setCorrectionRange(SS, TypoName);
Richard Smithe156254d2013-08-20 20:35:18 +00004364 checkCorrectionVisibility(*this, TC, TypoName.getName());
David Blaikie04ea41c2012-10-12 20:00:44 +00004365 return TC;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004366 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00004367 else if (BestResults.size() > 1
4368 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4369 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4370 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4371 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00004372 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004373 && BestResults["super"].front().isKeyword()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004374 // Prefer 'super' when we're completing in a message-receiver
4375 // context.
4376
4377 // Don't correct to a keyword that's the same as the typo; the keyword
4378 // wasn't actually in scope.
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004379 if (ED == 0)
4380 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004381
Douglas Gregor87074f12010-10-20 01:32:02 +00004382 // Record the correction for unqualified lookup.
4383 if (IsUnqualifiedLookup)
Kaelyn Uhrainba896f12012-06-01 18:11:16 +00004384 UnqualifiedTyposCorrected[Typo] = BestResults["super"].front();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004385
David Blaikie04ea41c2012-10-12 20:00:44 +00004386 TypoCorrection TC = BestResults["super"].front();
4387 TC.setCorrectionRange(SS, TypoName);
4388 return TC;
Douglas Gregoraf9eb592010-10-15 13:35:25 +00004389 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004390
Kaelyn Uhraincb7a0402012-01-23 20:18:59 +00004391 // If this was an unqualified lookup and we believe the callback object did
4392 // not filter out possible corrections, note that no correction was found.
4393 if (IsUnqualifiedLookup && !ValidatingCallback)
Douglas Gregor87074f12010-10-20 01:32:02 +00004394 (void)UnqualifiedTyposCorrected[Typo];
4395
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00004396 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004397}
4398
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004399void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4400 if (!CDecl) return;
4401
4402 if (isKeyword())
4403 CorrectionDecls.clear();
4404
Kaelyn Uhrainf60b55a2012-11-19 18:49:53 +00004405 CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00004406
4407 if (!CorrectionName)
4408 CorrectionName = CDecl->getDeclName();
4409}
4410
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004411std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4412 if (CorrectionNameSpec) {
4413 std::string tmpBuffer;
4414 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4415 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
David Blaikied4da8722013-05-14 21:04:00 +00004416 PrefixOStream << CorrectionName;
Benjamin Kramer73faad62012-04-14 08:26:28 +00004417 return PrefixOStream.str();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004418 }
4419
4420 return CorrectionName.getAsString();
Douglas Gregor2d435302009-12-30 17:04:44 +00004421}
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00004422
4423bool CorrectionCandidateCallback::ValidateCandidate(const TypoCorrection &candidate) {
4424 if (!candidate.isResolved())
4425 return true;
4426
4427 if (candidate.isKeyword())
4428 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4429 WantRemainingKeywords || WantObjCSuper;
4430
4431 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
4432 CDeclEnd = candidate.end();
4433 CDecl != CDeclEnd; ++CDecl) {
4434 if (!isa<TypeDecl>(*CDecl))
4435 return true;
4436 }
4437
4438 return WantTypeSpecifiers;
4439}
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004440
4441FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004442 bool HasExplicitTemplateArgs,
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004443 MemberExpr *ME)
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004444 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004445 CurContext(SemaRef.CurContext), MemberFn(ME) {
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004446 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
4447 WantRemainingKeywords = false;
4448}
4449
4450bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4451 if (!candidate.getCorrectionDecl())
4452 return candidate.isKeyword();
4453
4454 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
4455 DIEnd = candidate.end();
4456 DI != DIEnd; ++DI) {
4457 FunctionDecl *FD = 0;
4458 NamedDecl *ND = (*DI)->getUnderlyingDecl();
4459 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4460 FD = FTD->getTemplatedDecl();
4461 if (!HasExplicitTemplateArgs && !FD) {
4462 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4463 // If the Decl is neither a function nor a template function,
4464 // determine if it is a pointer or reference to a function. If so,
4465 // check against the number of arguments expected for the pointee.
4466 QualType ValType = cast<ValueDecl>(ND)->getType();
4467 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4468 ValType = ValType->getPointeeType();
4469 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
Alp Toker9cacbab2014-01-20 20:26:09 +00004470 if (FPT->getNumParams() == NumArgs)
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004471 return true;
4472 }
4473 }
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004474
4475 // Skip the current candidate if it is not a FunctionDecl or does not accept
4476 // the current number of arguments.
4477 if (!FD || !(FD->getNumParams() >= NumArgs &&
4478 FD->getMinRequiredArguments() <= NumArgs))
4479 continue;
4480
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004481 // If the current candidate is a non-static C++ method, skip the candidate
4482 // unless the method being corrected--or the current DeclContext, if the
4483 // function being corrected is not a method--is a method in the same class
4484 // or a descendent class of the candidate's parent class.
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004485 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004486 if (MemberFn || !MD->isStatic()) {
4487 CXXMethodDecl *CurMD =
4488 MemberFn
4489 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
4490 : dyn_cast_or_null<CXXMethodDecl>(CurContext);
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +00004491 CXXRecordDecl *CurRD =
4492 CurMD ? CurMD->getParent()->getCanonicalDecl() : 0;
4493 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
4494 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
4495 continue;
4496 }
4497 }
4498 return true;
Kaelyn Uhrain53e72192013-07-08 23:13:39 +00004499 }
4500 return false;
4501}
Richard Smithf9b15102013-08-17 00:46:16 +00004502
4503void Sema::diagnoseTypo(const TypoCorrection &Correction,
4504 const PartialDiagnostic &TypoDiag,
4505 bool ErrorRecovery) {
4506 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
4507 ErrorRecovery);
4508}
4509
Richard Smithe156254d2013-08-20 20:35:18 +00004510/// Find which declaration we should import to provide the definition of
4511/// the given declaration.
4512static const NamedDecl *getDefinitionToImport(const NamedDecl *D) {
4513 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4514 return VD->getDefinition();
4515 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4516 return FD->isDefined(FD) ? FD : 0;
4517 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
4518 return TD->getDefinition();
4519 if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
4520 return ID->getDefinition();
4521 if (const ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
4522 return PD->getDefinition();
4523 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
4524 return getDefinitionToImport(TD->getTemplatedDecl());
4525 return 0;
4526}
4527
Richard Smithf9b15102013-08-17 00:46:16 +00004528/// \brief Diagnose a successfully-corrected typo. Separated from the correction
4529/// itself to allow external validation of the result, etc.
4530///
4531/// \param Correction The result of performing typo correction.
4532/// \param TypoDiag The diagnostic to produce. This will have the corrected
4533/// string added to it (and usually also a fixit).
4534/// \param PrevNote A note to use when indicating the location of the entity to
4535/// which we are correcting. Will have the correction string added to it.
4536/// \param ErrorRecovery If \c true (the default), the caller is going to
4537/// recover from the typo as if the corrected string had been typed.
4538/// In this case, \c PDiag must be an error, and we will attach a fixit
4539/// to it.
4540void Sema::diagnoseTypo(const TypoCorrection &Correction,
4541 const PartialDiagnostic &TypoDiag,
4542 const PartialDiagnostic &PrevNote,
4543 bool ErrorRecovery) {
4544 std::string CorrectedStr = Correction.getAsString(getLangOpts());
4545 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
4546 FixItHint FixTypo = FixItHint::CreateReplacement(
4547 Correction.getCorrectionRange(), CorrectedStr);
4548
Richard Smithe156254d2013-08-20 20:35:18 +00004549 // Maybe we're just missing a module import.
4550 if (Correction.requiresImport()) {
4551 NamedDecl *Decl = Correction.getCorrectionDecl();
4552 assert(Decl && "import required but no declaration to import");
4553
4554 // Suggest importing a module providing the definition of this entity, if
4555 // possible.
4556 const NamedDecl *Def = getDefinitionToImport(Decl);
4557 if (!Def)
4558 Def = Decl;
4559 Module *Owner = Def->getOwningModule();
4560 assert(Owner && "definition of hidden declaration is not in a module");
4561
4562 Diag(Correction.getCorrectionRange().getBegin(),
4563 diag::err_module_private_declaration)
4564 << Def << Owner->getFullModuleName();
4565 Diag(Def->getLocation(), diag::note_previous_declaration);
4566
4567 // Recover by implicitly importing this module.
4568 if (!isSFINAEContext() && ErrorRecovery)
4569 createImplicitModuleImport(Correction.getCorrectionRange().getBegin(),
4570 Owner);
4571 return;
4572 }
4573
Richard Smithf9b15102013-08-17 00:46:16 +00004574 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
4575 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
4576
4577 NamedDecl *ChosenDecl =
4578 Correction.isKeyword() ? 0 : Correction.getCorrectionDecl();
4579 if (PrevNote.getDiagID() && ChosenDecl)
4580 Diag(ChosenDecl->getLocation(), PrevNote)
4581 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
4582}